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

Designing a web page is one of the most fascinating yet challenging jobs in the current scenario. We need high-end developers to take care of the efficiency, the security and the user-experience of any website. There are many technicalities like these that the developers have to face in the process of bringing out the final outcome, i.e. a website free of all vulnerabilities. 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. PHP is dramatically the most criticized languages 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.

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, we will discuss a few of the most common PHP security issues and their fixes.

1) PHP Security Issues: 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! The attainment of cookies, sessions and further sensitive details about the browser are some end results of a cross-site scripting attack. What you can do to overpass this issue is to 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 mentioned as follows.

Code to fix cross-site scripting issue in PHP

$search = htmlspecialchars($search, ENT_QUOTES, ‘UTF-8’);

echo ‘Search results for ‘.$search

2) PHP Security Issues: 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) PHP Security Issues: Cross site request forgery XSRF/CSRF in PHP

Unlike a XSS attack, a CSRF attack works quite differently and can have an altogether different series of threats planned for 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.

Let us now see what we could do to get to these malicious attacks. And then redirect the user to whatever you wish to do with them. The first URL here, is to target the user to send money to another account.

GET http://bank.com/transfer.do?acct=TIM&amount=100 HTTP/1.1

These URL(s) can be sent via any email, 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:

http://bank.com/transfer.do?acct=Mandy&amount=280000

4) PHP Security Issues: 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. You need to go through an XSS attack for this attack to be possible, or it could find other channels like 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 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 to fix session hijacking issue in PHP

setcookie ($cname, “”, 1);

setcookie ($cname, false);

unset($_COOKIE[$cname]);

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.

5) PHP Security Issues: Hide files from the Browser

Moving on to the next horrifying attack that you might be facing is Attack through browser files. As it 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 which makes sure that their files are placed in order. Specific frameworks such as these, enables 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, they need to be redirected to a public folder from the root directory.

6) PHP Security Issues: 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. Declaring the property encrypt+”multipart/form-data” in <form> tag and using POST request in the form is recommended.

Code to fix this PHP security issue:

$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 fix the issue:

<form method=”post” enctype=”multipart/form-data” action=”upload.php”>

File: <input type=”file” name=”pictures[]” multiple=”true”>

<input type=”submit”>

</form>

Fixing General PHP Security Issues

Use SSL Certificates for HTTP

HTTPS protocol is recommended by a number of modern browsers for web applications. The S in HTTPS stands for Secure. It provides a much more secure encryption from accessing channel for sites which are not well trusted. 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 the most important step when deploying any web application. You need to be on top of your game to make sure that the local PHP servers that you always create your project on, are deployed safely onto other live servers. These live servers give you options to choose among shared, cloud or dedicated hosting.

It is mostly recommended by professionals 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 webstack 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.

Waiting to Get Hacked?

Get security tips & latest vulnerability fixes right in your inbox:

About The Author

Naman Rastogi

Naman is a Digital Marketer at Astra.

1 Comment

  1. Laravel or Codeigniter Website Hacked: These Laravel or Codeigniter Vulnerabilities Can Be The Cause - Reply

    […] 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 […]

Leave a Reply

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

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

Close