Skip to main content

PHP Form Handling Tutorial for Beginners

The handling form is one of the most common tasks performed by any PHP developer. Because normally we create user interaction with our web application by form. This tutorial is for beginner and intermediate level of programmer who integrates different kinds of form in their PHP-based web application. This tutorial will cover different kind of trips, tricks, challenges and security involve in form handling in PHP.

Form Handling PHP Tutorial Covers following topics

  • Basics of Web Forms
  • Different Types of Form Submission & HTML Form
  • Different Types of Form Submission
  • Handling GET Request in PHP
  • Handling POST Request in PHP
  • Security in Forms
In this tutorial we have used some example code for learning and demonstration purpose, please do not try these example code directly on your live website or production servers.

Basics of Web Form

Forms are one of the major ways to communication between users and the websites. Forms provide a various medium of communication between user and website. On daily basis, we interact with lots of forms while using websites.

Followings are some of the common examples where we face form on websites:

  • Login forms on webmail or online banking websites
  • During funds on banking websites
  • Writing email using webmail client like Gmail or Yahoo
  • Posting image on the Facebook wall
  • Approving friend request on Facebook

Now to understand how these forms work you first need to understand how the web works or how HTTP protocol works. You need to know basics of HTTP and HTTP web server.

How HTTP Protocol Works

Although this is very very big topic to cover here. But we will quickly understand the summary of HTTP protocol working model so that it will be very easy to understand how HTTP form works. If you want to dig HTTP protocol working model then please refer to RFC 2616 which has everything about HTTP protocol version 1.1.
HTTP is a stateless communication protocol and used for communication between different systems. HTTP is application layer protocol which works on TCP/IP. It works on the client-server model. The client initiate request with some information to the server, the server evaluate the request and send the response to the client system.

Key process of HTTP protocol:

  • Stateless communication Protocol
  • Application layer protocol works on TCP/IP
  • Works on Client & Server Model where client initiates request and communicate with server
  • Client and server communication takes places with the help of HTTP headers.
  • HTTP header is regulated by the W3C consortium and IEEE.
  • HTTP header contains different kind of information like URL
  • The client initiates a request to the server with URL and different HTTP header.
  • HTTP Header sent by the client system is named as “Request Header” and request header contains information like host, browser information, cookies, referer etc.
  • The server takes request and evaluate URL and HTTP header and provides a response to the client with HTTP header.
  • HTTP header sent by server is named as “Response Header” and primarily contains information are cache header, status code etc

The URL

URL is one of the key element of the HTTP protocol. URL stand for Uniform Resource Locator & it is used to identify the request initiated by the client, or in simple terms web address with complete path of resource which client browser wants.
Following are 3 common things in normal URL

  • Protocol type: Whether URL is HTTP or https. Example: http://
  • Host Address: Website host address for example www.techflirt.com
  • Path of resource: In the current page URL it is /form-handling-php

 

URL Pattern

 

Above is a case of normal URL. It may or may not have following things

  • Host Port: If a website is hosted on other than port 80 in HTTP protocol and other than 443 on HTTPS protocol.
  • Query String: If website is passing query parameter like some string you have seen like ?id=2&p=2
  • Hash Fragment: In some of URL you have seen hash component.

 

URL Pattern With query string and port

 

HTTP Request Methods

In HTTP protocol client sends a request to the server with the request method. Request method informs the server about what kind of request is made.

Following are the request methods in HTTP protocol:

  • Get
  • POST
  • OPTIONS
  • PUT
  • DELETE
  • HEAD

GET

GET method uses URL to fetch or retrieve information from the web server. In a GET method,  request URI is the main key to identify and fetch the information. GET request method is default method to fetch the information from the server. For example, if you have entered URL http://www.test.com/abc.php then by default it sent GET request to web server. For passing dynamic information with the GET request you can also use a query string, for example,  www.test.com/get-pic.php?pic_id=123. In this example pic_id is dynamic ID which is passed 123. If the query string is not used then the response might be cached at browser end in the GET request.

POST

In Post request method resource is still identified by request URL path(commonly known as URI) but request also accept additional data via HTTP header. POST request method is used to post some large chunk of data to the server resource. For example Login form, custom information form, file upload etc. In POST request method response is non-cacheable.

OPTIONS

OPTIONS request is used for requesting information from the server about its capabilities. One of a common example is checking allow-origin request.

PUT

PUT request method is used to update existing resource.

DELETE

DELETE request method is used to delete the existing resource request.

HEAD

In HEAD request method response does not contain any response body and only returns response header. This is identical to a GET method with the only difference that response body text does not return by the server.
Since most of the form-based communication happen using GET and POST method, in next section we will in depth aspect of both GET and POST method. Also, we will see how a form is generated on a web page and form handling in PHP.

Different Types of Form Submission & The Form

Hope you have the clear idea about basic of HTTP and HTTP methods. As you have seen in the previous section that via different HTTP methods client (or in general term, we can say browser) can send data to the server. HTTP method GET and POST are the most common way of sending the data. In the GET method, you can send data to the server via URL and in POST request method along with URL you can also include data which will be sent to the server in the request-header.

Now next question: How data from a client browser can send to server?  How can user generate or tell the browser about the data which will be sent?

Answer is: HTTP FORM

The Form

The HTTP Form allows users to enter the data and send to the server via different HTTP request methods. A form can be created inside the web page with the help of HTML. It can be placed anywhere on the visible viewport of the webpage. The form enables websites to interact with their users and provides a dynamic experience. For example on e-commerce website almost at every point, there is a form submission happen, the server evaluates the form submission and takes his user to complete e-commerce journey. In this section, we will explore some basic semantic of HTTP form.
In general terms we can think of HTML form are like paper forms. HTML forms had a different kind of elements like input box, radio button, checkbox. All HTML form elements are enclosed within <form> tag.

A Simple HTML Form Example:

<form method="post" action="login.php">
Username: <input type="text" name="username" /><br/>
Password: <input type="password" name="password"/><br/>
<input type="submit" name="submit" value="Login"/><br/>
</form>

Above HTML code will create the following form.
HTML Form Example
In Above example we have used following 3 type of elements in <form> tag

  • Text Input: User Name is text input type field where the user will simply write his username.
  • Password Input: Password has dedicated input type other than text because, because in password if user write anything it will simply display * in front of user in a box so that no one can see what user has typed in password field
  • Submit Button For a simple form submit button input type submit is used. It draws button, and by clicking the button simply form get submitted.

All element used in the above HTML form has different type of attribute like <form> element has attribute action and method, <input> tag has attribute type & name. So now before going for detail coverage let us explore basic of different HTML element and their attributes.

Form HTML Tags and their attributes

Following are the HTML tags which we need to learn to create HTML form:

  • Form Tag: Form Tag is for enclosing all HTML tags which will be for a particular form. Also in the form tag, we can define the behavior of form.
  • Text Input Tag: For entering text input.
  • Password Input Tag: For entering password input.
  • Checkbox Input: For providing checkbox input to the user.
  • Radio Button Input: For Radio button input to the user.
  • File Input: For providing option to upload a file to the user.
  • Submit Button: For providing submit button to the user.
  • Hidden: This field is primarily used by developer to have some value in form hidden.
  • Select Input: Providing drop-down option to the user.
  • Text Area: For providing option to write text in multiple lines to the users.

Form Tag <form>

Form Tag starts with <from> and end with </form>. Form tag wraps all different type of input tags and the submit button of the form. Form tags has following attributes

  • Action: Action attributes defines where form data will go when user will submit the form.
  • Method: Method attributes tells a type of HTTP request method form will use while posting the data. For example, whether the form will use GET request Method or Post Request Method.
  • Name: Name of the Form. What is the name of the form?
  • Enc Type: This attributes defines what type of encoding will be done when form data will be submitted. This is only valid for form method post.

Let us recall HTML code from above example for <form> tag :
<form method="post" action="login.php">
</form>

Now in above example, we have defined that the form will use post method and the form action is taking data to login.php.

Input Tags

If you will again recall our firm HTML form HTML then we have used following input field:
<input type="text" name="username" />
<input type="password" name="password"/>
<input type="submit" name="submit" value="Login"/>

Above input fields are drawing the following boxes:

  • Text Input
  • Password Input
  • Submit button

So using input <input> field we can create following form fields

  • Text Input
  • Password Input
  • Radio Input
  • File Input
  • Hidden Input
  • Checkbox
  • File Input
  • Submit Button

Following is the structure of <input> tag

<input type="text|password|radio|file|submit|hidden|checkbox" name="name of your field" value="value of input field" [checked="checked"] />

So input type tag has primary following attribute:

  • type : It could be text|password|radio|file|submit|hidden|checkbox depending on what you want to draw.
  • name: Name of your input type. This will be used in your server side script like PHP to get the value of your input type.
  • value: Value is for showing the current value of your <input> for text box, and password it is used to show pre-field value however in radio, checkbox & submit it is used frequently as values are pre-defined.

Following are the examples of Input types:

Text Box:
Username <input type="text" name="username"/><br/>
Password <input type="password" name="password"/><br/>
Full Name <input type="text" name="fullname" /><br/>

Hidden Input:
<input type="hidden" name="security-code" value="12sdsaq13">

Radio Button:
Gender <input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female

In Radio Button you have seen that we have created both buttons with the same name. If we need to provide an option to choose from one of the sets of radio button then we have to give both as the same name. Also since the radio button will have pre-decided value, we need to pass value tag in the radio button as well.

Checkbox:

Hobbies <input type="checkbox" name="h_cric" value="cricket"/>Cricket
<input type="checkbox" name="h_basket" value="basketball" >Basket Ball<br/>
Simillarly like rado button checkbox will also have value, but not necessary to provide same name.

File Upload Box:

Photo <input type="file" name="profile_pic"/><br/>

Submit Button:

<input type=”submit” name=”submit” value=”Update Profile” />

Select Box <select>

By <select> tag we can create dropdown box for the user. Dropdown can be used to provide an option to choose from the list of available option. For example: In profile form, we can provide country or state option via dropdown. Following is the structure of dropdown:

<select name="name of your select box">
<option value="value of option">Name or Label of option</option>
</select>

For example:
Country <select name="country">
<option value="india">India</option>
<option value="USA">USA</option>
<option value="UK">UK</option>
</select>

Textarea<textarea>

Textarea tag is used to provide larger input box where a user can use multiline of text. For example autobiography in profile form.

Example:
<textarea name="autobio" rows="5" cols="30"></textarea>

The Complete HTML Form Example

Now we have explored all basic element of HTML forms. Following is the example of complete HTML form:

<form action="test.php" method="post" enctype="multipart/form-data">
Username <input type="text" name="username"/><br/>
Password <input type="password" name="password"/><br/>
Full Name <input type="text" name="fullname" /><br/>
Gender <input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br/>
Hobbies <input type="checkbox" name="h_cric" value="cricket"/>Cricket
<input type="checkbox" name="h_basket" value="basketball" >Basket Ball<br/>
Photo <input type="file" name="profile_pic"/><br/>
Country <select name="country">
<option value="india">India</option>
<option value="USA">USA</option>
<option value="UK">UK</option>
</select><br/>
Tell Something about Yourself<br>
<textarea name="autobio" rows="5" cols="30"></textarea><br/>
<input type="hidden" name="security-code" value="12sdsaq13">
<input type="submit" name="submit" value="Update Profile" />
</form>

Above code will generate following HTML form in the browser:
HTML Profile Example

Back To HTTP Method

In all above example, we have uses <form method=”post”> Now what is the actual behavioral difference when we are using the method as the post or get method.
Let us review the form tag from our previous example:
<form action="test.php" method="post" >

Now if we have used the above form code then it will simply send all fielded data on test.php and form data will be inside of HTTP header.
Now what happen if we will change the method from POST to GET like below:
<form action="test.php" method="get" >

Clicking on submit button will generate all form data in URL like below:
test.php?username=abc&password=asfas3&gender=male…. and so on.
But above will not work for our scenario because we have use enctype=”multipart/form-data” in our form tag. And enctype=”multipart/form-data” is used because we are uploading file via our form.

Question: So where we can use GET Method?
Ans: In some small and non-sensitive form like search form or very small user request form.
For Example

<form action="search.php" method="get">
Search: <input type="text" name="search" /> <input type="submit" value="Search">
</form>

Form Handling In PHP

In above section, we have explored lots of aspects of HTTP, request methods and different HTML tags which helps us to create nice form. But how we will process the form submitted by the user? How will we make the site interactive and provide the response to the user on different data entered by him or her?
In this section, we will find answers to our all these questions.
When we post form on PHP script then all forms data will be available in following super global variables:

  • $_GET: Associative array which contains all value submitted from the GET request.
  • $_POST: Associative array which contains all value submitted from POST request.
  • $_REQUEST:  Associative array which contains all value submitted from POST & GET both request also contains cookies.

In below sections, we will explore on how to handle

Handling GET Request in PHP

In PHP all form data submitted via the GET request method are available in $_GET as well as $_REQUEST variable. In Associative array data is available with the name used in input fields on the form.

For example:
Search.html
<form action="search.php" method="get">
Search: <input type="text" name="search" /> <input type="submit" value="Search">
</form>

On search.php
<?php
print_r($_GET);
?>

This will print:

Array
(
    [search] => test
)

Now on search.php you have $_GET[‘search’] variable where whatever has been entered in the textbox will be available. in $_GET the name of the array element is search because the name of the input box is search.
Let us explore some advanced example:
search-advance.html:
<form action="search-advance.php" method="get">
Search:
Keyword <input type="text" name="search" />
Category: <select name="category">
<option value="blog">Blog</option>
<option value="news">News</option>
</select>
<input type="submit" value="Search">
</form>

search-advance.php
<?php
echo 'Hey user you have searched for'.$_GET['search'].' in category: '.$_GET['category'];
?>

What happens behind the scene?

When we click on the search button on search-advance.html then it encodes all HTML input field in action which is search-advance.php. For example, if I have entered XYZ in the search box and selected blog from category then it has created URL like search-advance.php?search=xyz&category=blog. Now PHP has evaluated the URL and parsed all data appended as query string which is search=xyz&category=blog and stored in $_GET and $_REQUEST variable for your use.
So can we directly access search-advance.php with query string like search-advance.php?search=mysearch&category=anycategory ?
Yes, we can. And it will have same behavior what we got from search-advance.php form. The developer uses this approach very frequently in creating dynamic grids with edit feature on every row. Interesting is not it?

This is a first step where the user can break your form behavior very easily.

Suitable place to use GET request Method

Though GET encodes everything in URL following are some suitable use case for using GET method:

  • On Small Search Form.
  • One One Box text input like submitting ticket number.
  • Order search form on e-commerce.
  • Creating Edit link on a grid with dynamic ID.
  • Create Add or View link on Grid with dynamic ID.

Limitation or Security Risk in using $_GET or Get request Method

  • No long form can be posted: Since the GET method work as a query string in the browser, and URL has some character limit, so the long form can not be posted via the GET.
  • File Upload: Using GET Method we can not send a file from browser to server.
  • Proxy Caching: Some proxy caches GET request response or URL with query string, so if using GET method handle the cache properly.
  • Referer: From the page serve by the GET request, if a user is redirected to any other website then the other website will have all query string parameter in their referer.
  • Chances of Content Spoofing: IF you have used $_GET request or query string parameter and the parameter are getting printed exactly as is on your page, then content spoofers might pass some contradictory content via the GET request and post the URL on any third party forum and spoil your brand identity.

The Myth

I have heard from different people that GET request is less secure then post request, but it is not completely true. Both GET and POST are equally secure, only the difference is that in the GET all of your data is directly visible to the user but in POST the data is in HTTP header. So if the loophole is open then in both method hacker can hack your site.

Handling POST request Method in PHP

In PHP all request submitted via POST request is available in super global variable $_POST and $_REQUEST. In Associative array data is available with the name used in input fields on the form.
Now let us take an example of a search form with POST request method:
search-post.html:

<form action="search-post.php" method="post">
Search: <input type="text" name="search" /> <input type="submit" value="Search">
</form>

On search-post.php
<?php
print_r($_POST);
?>

This will print:

Array
(
    [search] => test
)

Now on search.php you have $_POST[‘search’] variable where whatever has been entered in the text box will be available. Similarly, like the $_GET name of the array element was search because we have named our input box as search.
Let us take the same advanced example with the POST method, which we have used as the GET
search-advance-post.html:
<form action="search-advance-post.php" method="post">
Search:
Keyword <input type="text" name="search" />
Category: <select name="category">
<option value="blog">Blog</option>
<option value="news">News</option>
</select>
<input type="submit" value="Search">
</form>

search-advance-post.php
<?php
echo 'Hey user you have searched for'.$_POST['search'].' in category: '.$_POST['category'];
?>

Only the variable is changed from $_GET to $_POST. But is there anything else which is changed? Yes, the URL formation in the browser. If you will see the URL in the browser then it will be intact as search-post.php or advance-search-post.php.

What happens behind the scene in POST method

The moment you have posted the form using post request method, it sends the form data to the page with key value pair in the request body. So for our advance-search-post.html, it sends the data to advance-search-post.php in the request body. In the request body again it sends the data in key value pair like search=asdfasfasf&category=blog.

So how can you see what has been posted

You can use different browser developer tools to see what has been posted in form. Let us seen in Firefox using firebug plugin for what has been posted to advance-search-post.php from advance-search-post.html
Below is the snapshot of HTTP Header in firebug

Firebug HTTP Header
If you will see the request header section then you can found that the request method is POST and referer is search-advance-post.html.
Following is snapshot of POST Tab of firebug where you can see what has been posted:
Firebug Post BodyHere there is 2 section, in first you can see your post parameter well formatted, but below that there is a section for the source which is showing everything as a query parameter.
In the GET request method, you have submitted data via the query string in the browser.

Is there any way you can submit the data on post method by any other media except browser?

Yes, you can. There are various tools available to do that. For example via different firefox or chrome plugin, or via curl or Wget utility. I have used following curl command to post data on my advance-search-post.php

curl ‘http://localhost/techflirt/form-handling/search-advance-post.php’  -H ‘Host: localhost’  -H ‘Content-Type: application/x-www-form-urlencoded’ –data ‘search=test&category=news’ -v

And here is what I got:
Curl Post

In nutshell, you can easily post data on any page using post method by different types of utilities.

So nothing is secure by default, you have to apply security in your form.

A big form

Now let us take a bigger example. The file name is test.html which we have created earlier to see all type of input field like radio button, select box, file. Now it is posting the data on test.php

test.html
<form action="test.php" method="post" enctype="multipart/form-data">
Username <input type="text" name="username"/><br/>
Password <input type="password" name="password"/><br/>
Full Name <input type="text" name="fullname" /><br/>
Gender <input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br/>
Hobbies <input type="checkbox" name="h_cric" value="cricket"/>Cricket
<input type="checkbox" name="h_basket" value="basketball" >Basket Ball<br/>
Photo <input type="file" name="profile_pic"/><br/>
Country <select name="country">
<option value="india">India</option>
<option value="USA">USA</option>
<option value="UK">UK</option>
</select><br/>
Tell Something about Yourself<br>
<textarea name="autobio" rows="5" cols="30"></textarea><br/>
<input type="hidden" name="security-code" value="12sdsaq13">
<input type="submit" name="submit" value="Update Profile" />
</form>

Now if you will submit the form to test.php and on test.php you will print $_POST you will get something like below:

Array
(
[username] => asdfasf
[password] => asdfadsf
[fullname] => dsfsadf
[gender] => Female
[h_cric] => cricket
[h_basket] => basketball
[country] => USA
[autobio] => asdfasdfasdf
[security-code] => 12sdsaq13
[submit] => Update Profile
)

Oh My God! where is the image which I have uploaded on the form?

Don’t worry you will get it in another PHP super global variable $_FILES. Now if you will print $_FILES you will get all information of your image like below

Array
(
[profile_pic] => Array
(
[name] => basic-url.jpg
[type] => image/jpeg
[tmp_name] => /Applications/XAMPP/xamppfiles/temp/phpAUqO7P
[error] => 0
[size] => 8615
)
)

If you want to know the complete file upload process then you can refer to my post on file upload in php.

Multidimensional Input Form Post

You can pass multidimensional array form using php. For example:

<form action="multidimension.php" method="post">
First Name <input type="text" name="name[first]"/><br/>
MIddle Name <input type="text" name="name[mid]"/><br/>
Last Name <input type="text" name="name[last]"/><br/>
<input type="submit" value="Search">
</form>

And once you will post this form it will give the associative array like below

Array
(
[name] => Array
(
[first] => Ankur
[mid] => Kumar
[last] => Singh
)
)

Another Multidimensional Form approach

<form action="multidimension.php" method="post">
First input <input type="text" name="input[]"/><br/>
Second input <input type="text" name="input[]"/><br/>
Third <input type="text" name="input[]"/><br/>
<input type="submit" value="Search">
</form>

Array
(
    [input] => Array
        (
            [0] => test 1
            [1] => test 2
            [2] => test 3
        )

)

Different Form on one page

Can you submit the different type of form on one page? Yes, you can. In every form, you can put identifier as hidden input and process the form data on the basis of that. Also, you can have more than one form on the same page which can submit data on a different PHP page.

On One Page Operation.

In all above examples, you have seen that we have used 2 different page for every form example like for search we have used search.html where I have form and posting on search.php. But sometimes you will be trapped in the case where you want to show edit form with pre-filled value and user submit the data. Also, you need to put server-side validation on the form to validate the input. Doing such type of complex operation using 2 files is bit difficult.

So can we do it on one page? Yes, we can since PHP can be embedded inside of HTML. Let us take and example
FileName: onepage.php

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
print_r($_POST);
//PUT YOUR Code to validate and save the form in DB
}
?>
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="/techflirt/form-handling/onepage.php" method="post">
First Name <input type="text" name="name[first]"/><br/>
MIddle Name <input type="text" name="name[mid]"/><br/>
Last Name <input type="text" name="name[last]"/><br/>
<select name="age">
<option value="">Select Age</option>
<?php
For($i = 12;$i<=99;$i++){
echo '<option value="'.$i.'">'.$i.' Years</option>';
}
?>
</select>
<input type="submit" value="Search">
</form>
</body>
</html>

If you will see the above example then you can see that Age is the select box is generated dynamically using following code:
<select name="age">
<option value="">Select Age</option>
<?php
For($i = 12;$i<=99;$i++){
echo '<option value="'.$i.'">'.$i.' Years</option>';
}
?>
</select>

Also on the top of the page, there is a condition which says that whether the form is posted or not. Below is the code:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
print_r($_POST);
//PUT YOUR Code to validate and save the form in DB
}
?>

POST with Query String

We can also use the query string in URL while posting the form. And we can get different values in $_GET and $_POST variable at the same time. For example:
<form action="/techflirt/form-handling/get-post.php?user_id=1" method="post">
First Name <input type="text" name="name[first]"/><br/>
MIddle Name <input type="text" name="name[mid]"/><br/>
Last Name <input type="text" name="name[last]"/><br/>
<select name="age">
<option value="">Select Age</option>
<?php
For($i = 12;$i<=99;$i++){
echo '<option value="'.$i.'">'.$i.' Years</option>';
}
?>
</select>
<input type="submit" value="Search">
</form>

In above example form action is /techflirt/form-handling/get-post.php?user_id=1 which has query parameter user_id=1 so once you will post the form you will get $_GET[‘user_id’] =1 along with all of your $_POST variables.

Security in in Form

Forms are publicly available input system on your website for user interaction. There is no any big built-in security applied either by HTTP protocol or your browser. On the browser, if you have applied any security like input validation then still you can intercept the form data or post data to your form directly on a page by the different kind of tools. This is not a flaw in HTTP protocol, but this is the great flexibility by which you can have endless opportunity to build a great system. So you need to take care of security of what you have created. Although different kind of system built requires a different kind of security mechanism but some of the basic security consideration should be common across all kind of form which build and handled by PHP script. In this section, we will discuss those considerations.

Validate Form Submission Origin

In previous sections, you have seen that by passing action in form tag or by wget or curl utility anyone from any site or any other source can post data on your form which can lead to potential risk. So always validate for source origination of your form. Below is the one technique for origin validation:

Step 1: On Input form action or page generate a dynamic token and store in session. Make sure that token is always unique and mix with some of your private key and the key should be secret and not available to the user by any means.
Step2: Put the dynamically generate secure token as hidden input on your form.
Step 3: Validate the hidden input token on your submission action. If the token is not valid just stop the form processing and show appropriate action. If the token is valid then only proceed to next.
Step 4: The token should always be unique for every action of your form, even the same form is opened.

Following is a basic code implementation:

Generate Unique ID:
function generate_secure_key() {
$bytes = random_bytes(10);
$key = bin2hex($bytes);
$token = md5(uniqid(microtime(), true)) . $key;
return $token;
}

Store it in Session
$_SESSION['token'] = generate_secure_key();
Put in Hidden Variable
<input type="hidden" name="token" value="<?php echo $_SESSION['token'] ?>"/>

Do not forget to validate it:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//print_r($_SESSION);die;
if(!empty($_SESSION['token']) && !empty($_POST['token'])){
if($_SESSION['token'] == $_POST['token']){
//Write code to process your form
echo 'Now form data can be processed';
}
}
}

Following is the complete code:

<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//print_r($_SESSION);die;
if(!empty($_SESSION['token']) && !empty($_POST['token'])){
if($_SESSION['token'] == $_POST['token']){
//Write code to process your form
echo 'Now form data can be processed';
}
}
}
else{
$_SESSION['token'] = generate_secure_key();
}
function generate_secure_key() {
$bytes = random_bytes(10);
$key = bin2hex($bytes);
$token = md5(uniqid(microtime(), true)) . $key;
return $token;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="/techflirt/form-handling/php-token.php" method="post">
First Name <input type="text" name="name[first]"/><br/>
MIddle Name <input type="text" name="name[mid]"/><br/>
Last Name <input type="text" name="name[last]"/><br/>
<select name="age">
<option value="">Select Age</option>
<?php
For ($i = 12; $i <= 99; $i++) {
echo '<option value="' . $i . '">' . $i . ' Years</option>';
}
?>
</select>
<input type="hidden" name="token" value="<?php echo $_SESSION['token'] ?>"/>
<input type="submit" value="Submit">
</form>
</body>
</html>

Validate All input in your PHP

First of all, do not rely only on JavaScript validation. Always validate the form input via the PHP script. This is because the user might submit the form by disabling javascript in his browser, or he can submit the form via wget or curl utility.

Always validate for correct input field

Always validate for what you are looking into the form, because on form anything can be posted. The user can add some extra element or remove any vital element from your form with the help of any utility. So always validate for that.

Do Not User PHP_SELF on your form action

I have seen that most of the developers are using $_SERVER[‘PHP_SELF’] variable in the form action like <form action=”<?php $_SERVER[‘PHP_SELF’] ?>” but it always has security risk. What happens if the user has passed some malicious code on his URL. It will be simply injected here.

Sanitize the form input for Cross Site Scripting handling

Suppose you want to print the same thing on any of your pages by taking input from the user, for example, Hello [Username]. Username is coming from a form submitted by the user. Now user has passed some HTML like <b><a href=”www.othersite.com”>Click Here</a></b> then it will print Hello Click Here with URL of www.othersite.com in link. So always remove HTML by strip_tag function.

Download Code used in the tutorial.

Support Me by Sharing This Article

Ankur Kumar Singh

I am a PHP programmer having some knowledge about Linux. I am always interested in web development and knowledge sharing. I am full time tech evangelist part time human being. :-)

Leave a comment/Ask Question

4 thoughts on “PHP Form Handling Tutorial for Beginners

shares