10 Helpful Tips for Creating Secure PHP Applications

Sector: Technology

Author: Nisarg Mehta

Date Published: 07/30/2014

10 Helpful Tips for Creating Secure PHP Applications

Tip 1: Use Proper Error Reporting/Error Handling

The development process of the application can become very cumbersome when the errors are not handled properly. In other words if there are no error reports enabled then identifying the minor mistakes like spell checks, incorrect functions usage and many more mistakes can become very difficult. It is a great practice to enable error reporting before even starting the development process. Once the website goes live, just hide error reporting from displaying.

  • Set Below Code in PHP.ini file.
1Log_errors = On<br />
2Display_errors = Off
3
  • Set Below Code in Configuration file.
1define('DEBUG',true);<br />
2if(DEBUG ==true)<br />
3{<br />
4ini_set('display_errors','On');<br />
5error_reporting(E_ALL);<br />
6}<br />
7else<br />
8{<br />
9ini_set('display_errors','Off');<br />
10error_reporting(0);<br />
11}
12

Tip 2: Validate Input

  • The inputs that are coming from the users needs to be validated from server side as well as client side. The inputs come in the form of POST or GET. Always use regular expressions in validation to avoid blank entries in the database.
  • Check the ‘type’ of the data
  • Check range of numbers
  • Check length of strings
  • Check emails , urls , dates to be valid
  • Ensure that data does not contain unallowed characters.

For Example,if Month value is not valid

1if ( ! preg_match( "/^[0-9]{1,2}$/", $_GET['month'] ) )<br />
2{<br />
3echo “”; // handle error<br />
4}
5

Tip 3: Protecting Against Sql Injection

  • To perform your database queries, one should be using PHP Data Objects(PDO). With parameterized queries and prepared statements (Store Procedure), you can prevent SQL injection.
  • Take a look at the following example:
1<?php
2$sql = "SELECT * FROM users WHERE name=:name and age=:age";
3$stmt = $db->prepare($sql);<br />
4$stmt->execute(array(":name" => $name, ":age" => $age));  ?>
5
  • The code given above has two parameters named :name and :age. Prepare() is the method which informs the database engine to pre-compile the query and attach the values to the named parameters later. When execute() is called, the query is executed with the actual values of the named parameters. By coding this way, the attacker on the SQL wont be able to inject a malicious query because the queries are already precompiled and the database will not accept it. Hence a secure database can be achieved.
  • mysql_real_escape_string :- The mysql_real_escape_string() function escapes special characters in a string for use in an SQL statement

Our team of experienced Angular professionals is ready to handle all your Angular development requirements.

Hire Angular Developer Now
Mobile Apps preferred Over Web

Tip 4: Disable PHP’s Bad Features

  • Global Variables (Register Globals)
  • Using the PHP feature ‘Register Globals’ can hamper the objective of maintaining programming safety. As soon as this feature is activated in the PHP configuration file, even an uninitialized variable can lead to a damaging security flaw and the height is almost anyone can seize administrative control. To deal with this situation, disable Register Globals, ensure that you initialize variables as well as use localized variables too within the program.
  • If the application is running with register_globals ON, a user could just place access=1 into a query string, and would then have access to whatever the script is running.
  • Unfortunately, we cannot disable register_globals from the script side (using ini_set, like we normally might), but we can use an .htaccess files to do this.
  • Set Below Code in .htaccessfile for disabling.
1php_flagregister_globals 0
2
  • Set Below Code in php.ini file (if you have access for the same) for disabling.
1register_globals = Off
2

Tip 5: Protect Against XSS Attacks

  • Cross Site Scripting has to be protected in order to protect a very simple attack on the website. PHP Application which allows the user inputs may come across a situation where the user placed a malicious script as per the example below into your application.
  • Here is an example of what an XSS attacker might submit to an application:
1<script>window.location.href='http://www.bad-location.com';</script>
2
  • What the script means is, it will hijack every user who visits that output page and send them to an unwanted page. This type of attack can be eliminated by using proper techniques to validate user input data and not allowing specific types of data.
  • Few functions to filter/validate data :
1htmlentities() ,strip_tags () , utf8_decode (), htmlspecialchars() , ctype_digit() , ctype_alnum(),<br />
2stripslashes() , str_replace()
3

Tip 6: Avoid Short tags

  • <? and <?= are called short open tags, and are not always enabled.
  • PHP 5.3.0, they are disabled by default, however if they are enabled Set Below Code in PHP.ini file.
1short_open_tag = Off
2
  • Your Application will not work if they are not enabled.<!–?php tag cannot be disabled

Tip 7:Protect Against CSRF Attacks

  • CSRF stands for Cross Site Request Forgery. The attacker is the remote machine which is trying to access the cookies or some other means of a normal legitimate user. For example when the user is trying to comment on the website, the login information is primarily stored in the cookies and there is every possibility that the cookies can be accessed by remote server who is a malicious user. This is why it is imperative to use filters when requesting for random information.
  • Lets say a certain url in the application performs some database changes,
    update_info.php?id=123
    delete_record.php?id=123
  • A hacker can setup a webpage with the following piece of code
1&lt;image(tag) source(tag)="http://www.original-application.com/delete_record.php?id=123" alt="" /&gt;
2
  • Ask the user to open this webpage. Now since the user is logged into the application the url will be triggered and whatever action necessary would be taken by the script.So basically a hacker has made the request through the user. This is “request forgery”.
  • Solution is to, enable the server to identify each request with a key/random value.

Tip 8:Securing the session

  • Regenerate Session ID ( function:— session_regenerate_id(); )
  • Lock the user agent during a session
    //Function to check if user is logged in or not
1functioncheck_login_status()<br />
2{<br />
3if($_SESSION['logged'] == true and$_SESSION['old_user_agent'] == $_SERVER['HTTP_USER_AGENT'])<br />
4{returntrue;}<br />
5returnfalse;<br />
6}<br />
7if(!check_login_status()){ logout();}
8
  • Lock the IP of a session
1$user_agent= @md5( $_SERVER['HTTP_ACCEPT_CHARSET'] . $_SERVER['HTTP_ACCEPT_ENCODING'] . $_SERVER['HTTP_ACCEPT_LANGUAGE'] . $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR']);
2
  • Store sessions in database
  • By default sessions are stored in files. Many applications are hosted on shared hosting environments where the session files are saved to /tmp directory. This directory may be readable to other users as well. If unencrypted the session information will be plain text in the file :
    userName|s:5:”ngood”;accountNumber|s:9:”123456789″;
  • Store sessions in database. Sessions stored inside database are not visible like files. They are only available to the application using it.

Tip 9:Setup correct directory permissions

  • Directories should have proper permissions with regard to the need of being writable or not. Keep a separate directory for temp files, cache files and other resource files and mark them writable as needed. Also directories (like temp) which can contain resource files, or files with other information should be guarded well and be totally inaccessible to the outside web.
  • Use htaccess to block all access to such directories( deny from all )

Tip 10:Password Security

1$salt = 'SUPER_SALTY';<br />
2$hash = md5($password . $salt);
3

Latest Tech Insights!

Join our newsletter for the latest updates, tips, and trends.

Related Insights

Starting a new project or
want to collaborate with us?

Starting a new project or
want to collaborate with us?

Get our newsletter.

Techtic’s latest news and thoughts directly to your inbox.

Connect with us.

We’d love to learn about your organization, the challenges you’re facing, and how Techtic can help you face the future.