By 
PHP

How to Create and Handle Forms in PHP – Best Practices


Hello guys, I hope its going all good so far. Today,  lets talk about PHP forms, best practices of form handling and see some practical examples. So lets dive in right now.

What is Inside this Post

 

·      Lifecycle of a Form

·      Detailed guide of HTML tags used to create any form

·      Guide on HTTP GET and POST methods with examples

·      How to retrieve form data – Form Handling

·      Creating Sample Contact Us Form

·      How to Insert Form data in MySQL using MySQLi approach

·      Sanitizing and Validating HTML form Data

·      Best Practices

Here is a short journey/Lifecycle of any form:

·      You create a required form

·      User fills in the data

·      Finally, the user clicks on submit button

·      Data is sent to server via GET or POST HTTP method where data processing is performed

In order to make above happen in real life, you do the following at the minimum;

The above code will create a form requesting a user to enter his name and email. Once he clicks on the submit button, form data is sent to the server via HTTP ‘POST’ method where ‘process.php’ will be responsible to perform required operation on that data such as saving to database etc.

Lets dissect line by line each statement and try to understand what it means,

<form></form> Tags

This HTML tag is the beginning of a form, all the form elements should reside within these tags.

Action=”process.php”

This statement describes the target file on server that will process the form data. All the form data will be made available for that PHP file on the server, where you can process it such as saving records in database, calculations etc. Use the name of file that you have created, process.php is just an example.

Method=”post”

This statement defines how the form data will be sent to the server. Use can use the following available HTTP methods:

GET Method:

Normally your browser will encode form data before sending it to the server, called URL encoding.  This involves creating name/value pairs, if there are multiple values, they are separated with ‘&’ sign. e.g.;

By using above format, GET method will send form information in your URL such as,

This is why it is highly secure, because a hacker can easily track and obtain required information. GET method has limitations as well, which are:

·       It can only send data upto a certain size

·       Never use this method for sending sensitive data

·       You can not use this method for sending binary data such as images.

·       URL parameters are saved as browser history

·       Can be bookmarked and cached

·       Very easy to hack

POST Method:

This HTTP method transfers data in the form of HTTP headers. Form information is encoded and put into the header called QUERY_STRING. Here are its characteristics,

·       Does not have any size limitation

·       Difficult to hack

·       URL parameters are not saved as browser history

·       Can not be cached and bookmarked

·       Since the data is sent as HTTP header, you can implement HTTP security to prevent hacking

·       Can send any type of data such as images

All the form elements are accessible in your target file which in our case is process.php file on server. PHP creates an associative arrays containing form values which can be accessed like,

$_POST[‘name’]

$_POST[] is a predefined associative array, you just need to put the variable you need inside. If you had used GET method, then all the values of form will be populated within $_GET[] associative array.

So in order to access values from the above form that we have created, we will write this code in PHP.

In real life we use some built-in PHP methods to sanitize the input and to prevent hacking attempts. We will discuss these shortly in next section.

Retrieving form data

We have already seen in previous examples how to retrieve data from form. PHP automatically creates an associative array containing form values. For example, if there is a field name ‘id’ in the form, then you can call the value of this field by using $_Post[‘id’] e.g.;

Let us make a sample Contact Us form and see how can we handle it in PHP

Sample Contact Us Form

Here is the output:

sample contact us form PHP

Dont worry, in next tutorials, we will learn CSS and JS to make this form more beautiful looking. We will also create forms in Bootstrap which by default includes CSS.

By clicking on the submit button, form data will be sent to the server where process.php file will be responsible to handle it, lets see an example of process.php file,

Here we have used a function sanitizeString() for which the detailed description will be discussed in next section. This function basically removes all dirt from the user input such as slashes, html tags etc.

Once you have obtained required data, you can do what ever you want for example you may need to insert it in MySQL database, lets do it now to learn more;

How to insert PHP form data in MySQL Database

We will be using MySQLi  object oriented approach

 Sanitizing and Validating HTML Form Data

This is the most important part where you should pay utmost importance otherwise a hacker may input any code which might get executed. More importantly when you are dealing with MySQL queries such as taking input from user then executing a query. So it is important that before you assign any value to a variable or process it, you must sanitize and validate it.

 First step: Make sure form fields are not empty

Make sure the field is not empty, we use following PHP function (isset()) to check if the field has any value or not, you may use other methods to check it:

Step 2: Removing Slashes

You can prevent escape characters from user input that can be used for malicious purposes or by mistake. Use following PHP built-in method

Step 3: Remove HTML tags

A hacker might try to insert HTML which can be safely removde by using the following code:

Step 4: Remove HTML entirely

You can remove entire HTML from the input by using htmlentities() method like below;

Best Practices for Form sanitization:

Rather than using all these method throughout the code, you should make a separate function that will sanitize the input and clean it just like below:

Conclusion

WoW, we have learned some basics of how to create form and then handle it in PHP. In the next post, we will look at creating forms by using Bootstrap. So far lets close this topic for now and watch some movies 🙂

 

 

Sohail ahmed
About me

Love to train and learn. SEO and development is my profession. 10+ years of IT training, practical experience in SEO. Creativity helps me strategize things well, especially when i code.

Leave a comment

Your email address will not be published. Required fields are marked *