This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

Forms - GET & POST


Forms is where you start to actually have some fun! This is where you start your journey from static webpages, to dynamic webpages. PHP Forms is why we've had to go through all the previous classes and learn some, not-so-fun stuff.
To catch everybody up, so we're all on the same level right now, a form is what holds those little boxes on websites that you put your information on.
ie: registration form has your name, email and password.
Up until now, any static web site you've made most likely can't do anything with a form. For now, we're going to stick with the two basic types of forms: GET and POST.

Let's move in to our first section,

Post Method

Save the code below as info.html

 

<html>
<body>

<form method='post' action='do.php'>
What is your name? <input type='text' name='my_name' /><br />
What is your favorite color? <input type='text' name='fav_color' /><br />
<input type='submit' />
</form>

</body>
</html>

The red areas above are the parts that are probably new to you.
Method is the type of form we use, GET or POST.
Action is the file we want to execute when someone hit the submit button.
Name is what we will be naming the variable the PHP makes for us.
These 3 keys are extremely important!

Now copy and save the code below as do.php:

<html>
<body>

Hello <?=$_POST['my_name']; // shorthand echo command ?>
who likes the color <?=$_POST['fav_color']; // shorthand echo command ?>

</body>
</html>

Upload do.php and info.html into the same directory, and open http://yourwebsite.com/info.html
Type in your information and hit "submit".

After you hit the submit button, notice your URL changed to do.php, and it has your information you put inside the form!
But wait.. if you just went to http://yourwebsite.com/do.php, your page would display: Hello who likes the color. Why does it do this?
The $_POST superglobal variable is only created when you submit the form.
If you didn't notice, the name you gave your input field is what your $_POST variable was named.

Why should I use $_POST?
$_POST is more secure than $_GET, because $_GET (or method="get") urlencodes the inputs.

Get Method

Like I said, the main difference between $_POST and $_GET is that $_GET turns your inputs into a URL.

 

Open info.html again, and change the form method to get, and save it.
Open do.php again, and change $_POST['my_name'] to$_GET['my_name']
                  and change $_POST['fav_color'] to$_GET['fav_colour'].
Upload both files, and open info.html in your browser.
Input your information and hit submit..... Looks like there's no difference..
But if you look at your URL, it should say something like http://yourwebsite/do.php?my_name=dave&fav_color=red.

After do.php is a question mark "?", followed by your form's field name this is equal to your input. The AND "&" symbol in your URL means it's connected another $_GET variable to your page.
The "?" means that PHP will start looking for a variable in the URL.
ie: yourpage.php?variable=value&variable2=second_value

<form method='get' action='do.php'>The GET method
What is your name? <input type='text' name='my_name' /><br /> my_name is in the URL
What is your favorite color? <input type='text' name='fav_color' /><br /> fav_color is in the URL
<input type='submit' />
</form>

Another Option:

Instead of using $_POST and $_GET, you can also use $_REQUEST. $_REQUEST can get information from get and post methods, and even cookies.

Your task:
Create a different html page that has a form with 3 or more input fields.
When you "submit" your form, the new page will echo the text you gave the form.
Do this using the get method, and the post method.

Task Discussion


  • Tynanh   March 27, 2013, 12:51 a.m.

    My form code is here

    forms.php

  • katpal   July 14, 2012, 12:13 p.m.

    Hi,

    quesiton A:

    isn't there a way to collect all form elements automatically (inputs, options etc) and use:

    1. their "name" values -  as the title

    2. their values - as the value

    to produce clear data?

    e.g. Name: Paul Simon

    I tried to do that with javascript (for just the input elements) but did not know how to pass the values to the do.php file

    I have this in the head section of the form.html document

    function getForm() {    
    var str='';    
    var inputs=document.getElementById("myForm").getElementsByTagName('input');
    var i;
    for (i=0; i<inputs.length; i++) {
        str+=inputs[i].name + "=&nbsp";
        str+=inputs[i].value + "&nbsp";
        str+=inputs[i].checked;
        str+=inputs[i].type + "&nbsp";
        str+="<br>";        
    }
    alert (str);
    
    
    ----------------------------------

    Question B:

    How can we send this data by email?

     

    Can you point me to any site that has step-by-step tutorial on how to achieve the  above 2? thanks,

    k.

  • MiniDawg   July 14, 2012, 3:20 p.m.
    In Reply To:   katpal   July 14, 2012, 12:13 p.m.

    On the POST/GET page you can write:

    foreach($_POST as $K => $V) {
        echo $K . " is my Key and " . $V . " is my value <br />";
    }

    $K is the key and $V is the value. You can play and manipulate this in anyway you see fit. 

     

    Hope this helps. 

  • katpal   July 15, 2012, 2:53 a.m.
    In Reply To:   MiniDawg   July 14, 2012, 3:20 p.m.

    Hi Mini,

    thanks for the reply. That part I got already. But you still have to declare the variables one by one manually eg

    $data = array('Title:' => 'title', 'Name: ' => 'name', 'Surname: ' => 'surname', 'Date of birth: ' => 'birthday')

    I want to find a way so that all control names and values are listed automatically in one array...

    is this possible?

     

    K.

  • MiniDawg   July 15, 2012, 1:15 p.m.
    In Reply To:   katpal   July 15, 2012, 2:53 a.m.

    In that case, you can declare the variable in an array variable. Like so:

    foreach($array as $key => $value) {
        $array[$key] = $value;
    }

    and that will give you variables like $array['MyName'] = "Kalob"; 
    Or if you are trying to create a variable with the form name, you can use the name as the variable name by referencing it like so:

    	$arr = array("Me" => 22, "You" => 24, "Friend" => 21);
    foreach($arr as $k => $v) {
        ${$k} = $v;
    }
    
    echo "I am " . $Me . " years old";

    And that will give you variable names of $Me, $You and $Friend. 

    Did that answer the question? 

  • Asier Iturralde Sarasola   April 15, 2012, 11:55 a.m.

    For my task I wrote a form to registrate new users.

    The new user enters his/her data (username, password, confirmation of the password and if he/she accepts the conditions) and the php script validates the values:

    • The username can't be empty.
    • The password must be at least 8 characters long.
    • The password must match the confirmation of the password.
    • The new user must accept the conditions.

    If all the requirements are fulfilled the new user gets a welcome message else gets a error message.

    My code using GET:

    My code using POST:

    Any recommendations on how to sanitize user inputs to avoid SQL injections?

  • Anonym   Jan. 13, 2012, 9:57 p.m.

    Hey Calob!

    I created a multple-choice quiz using form with php code embedded in html.  Everything works, except the "reset" button.  It works before submitting the answers, but doesn't work after submitting the answers.  I googled around for a solution to this problem, and tried

    if($_POST["reset"]{

       $_POST=""; }

    But it didn't work.  It didn't clear the post array content.  I also tried

    unset($_POST);

    to no avail.  How can I get the reset button to work after submission?  Thanks! Demian

  • [Hidden]   Jan. 14, 2012, 2:28 a.m.
    In Reply To:   Anonym   Jan. 13, 2012, 9:57 p.m.

    a few options. You can use <button type='reset'></button>. 

    Doing it your way though, i'd be more specific with the unset. Try something like:

    if(isset($_POST['reset'])) {
        // reset
        unset($_POST['reset']);
    }

    Why? Because using unset on $_POST[] can unset all the post variables, and in the future you might need them for your app. 

    Im also not sure if that was a copy & paste you wrote, but if it is, your code won't work because of Line #1: There's no closing bracket after $_POST["reset"].

    Hope this helps!

  • Richard   Dec. 10, 2011, 8:07 a.m.

    I'm lost at::

    "Try this: change the last part of your URL.
    ie: change red to PHP+Forms (Read a little on urlencoding and urldecoding if you can't wait to figure out why the "+" symbol made a space)
    Your page changes!! As easy as that!"

    Was fine up to this part -now change URL???

    My url=

    http://localhost/learnphp/do.php?my_name=thechard&fav_color=blue

    What do I change?....any help appreciated-thanks

    MY EDIT....

    So far my best way to get this to work is:

    <?php    echo "my name is ";
    echo $_POST["name"];
    echo "<br />";
    echo "my fav color is ";
    echo $_POST["fav_color"];
    ?>

  • Richard   Dec. 10, 2011, 9:42 a.m.
    In Reply To:   [Hidden]   Dec. 10, 2011, 8:47 a.m.

    Thanks for your reply-I tried the enter key & nothing happens-I try the browser refresh & nothing happens-I think I have misunderstood-can you explain more? Thanks

  • [Hidden]   Dec. 10, 2011, 5:07 p.m.
    In Reply To:   Richard   Dec. 10, 2011, 9:42 a.m.

    make sure 
    <form method='get' action='do.php'>..

    then you need to change your code to $_GET instead of $_POST. 
    method='get'         $_GET['my_input_name']
    method='post'       $_POST['my_input_name']

    Alternatively, you can use $_REQUEST['variable_name'] to get both $_GET and $_POST, it's not recommended though.

  • Richard   Dec. 11, 2011, 7:52 a.m.
    In Reply To:   [Hidden]   Dec. 10, 2011, 5:07 p.m.

    Kalob -I have done that (eg using $GET)-the problem I have is changing the URL & your first suggestion of using enter did not work.

    I only get this output:

    Hello who likes the color

    http://localhost/learnphp/newdo.php?my_name=thechard&fav_color=PHP+Forms

    I do not understand-sorry...