Best PHP practices to make your web application more secure
PHP is one of the world’s most popular web-development languages. Famous websites like Facebook and the most popular Blogging platform WordPress are also created on PHP. According to a survey, more than 32% of web applications are build on PHP. But there is always an headache for developers,and that is to make their websites more secure so that hackers cannot interject malicious injections on the server.
And today we are going to talk about some basic considerations that a developer must consider before start making an application.
Htmlspecialchars and Htmlentities
Htmlspecialchars or htmlspecialchars() is a special PHP built-in function which basically converts special html characters into Html entities so that a hacker cannot inject Javascript onto the server.
Basically, this special function can convert 5 special html tags. If you want to convert all html characters into Html entities, then use htmlentities instead.
You can read more about Htmlspecialchars and Htmlentities here.
Now to be more specific, You basically need to use this function wherever you are getting an input from a user in shape of a form or an AJAX request.
Here is a good example of where and how you should use htmlspecialchars and htmlentities:
Consider we are getting some user data via Post method which will be inserted into MySQL database later. So using htmlspecialchars or htmlentities is necessary.
[php]
$example = htmlspecialchars($_POST[‘field1’]);
OR
$example = htmlentities($_POST[‘field1’]);
 
[/php]
After PHP 5 there were so many new upgrades in the PHP. Now we have filter_var function which can validate and sanitize many inputs like Emails, IP Addresses and Integers.
Also use strip_tags() to remove any tags presented into user input, “<script>,<php>” etc
Get Vs Post Method
This is being a big concern for new developers. Which method should be preferred and when? The simplest answer is when the circumstances are better to use any of them. For example if you have small data to send, then GET method is ideal to be used. However, it’s a bit unsafe because the request will be shown on the URL.
Whereas Post methods stays hidden in the system which means your request will be send without showing any data on the user screen. Basically, POST method is ideal to be used when there is huge data to be sent by a user. For example long Blog posts like we do post on our Blogs.
It’s recommend to not use GET method for making transactions on a site like Paypal, instead only use it to access information but not to insert something into the database.
Avoiding SQL Injections
To put one extra layer of security you should use mysql_real_escape_string() function wherever you are inserting user input into the database. For example:
[php]
@$name = htmlspecialchars($_POST(‘userdata’));
@$post = htmlspecialchars($_POST(‘userdata2’));
$query = "INSERT INTO table_name (column1, column2) VALUES (‘".mysql_real_escape_String($name)."’,’".mysql_real_escape_String($pass)."’)";[/php]
It is more recommended to use MySQLi or PDO extensions to create your content management system.
Abandoning malicious file uploads
This is a serious thing of concern, normally web applications allow users to upload images or photos like profile pictures etc. This can be dangerous if you are not making sure that all the security parameters are checked.
For this you must first confirm that the user is uploading the file with the valid extension. Let’s say if he/she tends to upload an image file, then the file extension should be an image extension(i.e. gif, jpg or png).
To make sure that the file has these extensions you can make an if statement like this:
[php]
if($check = getimagesize($_FILES["fileToUpload"]["tmp_name"]) == true) {
//Do something here
} else {
//Else do this
}
[/php]
Session Handling
Sessions are not safe. Sessions are saved in the temporary directory which means that anyone other than you can create a script and can read your session data from it in case of shared hosting servers.
It’s always a good idea to prefer Cookies on Sessions. However, you can use encryption commands to encrypt your session data to protect your data. Use session_set_save_handler() to encrypt your session data and make sure that you save important data on the database instead of saving it somewhere in the directory.
Prepared Statements
With PHP 5 there were many new introductions to the PHP world. One of them was Obect-Oriented-Programming(OOP) which makes the whole thing so effective and more secure. Specifically, if we talk about databases PHP 5 introduced MySQLi, MySQLI Procedural and PDO to connect with database and send queries.
With these extensions there was a new innovation for webmasters and that was Prepared Statements. Prepared statements should always be used when Inserting, Updating or Deleting data to avoid any MySQL injections.
Basically, Prepared statements makes the work a lot easy for any programmer because you can create a statement once and then can use it again and again. For instance, consider you are going to Update two rows in the database with the user input for which you will use a SQL statement like this:
[php]
$userInput = $_POST[‘input’];
$userInputB = $_POST[‘inputB’];
$query = "UPDATE table SET column1 = ‘AA’, column2 = ‘BB’ WHERE column3 = ‘".$userInput."’ ";
$query = "UPDATE table SET column1 = ‘CC’, column2 = ‘DD’ WHERE column3 = ‘".$userInputB."’ ";
[/php]
Now if you will use this sort of normal statement then you need to use two statements. However, with prepared statements you will just need to put the statement once and then create as many instances as you like:
[php]
$userInput = [‘input’];
$userInputB = [‘inputB’];
$query = $conn->prepare("UPDATE table SET column1 = :columnA, column2 = :columnB");
$query->bindParam(‘:columnA’, $columnA);
$query->bindParam(‘:columnB’, $columnB);
//Making Request one
$columnA = "AA";
$columnB = "BB";
$query->execute();
//Making Request two
$columnA = "CC";
$columnB = "DD";
$query->execute();
[/php]
This also ensure that no malicious injections are made from an unwanted user. Also it will help you to make your script more lightweight because you do not need to write a single statement again and again.
Error Handling
The most important thing when making a web app is proper error handling. Otherwise anyone will be able to read your application bugs which may help him to exploit the vulnerability of your website.
It’s also not good to show your applications bugs to your users, this is not user-friendly and doesn’t give a good look to your website.
To handle errors and avoid bugs there are numerous ways to deal. One of the most popular way is to use Exception.
It is also recommend to turn off display_errors and display_start_up_errors settings whereas log_errors and error_reporting should be turned on so that we can hide errors from end user and can log them so that we can deal with them later.
Wrapping it up!
Finally, I will like everyone of you to keep learning more about security issues. Also make a small checklist to make sure that everything is done. Don’t forget to use htmlentities or htmlspecialchars.
Never trust on user input and avoid using GET method for long inputs. Also make sure that you hide sensitive data from your users, for this you should not send data to user browser in shape of a COOKIE or SESSION instead of it, save it on your database.
For more please do read PHP security manual to make your application more secure.

Hi Husnain,
Great article and tutorial you got here! Keep it up man.
Some of the info here looks new to me and I got to give you credit for that!
Good job and just shared this around 🙂
Thanks Chan for posting your valuable feedback here :).
Great tips! Thanks! 🙂
Thanks for your commentsm JanLards