Security Best Practices in PHP


· ·

OAccording to a 2019 report by Accenture, security vulnerabilities have surged by 67 percent since 2013, including web apps that use PHP. We must take extra precautions to protect the security of web applications. PHP web applications are vulnerable to a variety of attacks, including cross-site scripting (XSS), SQL injection, local file inclusion, and path traversals. This could then cause a web program to execute a file from another location on the system. As a result, recommended practices for securing PHP applications are a necessity.

When working on PHP applications, this guide will go through several security best practices. This will assist developers in prioritizing security and defending against web threats.

PHP Security Best Practices 

#1 Update your PHP version regularly.

Older versions of PHP have known security issues. These flaws have been rectified in newer versions, making it more difficult for hackers to stage attacks. While maintaining PHP programs, you should prioritize version updates to prevent attack surfaces that are vulnerable to outdated versions. 

#2 Beware of XSS attacks (Cross-site scripting).

An XSS attack occurs when a web application executes external remote code. A good example is when a user inputs HTML, JavaScript, or CSS into a user input form, and it gets printed directly into a web page. This execution of remote code can cause a page to malfunction or display unintended results.

A form accepting user input may appear as below:

<form action="form.php" method="post"> 
 <input type="text" name="totalValue" value=""> 
 <input type="submit" name="submit" value="Submit message"> 

 To print out the input value, call this PHP function:  

echo $_POST["totalValue"]; 

An attacker may take advantage of an input form by inputting a script instead of the required


<script>alert("I was here")</script>  

When the script gets executed, “I was here”  will be visible as an alert message on the browser.

Although this is a simple example of an XSS attack, hackers can input more complex JavaScript into input forms that could completely jeopardize a web application as they can inject the trojan virus into a web application, capturing a user’s login credentials, and enabling a complete virtual defacement of a web application.  

XSS attacks can be prevented by:

  •  Filtering all user input on arrival to eliminate possible code tags from making their way into the site.
  •  Encoding all user-controlled data to prevent it from being interpreted as active content in HTTP responses.
#3 Make use of prepared SQL statements.

Prepared SQL statements to ensure that no room is left for SQL injection attacks. With unprepared SQL statements, the user can break the SQL query and execute any query they wish.

For example:

$grapes = mysql_query("SELECT * FROM `fruits` WHERE `id`='$_GET[id]'");  

The example above uses unsanitized user input inside the SQL query, and this gives the hacker a chance to break the statement and try to query for other information. Prepared statements ensure that all values inputted are escaped, and this leaves no room for an SQL injection.

Prepared SQL statements appear as below:

$stmt = $conn->prepare("INSERT INTO fruits (type, colour) VALUES (?, ?)");
$stmt->bind_param("ss", $type, $colour);  
#4 Do not upload all framework files to your server 

Uploading all framework files to a web server gives room for attackers to gain access to an application’s logic, which could also enable them to possibly come across security loopholes and take advantage of them.

Many PHP frameworks consist of the Model View Controller (MVC) file structure, and may appear as below:

public_html/ .htaccess    

The above structure is very simple and is prone to security breaches because it is easy to take advantage of the architecture to locate vulnerable files to launch attacks. It is important to leave out some files when deploying to the webserver.  

#5 Limit directory access 

Limiting directory access can be done by making use of the open_basedir function.

For example, if the open_basedir function is set to the project’s root, this means accessible files are only ones at the root of your project and downward.

#6 Verify your SSL configuration

To enable safe and encrypted accessing methods for untrusted sites, all modern browsers encourage using HTTPS protocols for web applications. Installing SSL certificates into your web apps or websites enforces HTTPS, which protects against XSS attacks and encrypts sent data. To obtain the highest level of PHP security, you must configure SSL and check SSL certificates on a regular basis, as expired certificates allow for XSS attacks.

#7 Use URL encoding 

URL encoding allows for a safe generation of valid URLs. This prevents security breaches that may happen as a result of user information being exposed.

An example of URL encoding is as below:

echo '<a href="mylink?fruit=', urlencode($fruitID), '">'; 
#8 Avoid remote file inclusion 

Avoid accepting user input requiring a file. This is because an attacker can input a path leading to sensitive information, e.g,  ../../../etc/passwd, which can lead them to gain access to an app’s admin password if they are on a Linux/Unix server.

If at all accepting user input requiring a file, then validating it before execution is a necessary step further. This could also be coupled with making use of the open_basedir folder. An even better solution when accepting user input requiring a file would be to specify a user’s possible choices using a switch statement.

For example:

$mypage = $_POST['mypage']; 
if ($mypage == "oranges") { 
require("./pages/oranges.php"); } elseif ($mypage == "bananas") { 
} else { 
#9 Proper Documentation

Proper documentation is also a security strengthening measure because it will keep you up to date with your project version. It ensures that you’re constantly aware of any changes that you need to make, such as updating a password or an SSL certificate.

#10 Application Error Logging 

It is impossible to overstate the importance of error logging in application development, both in the staging and production environments. This is due to the fact that error logs aid in debugging and monitoring the application’s performance. Therefore, you should save logs from PHP applications to a specified file for later usage. Configure logs as follows inside the php.ini file:

log_errors = On

To prevent hackers from getting valuable information on your site based on errors, you must disable the display of errors on the live server. Set the following parameters in the file:

Display_errors = Off

To better understand how logging helps in security compliance, learn more here.


When developing PHP apps, it is critical that developers consider security from the start. As a result, apps will be more robust and less prone to cyber-attacks. If you take into account all of the above techniques during the development process, PHP applications will be much more secure.

Faith Kilonzi is a full-stack software engineer, technical writer, and a DevOps enthusiast, with a passion for problem-solving through implementation of high-quality software products. She holds a bachelor’s degree in Computer Science from Ashesi University. She has experience working in academia, fin-tech, healthcare, research, technology, and consultancy industries in both Kenya, Ghana, and in the USA. Driven by intellectual curiosity, she combines her passion for teaching, technology, and research to create technical digital content.


Leave a Comment

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

Skip to toolbar