PHP Security

Resolving XSS, CSRF, SQLi, Session Hijacking & Other Security Issues in PHP

Updated on: June 23, 2021

Resolving XSS, CSRF, SQLi, Session Hijacking & Other Security Issues in PHP

PHP is dramatically the most criticized language when we talk of security, yet the oldest in its usage. Despite being old it is far from being outdated. On the contrary, it is still in high demand. Thus, it is important that it remains as protected as possible for it is basic to many growing businesses. PHP coders, understand the fact that it is highly expected of them to take care of all the PHP security issues that come along way. Here, I will try to explain in brief what PHP security issues are and how you could solve them. 

What you can do beforehand, to be on top of your game is updating PHP regularly. The most stable version of PHP available as of now is PHP 7.2.8. We strongly recommend you to switch to this version from any other. The older ones are likely to be much more troublesome. Moving on, let’s discuss a few of the most common PHP security issues and their fixes.

PHP security issues & prevention steps

1) Cross-Site Scripting in PHP

This PHP security issue arises when there is an unwanted entry of a malicious script from external sources into your script. In an ideal world, the browser would be able to identify it as a non-trusted script but alas! that doesn’t happen. The attainment of cookies, sessions, and further sensitive details about the browser are some end results of a cross-site scripting attack.

To bypass this issue, you can use htmlspecialchars in the code. You could also embed ENT_QUOTES and escape single/double quotes therein.

htmlspecialchars() helps to convert special characters to HTML entities when put without any arguments. The code below shows a way that you can implement the same. ‘ENT_QUOTES’ are used to ensure that single quotes are encoded, as does not happen in the following otherwise.

‘&’ becomes ‘&’

‘ ” ‘ becomes ‘"’

‘<‘ becomes ‘&lt;’

‘>’ becomes ‘&gt;’

An example of how to incorporate it into the code is as follows.

Code to add htmlspecialchars & ENT_QUOTES

$search = htmlspecialchars($search, ENT_QUOTES, 'UTF-8');
echo 'Search results for '.$search

2) SQL Injection Attacks in PHP

The most common of all attacks in PHP scripting is the SQL injection, wherein the entire application is compromised because of a single query. The attacker here tries to alter the data that the coder is trying to convey through queries. All you need to do is solve the bug using minor changes in the program, including usage of ORM like doctrine or eloquent. You could also try keeping a check on the entry points of such malicious attacks. The step by step protocol to avoid this kind of attack is mentioned here.

Code to fix SQL injection issue

$sql = "SELECT * FROM users WHERE uname = '" .$name. "';
$sql = "SELECT uname, emailadd FROM users WHERE id = ".$pid." ;
foreach ($dbh->query($sql) as $row) {
 printf ("%s (%s)n", $row['uname'], $row['emailadd']);
 $sql = "SELECT uname, emailadd FROM users WHERE id = :pid";
$sth = $dbh->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
$sth->execute([':pid' => $id]);
$users = $sth->fetchAll();

Related PostConsequences of SQL Injection in PHP

3) Cross-site request forgery XSRF/CSRF in PHP

Unlike an XSS attack, a CSRF attack works quite differently and can throw an altogether different series of threats to you. In a CSRF attack, the end-user can bring about ‘N’ number of unwanted actions on authenticated web pages, thereby transferring malicious commands to the targeted site, causing an undesirable action at the end.

CSRF does not read the user’s request and mostly focuses on changing the request solely. In this attack, the attacker forces the user to perform requests such as changing email addresses, transferring funds, etc.

The hacker can also redirect the user to a domain of their wish. The first URL here is to target the user to send money to another account.


These URL(s) can be sent via any email or in any file. You might be asked to download the file or even click on it for a bit. These could also exploit the application by changing the name and amount to something like this:

4) Session Hijacking in PHP

Another kind of attacking that the attackers might use against you is session hijacking. Wherein the attacker secretly steals the session ID of the current user and thereafter gets hold of his applications. This attack generally happens through an XSS attack. But, it could also find happen by gaining access to the folder on a server where session data is stored. There is an entire trick book on how you can prevent this kind of malicious attack sticking to your IP addresses, and a few cheat codes are mentioned below.

$IP = getenv ( "REMOTE_ADDR" );

Since the exact IP address is not provided but rather values such as :::1 or :::127, you would need to be alert of it when operating on the local host. You must invalidate (unset cookie, unset session storage, remove traces) sessions as quickly as possible to take care of the violation that occurs, and also should try not to expose ID(s) under any given circumstance.

Here’s an example for you, which involves never using serialized data stored in a cookie. Attackers might be able to easily manipulate such cookies, leading to unwanted variables in your work. You can thereby safely delete the cookie by using the following code:

Code for session cookie deletion

setcookie ($cname, "", 1);
setcookie ($cname, false);

The first line here ensures cookie expiration inside the browser. The second line denotes a standard method to delete a cookie. The third and final line removes the cookie from your script thereafter.

Related guide – Clickjacking in PHP

5) Hide files from the Browser

Moving on to the next horrifying attack that you might be facing is Attack through browser files. As its name suggests, it is done through your files from the browser. Those who have worked with PHP’s micro-frameworks would know the specific directory structure that places files in order. Specific frameworks such as these enable having different files like configuration files (.yaml), models, controllers, etc in that directory.

Even though the browser doesn’t process every file, they may yet be available in the browser to be seen. In order to resolve this issue and make sure that the files are not accessible, redirect the files to a public folder from the root directory.

Related Guide – Comprehensive Guide on PHP Security

6) Securely Upload Files

Many times, the users are not quite aware of a folder/unknown file is an XSS attack or just a regular file, as it is quite easy for hackers to camouflage it amongst the ordinary. Thus, mitigate this issue by declaring the property encrypt+”multipart/form-data” in <form> tag and using POST request in the form.

Code to add validation rules:

$finfo = new finfo(FILEINFO_MIME_TYPE);
$fileContents = file_get_contents($_FILES['any_name']['temp_name']);
$mimeType = $finfo->buffer($fileContents);

The good thing is, you can create your own customs to define & secure file validation rules. Also, some frameworks like CodeIgniter, Symfony and Laravel already have helpful predefined methods.

Code to add encryption:

<form method="post" enctype="multipart/form-data" action="upload.php">
File: <input type="file" name="pictures[]" multiple="true">
<input type="submit">

7) Buffer Overflows

A buffer overflow is a programming error in common languages c and c++. It occurs due to the writing of codes beyond the boundaries of allocated buffers (memory). The exploitation of buffer overflow is quite a common phenomenon. Any hacker can meddle with the behaviour of buffer overflow by sending in designed data to cross boundaries of the memory and rewrite/overwrite into spaces known to have vulnerabilities.

PHP code does not give rise to a buffer overflow directly. It is the C codes in the PHP engine that causes a buffer overflow security issue in PHP.  You can prevent buffer overflow by writing secure codes, i.e. minimizing the use of unsafe functions, group standards, etc. Further, there are several compiler tools available, which can detect buffer overflow and alter memory allocation.

8) Source Code Revelation

PHP is a server-side scripting language. And as it happens with server-side scripts, the source of code is hidden. For example, when you request the source of .php extension file, the server will cause mod_php to execute the PHP code contained within the file and then return the resulting web page to the user. Thus, it won’t return the request. 

However, in case of server misconfiguration, it returns the scripts as plaintext, revealing its source. This is highly exploitable as some of these scripts might contain sensitive information like database credentials, config file details, etc.

Related Guide – PHP File Permissions

Code to prevent PHP source code

You can prevent your website from source code revelation by adding a rule to detect the opening PHP tag in ModSecurity.

Prevent PHP source code as:

SecRule RESPONSE_BODY "<?" "deny,msg:'PHP source code disclosure blocked'"

Fixing General PHP Security Issues

Use SSL Certificates for HTTPs

HTTPS protocol is recommended by a number of modern browsers for web applications. The S in HTTPS stands for Secure. It provides more secure encryption from accessing non-secure channels of sites. All you need to do to include HTTPS is install an SSL certificate for your website.

The inclusion of SSL certificates in your applications makes it more secure and prevents hackers from intercepting, reading or modifying transmitted data.

Deploy PHP Apps on Cloud

Hosting is the final and most important step when deploying any web application. Make sure to deploy the local PHP servers, on which you make your projects, safely onto other live servers. These live servers give you options to choose among shared, cloud or dedicated hosting.

Professionals recommend to go for cloud hosting like Digital Ocean, Linode, AWS and many more as they are rapid, much more secure and take care of your application just how it’s supposed to be. They tend to provide an additional security layer to fight DDOS, Brute force and phishing attacks that deteriorate your application.

All the skills that you need to efficiently deploy your PHP project on cloud servers are related to Linux. You can create a powerful web stack like LAMP or LEMP, and make your life easier.

Importance of Web Application Firewall (WAF) and Security Audit in PHP Websites

There is a vital role for Web Application Firewall and security audits in resolving the PHP security issues. A Web Application Firewall helps to protect attacks exploiting the security issues in PHP.

Hackers are trying to get hold of web servers every minute of the day, as working on the servers makes it easy for them to attack from a single point instead of different workstations. A server provides hackers with a huge amount of bandwidth and is way more powerful than any single workstation, which eventually makes their attack more efficient.

Astra security for PHP, Laravel, Codeignitor
How Astra WAF secure your PHP website

Therefore, we would like to state that the presence of a Web Application Firewall is quite critical as it secures the website from a wide variety of attacks. What a WAF actually does is act as a filter between the web application and the internet, monitoring all traffic and blocking out any malicious ones.

Next time you visit a website, you should observe if it contains a certificate (published by a certifying authority) ensuring that the website is safe to move forward with.

All in all, there are way too many security issues in PHP scripting that can lead to an overall insecure web application. It highlights the seriousness of weeding out these issues by bringing abroad the mentioned adaptations.


Naman Rastogi

Naman Rastogi is a Growth hacker and digital marketer at Astra security. Working actively in cybersecurity for more than a year, Naman shares the passion for spreading awareness about cybersecurity amongst netizens. He is a regular reader of anything cybersecurity which he channelizes through the Astra blog. Naman is also a jack of all trade. He is certified in market analytics, content strategy, financial markets and more while working parallelly towards his passion i.e cybersecurity. When not hustling to find newer ways to spread awareness about cybersecurity, he can be found enjoying a game of ping pong or CSGO.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Newest Most Voted
Inline Feedbacks
View all comments

[…] on the help forums. Apart from SQLi, unsafe development practices also make the sites vulnerable to XSS, CSRF, RFI etc attacks. According to John D. McGregor, author of Practical Guide to Testing Object-Oriented […]

Psst! Hi there. We’re Astra.

We make security simple and hassle-free for thousands
of websites and businesses worldwide.

Our suite of security products include a vulnerability scanner, firewall, malware scanner and pentests to protect your site from the evil forces on the internet, even when you sleep.

earth spiders cards bugs spiders

Made with ❤️ in USA France India Germany