Understanding the basic of HTML form and PHP GET and POST method

The idea of this post originated from the topic, using PHP GET and POST method simultaneously via a single form. While writing about the tutorial, I felt that, one need to know the basics of HTML forms and PHP suparglobal POST and GET variables to understand how HTTP interaction takes place in between user and the Server.

The most useful feature of any server side scripting language is the interactive capability of receiving and processing user data. Obviously, the data is to be sent from the browser through HTTP and it can be done via two methods. One is GET and another is POST. We will get into them soon, but before that, here are the download package and demo link for advanced users!

Demo[download id=”7″ format=”1″]

Now let us start from the very beginning of the concept behind HTTP transactions…

#0: The concepts behind HTTP data transaction:

  • User can not send data to the server without using some HTTP method. (till now)
  • There are two HTTP methods, GET and POST.
  • In GET method, the data is sent over as URL variables. So, it is shown on the browser and there is a limitation for the total data to be sent. In general, a URL with GET data looks like http://example.com/actions.php?pmode=admin&do=accept_user&user_name=john&email=abc@abc.com. The bold parts are the GET parameters and the italic parts are the value of those parameters. More than one parameter=value can be embedded in the URL by concatenating with ampersands(&). One can only send simple text data via GET method. The advantage is, the URL is bookmarkable while using GET method.
  • In POST method the data is sent completely in the background. There is no limitation for the data sent to the server (except for the limitation imposed by the server itself) and one can send text data as well as binary data (uploading a file) using POST. The URL is not bookmarkable in this case.
  • Normally people use HTML FORM to interact using GET or POST. This are the default Browser Methods one can use. But it is also possible to directly send data by typing in the URL for GET method and using some advanced HTTP technique for POST method. We will discuss about them sometime later.
  • Be it POST or GET, PHP is able to fetch them using two superglobal array variables $_POST and $_GET. The subscripts of the arrays are the name of the HTML form fields, or the parameters of the URL (for GET). Say, you have a HTML input box of text type, inside a form with POST method. If the name of that particular input box is “user_name” then it can be accessed via the superglobal $_POST[‘user_name’]. Similarly, we can use $_GET[‘user_name’] for GET method.

So, those were the basics… Let us now jump into the code structure.

#1: Understanding the Structure of HTML forms:

The basic structure of a HTML form looks like this:

<form action="action.php" method="post">
    <input type="text" name="user" id="user" value="Your name" />
    <input type="text" name="age" id="age" value="Your Age" />
    <select name="sex" id="sex">
        <option value="female">Female</option>
        <option value="male">Male</option>
    </select>
    <input type="submit" value="Submit" />
</form>

Here are the explanations of the attributes:

  • form » action: This is script where HTTP data would be sent. It is just the URL (relative or absolute, here we have used relative) of the script file.
  • form » method: The HTTP method to send the data. It can be GET or POST. In XHTML we write in lowercase, ie get or post.
  • form » input/select: These are the HTML fields for the users to enter or select data. There are various form elements. A detailed information is available here.
  • form » input » name: This is the unique name of the field. This will be used to get the data from the action.php script.
  • form » input » id: The unique id of the element. Mainly used to access the DOM or use as CSS selector. We have a detailed tutorial here.

#2: Simple PHP script to fetch the form input datas:

Based on the above form, the code inside the action.php can be something like this… I have commented them for better understanding, so go through the code very carefully…

<?php
/** Get the POST variables using $_POST superglobal */
/**
 * Every HTTP POST data is stored inside the $_POST array
 * We need to get them using proper subscript of the $_POST array
 * The subscript is same as the name of the form field
 * So the value entered in <input type="text" name="my_name" /> can be accessed via $_POST['my_name']
 * Similarly all the values get stored inside the $_POST superglobal array
 * It is known as SuperGlobal because it is made global by PHP itself
 * So $_POST can be used within a function or directly as well
 */
$user_name = $_POST['user'];
$user_age = $_POST['age'];
$user_sex = $_POST['sex'];

/** Now output the Information we have got from $_POST */
/** The period (.) concatenate the string */
echo '<p>Hi ' . $user_name . ' . You told us that you are a ' . $user_sex . ' of age ' . $user_age . '</p>';
?>

That was simple right? Basically, We can do the same with GET as well. In that case we need to change the method of the form to get and use $_GET superglobal instead. Have a look…

#3: The similar code for GET method:

#3.1: The HTML form:

<form action="action_get.php" method="get">
    <input type="text" name="user" id="user" value="Your name" />
    <input type="text" name="age" id="age" value="Your Age" />
    <select name="sex" id="sex">
        <option value="female">Female</option>
        <option value="male">Male</option>
    </select>
    <input type="submit" value="Submit" />
</form>

#3.2: The actions_get.php file:

<?php
/** Get the GET variables using $_GET superglobal */
/**
 * Every HTTP GET data is stored inside the $_GET array
 * We need to get them using proper subscript of the $_GET array
 * The subscript is same as the name of the form field
 * So the value entered in <input type="text" name="my_name" /> can be accessed via $_GET['my_name']
 * Similarly all the values get stored inside the $_GET superglobal array
 * It is known as SuperGlobal because it is made global by PHP itself
 * So $_GET can be used within a function or directly as well
 * We will pass each $_GET variable through a function urldecode
 * This is because every browser encodes the user input from the html form
 * We need to decode them using urldecode function to get the exact user input
 */
$user_name = urldecode( $_GET['user'] );
$user_age = urldecode( $_GET['age'] );
$user_sex = urldecode( $_GET['sex'] );

/** Now output the Information we have got from $_POST */
/** The period (.) concatenate the string */
echo '<p>Hi ' . $user_name . ' . You told us that you are a ' . $user_sex . ' of age ' . $user_age . '</p>';
?>

Note that we have wrapped every $_GET inside a special function urldecode. This is because web browsers encode the user input while using the get method. So, we need to decode them for getting the exact value.

Also, there are occasions when we need to strip off slashes from the input for both GET and POST. But, it will be better if we discuss about that later and keep this tutorial simple.

#4: A sneak peak to an advance script using HTTP POST method:

Now that you have got the very basic idea about using HTTP get and POST, let us see an advanced usage. I have commented the whole script for better understanding.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Basic Usage of PHP POST</title>
</head>
<body>
<div>
    <fieldset>
        <legend>Enter your Information</legend>
        <form method="post" action="">
            <p>
                <label for="user_name_post">Your Name: &raquo;</label>
                <input type="text" name="user_name_post" id="user_name_post" value="Enter name" />
            </p>
            <p>
                <label for="user_age_post">Your Age: &raquo;</label>
                <input type="text" name="user_age_post" id="user_age_post" value="Age in Years" />
            </p>
            <p>
                <label for="user_sex_post">Your Sex: &raquo;</label>
                <select name="user_sex_post" id="user_sex_post">
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                </select>
            </p>
            <p>
                <label for="user_email_post">Your Email: &raquo;</label>
                <input type="text" name="user_email_post" id="user_email_post" value="yourname@company.com" />
            </p>
            <p>
                <label for="user_text_post">Any Message? &raquo;</label>
                <textarea name="user_text_post" id="user_text_post"></textarea>
            </p>
            <p>
                <input type="submit" value="POST it" />
            </p>
        </form>
    </fieldset>
</div>
<div>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') { //Check to see if POST has been performed or not
    /** Store the POST data to some variable */
    $user_name = $_POST['user_name_post'];
    $user_age = $_POST['user_age_post'];
    $user_sex = $_POST['user_sex_post'];
    /**
     * Now output the post data
     * It is not necessary to store every post data to a variable
     * So, we have directly echoed $_POST['user_text_post']
     */
    ?>
    <div class="response">
        <h4>POST Response Found</h4>
        <p>Hi <?php echo $user_name; ?>. You are a <?php echo $user_sex; ?> of age <?php echo $user_age; ?> years</p>
        <p>You have left a message:</p>
        <blockquote>
            <p><?php echo $_POST['user_text_post']; ?></p>
        </blockquote>
    </div>
    <?php
}
else {
    ?>
    <p>No Response Yet!</p>
    <?php
}
?>
</div>
</body>

Basically, it uses the same script and we have set the form action to “” . It tells the browser to submit the form the current URL (With or the existing URL parameters).

Demo[download id=”7″ format=”1″]

And that was all! Don’t forget to give a look to our online Demo and download the complete package! Do give us your feedback and if you have any doubt, feel free to ask.

External Resources:

2 comments

  1. Pingback: Using PHP GET and POST simultaneously via single HTML form | InTechgrity

Comments are closed.