Capable SEO

PHP Posts and Redirects

Now we’re going to add in some functionality to your php. We’ll make a form which checks a person’s age then either redirects them to a different page, or displays an error message.

  1. First off is some html code for a form, the form will send via post method one variable for age.
    <form method=”post”>Age <input name=”age” type=”text” id=”age”></form>
  2. So now you’ve got a basic form that has a field for age. Now lets put in some a php code area and get started <?php ?>
  3. Now we need to put a variable there to catch whatever is posted back to the document. You can assign a vairable to a post like in the example.
    <?php
    /*$_POST is the method for describing a posted variable, then you describe the id of
    the variable within the [' '] tags.*/
    $age=$_POST['age'];
    echo
    "Age: $age";
    ?>

    This should print out Age: if you just start the page, and if you submit an age it will say Age: [your age here].

  4. Now lets add in a simple if statement determining if the age is below a certain point, if it is say below 13 we’ll assign a variable $error a sentence detailing how this site is made for those 13 or above.
    <?php
    $age
    =$_POST['age'];
    if (
    $age<13) {$error="Sorry this site is only for those aged 13 or above."}
    /* just having the variable in an if statement's ()s checks to see if the
    variable has been assigned anything or not. If it has it will run the statement.*/
    if ($error) {echo $error;}
    ?>

    Depending on what you submit to the page this will either print nothing or it will print Sorry this site is only for those aged 13 or above.

  5. Lets add in an else statement so that if they are able to see the site it will tell them that the site is redirecting them there now.
    <?php
    $age
    =$_POST['age'];
    if (
    $age<13) {$error="Sorry this site is only for those aged 13 or above."}
    if (
    $error) {echo $error;}
    else { echo
    "Your old enough to view the site, redirecting you now.";}
    ?>

    This will either tell the person they’re too young or tell them they’re old enough and the site is redirecting.

  6. The final part of the script is actually redirecting a person if they are of the correct age. So add in the following code to the redirect. header(’Location: http://www.example.com/’);
    <?php
    $age
    =$_POST['age'];
    if (
    $age<13) {$error="Sorry this site is only for those aged 13 or above."}
    if (
    $error) {echo $error;}
    else { echo
    "Your old enough to view the site, redirecting you now.";
    //remember you would be changing example.com below to whatever url you need.
    header('Location: http://www.example.com/');}
    ?>

    This will either tell you that your not old enough or redirect you to http://www.example.com, This lesson is now over.

Capable SEO