by Dinesh Thakur Category: PHP (Hypertext Preprocessor)

That says "dynamic website" generally called "forms" and therefore treatment of these. PHP was invented especially for this type of task and that is what we will discuss in this new tutorial. We will learn to use the forms via the superglobal arrays $ _GET and $ _POST. We will also determine the difference in the use of each of them.


[1] For the remainder of the tutorial, we will assume that the basics about HTML forms are acquired. We only deal with synthetically the main points of these to know the names, values, enctypes and methods.
[2] Moreover we will assume that all previous tutorials PHP basics are understood and acquired.

PHP or Javascript therapy treatment?

It is obvious that ALL forms must be given priority with PHP. However, nothing prevents the use of Javascript as an overlay to the work of PHP. Why PHP priority then? It there's several reasons for this:

• PHP is executed on the server when JavaScript is executed on the client (browser). Therefore, it may be disabled or nonfunctional resulting in loss of control.
• Being executed on the server, only the program can act on the information transmitted. Security is increased when compared to client side controls.
• PHP has a series of built-in functions can manipulate variables and control.
• The power of regular expressions also verifies custom data formats.

Note: since the information comes from anonymous people, we can not guarantee the veracity and dangerousness of these. That is why everything has to be checked. The principle number 1 when a user interacts with is to never trust him.

The essential parts of a form


To be able to communicate properly with an HTML form PHP script, you must ensure that the following are present:

• The action of the <form> tag attribute is the URL of the PHP file that will receive the information. This may be a different file from the current page, but it is advisable to process forms on the same page.
• HTTP method (method attribute) of the form is filled by one of these two values: GET or POST.
• If one is dealing with a file upload form, the <form> tag must have the attribute and value enctype multipart / form-data.
• All elements of a form must have a name attribute filled with a value. The field name will then be considered by the PHP script as a variable containing the entered value.

For information, here is a simple example of this form to upload all required elements discussed here.

Example upload form

<! - Debut of form ->
<form enctype = "multipart / form-data" action = "./ upload.php" method = "post">
           <legend> Form </ legend>
                         <label> Send File: </ label>
                         <input name = type = "file", "file" />
                         <input type = "submit" name = "submit" value = "Uploader" />
                </ p>
     </ fieldset>
</ form>
<! - End of form ->


Detail here GET and POST methods. What difference between them? Why choose?

The HTTP GET method

GET (the one used by default if nothing is entered) circulates the information in unencrypted form in the address bar by following the following formats:

Url instance created from the GET method of a form


This address means we will send the page codephp.php variable / value pairs passed as parameter. The first variable of a url is always preceded by the symbol? while others will be preceded by the symbol &. Variable names correspond to the name attributes of the form elements and values ​​to value attributes.

Note: contrary to what we read frequently on the canvas, the maximum limit of a URL is 255 characters. There is actually no standard limit. Indeed, the maximum size of a URL may be set up on both server side or client side. A web server administrator can at will increase or decrease the maximum length of URLs. As for browsers, also set a default maximum size. It is therefore recommended not to abuse the length of a URL when you do not control its entire production environment (Web server and clients).

The HTTP POST method

The POST method, in turn, passes the information of hidden way but unencrypted form. The failure to display data in no way means they are encrypted. Recall also that this information use HTTP and not HTTPS, which encrypts her data.

What is the best approach then? Well, the answer is "it depends." The choice of one or the other will depend on the context. If for example we wish to set up a search engine then we can content ourselves with the GET method which will forward the keywords in the URL. This will also enable us to provide the search URL to others. This is typically the case of the Google URLs:

Example of a Google search engine URL

The POST method is preferred when there's a large number of data to be transmitted or when to send sensitive data like passwords. In some cases, only the POST method is required: a file upload example.

Superglobal arrays $ _POST and $ _GET

$ _GET And $ _POST arrays are associative and Superglobal data. Here are their main features:

• They are generated on the fly by PHP even before the first line of the script is executed.
• These are associative arrays like those traditionally says. Their handling is exactly like these. The keys are the names of variables and values ​​transmitted to those associated with these variables.
• They are Superglobal, that is visible from anywhere in the program (even within a user function).
• They are read and write. It is therefore possible to modify them.

$ _GET Array contains all the variable / value pairs passed in the url. To access the value of a variable whose name is first name, it is so called:

Playing a variable belonging to the $ _GET array
<? php
   echo $_GET ['firstname'];

$ _POST Array contains all the variable / value pairs sent in POST, that is, information that does come from either the URL or cookies nor sessions. To access the value of a variable whose name is first name, it is so called:

Playing a variable belonging to the $ _POST
<? php
    echo $_POST ['firstname'];

The case of the variables is important. We must think about putting $_GET and $_POST uppercase. Otherwise it will be impossible to get an undefined value and variable type of error will be returned.

Note: there are also the superglobal $_REQUEST associative array which includes the 3 arrays $_GET, $_POST and $_COOKIE that we will see the next class. It works just like all other tables.

Simple and practical example of form processing

In this part, we will use a simple example of a form of treatment. We will collect and verify the data from an authentication form. Session of the principles will be squeezed out because they are not the main subject of the course. We will focus only on the entry and receipt of the form data.

Here are the prerequisites needed for the development of our example:

• An identification form needs two components: a text field that receives the login and a password field that receives the password of the visitor.
• We will process data in the same page before the first html tag of the document. Our form will therefore call itself.
• Comparing the IDs will be stored in two constants.
• Errors will be reported to the user.
• The login will be redrawn in the field if the user was mistaken.
• If all the information is checked, a success message will simulate the opening of the session member.

Let's full script. It is fully commented so only a few explanations will then be made:

Full identification script form processing example

<? php
      / *****************************************
         * Constants and variables
         ***************************************** /
         define ('LOGIN', 'Computer'); // Ok Login
         define ('PASSWORD', 'Notes'); // Okay Password
        $message = ''; // Message to display to the user

        // If the $_POST array is then the form has been sent
        if (!empty ($_POST))
                  // Is the login filled?
                if (empty ($_POST ['login']))
                       $message = 'Please specify Please login!';
               // The password is not filled?
               elseif (empty ($_POST ['storepass']))
                       $message = 'Please provide your password please!';
                // Is the login right?
               elseif ($_POST ['login']! == LOGIN)
                     $message = 'Your login is wrong!';
              // Is the correct password?
              elseif ($_POST ['storepass']! == PASSWORD)
                     $message = 'Your password is wrong!';
                // The identification was successful
                    $message = 'Welcome'. LOGIN. ' ! ';
<! DOCTYPE html PUBLIC "- // W3C // DTD XHTML 1.1 // EN" "">
<html xmlns = "" xml: lang = "en">
         <title> Identification Form </ title>
</ Head>
        <?php if (empty ($message)!):>
             <p> <?php echo $message; ?> </ p>
       <? php endif; ?>
     <form action = "<?php echo htmlspecialchars ($ _ SERVER ['REQUEST_URI'], ENT_QUOTES);?>" method = "post">
                   <legend> Name </ legend>
                              <label for = "login"> login: </ label>
                        <input type = "text" name = "login" id = "login" value = "<? php if (! empty ($ _ POST ['login'])) {echo htmlspecialchars ($ _ POST ['login']
ENT_QUOTES );}?> "/>
                       </ P>
                                  <label for = "password"> Password: </ label>
                                 <input type = "password" name = "storepass" id = "password" value = "" />
                                  <input type = "submit" name = "submit" value = "Login" />
</ P>
               </ fieldset>
       </ form>
</ Body>
</ Html>

From a general point of view, we have structured the page this way:

• Declaration of constants and variables.
• Data processing.
• Presentation of data

This design scheme is part of good development practices to adopt. It always processes information before presenting them. With this method, we can make such referrals without risk of error headers already sent.

A few lines of code still deserve explanations:

The first condition checks that the $ _POST array exists and is not empty. If this is the case, then it will return true (TRUE) and will be crossed to access the following tests.

Then performed a series of tests to verify that the form fields have been completed and that the transmitted values ​​are the constants defined in the file header. The empty () function checks the variable passed as parameter exists and is blank or null. If an error is detected, it is recorded in the $ message variable.

If no error is detected, this means that idenfiants are correct. We then enter the else clause. For information, we would have, in effect, log on and redirect the user to the protected page.

In the body of the page, we add a condition that checks if the $ message variable exists and is busy. If this is the case, you cross the condition and it displays the message in an HTML paragraph block.

Htmlspecialchars () protects variables by transforming brackets (<and>) and certain HTML characters in equivalent HTML entities. We use this function to protect against possible acts of Javascript code injection hacking or HTML (Cross Site Scripting attacks or XSS).

We call upon the environment variable $ _SERVER ['REQUEST_URI'] which contains the URL that leads to the current page. Through it, we specify the file that will receive the data itself. It is necessary to protect this variable as it is sensitive to the HTML injection piracy.

Finally, in the value attribute of the login text field, we place the last value posted by the user. It also protects the position because if the visitor html code, it will be interpreted directly. It is therefore necessary to ensure the safety of the variable that is desired to redisplay.

A word about the magic quotes

If the magic_quotes_gpc directive (GPC for GET / POST, and COOKIE) php.ini is enabled on the web server, then PHP will automatically protect the strings by escaping with a backslash some special characters (apostrophes, quotation marks ...). For example, if we post the string School's out so we get the following result:

Result of a chain of characters escaped automatically
L \ 'School's out

This protection thus acts as addslashes (). The backslash protects the apostrophe here. This character can be dangerous in a SQL query if it is not lost. SQL injection by talking about hacking risk. We must then be careful not to drop the data again with this function if the magic quotes are enabled because the backslashes would then also escape by other backslashes. Our previous example would look something like this several times if one escapes the data:

Result of a chain of characters escaped automatically
The \\\\\\\\\ school is finished

This protection initiative has generated much debate in the PHP community as it was indeed intended to close security holes created by beginners and little security conscious programmers. The move to PHP 6 will turn off this directive, which will force developers to protect their applications themselves.

We recommend disabling this directive to be directly in php.ini if ​​you have a stranglehold on the web server or by adding this line to the top of each PHP pages:

Temporary web server configuration
<? php
      // Disable magic_quotes_gpc
      ini_set ('magic_quotes_gpc', 0);

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.