PHP Security

A Step-By-Step Guide On PHP Security

Updated on: July 26, 2020

A Step-By-Step Guide On PHP Security

As of 2020, over 79% of server-side language was PHP. Most of these are content management systems including eCommerce sites and WordPress. As it is such a widely-used programming language for websites, including Facebook and Wikipedia, it is under continuous threat of attacks and exploitations. PHP security has become very important to keep websites and platforms safe from cyber-attacks and hacks.

Due to the advancement in cyber-attacks and hacking techniques, the risks of attacks have become greater. To add to that, PHP is fragile too. A small bug or coding error can make your PHP website vulnerable and prone to attacks.

After putting in so much effort into building a PHP website getting hacked is the last thing on anyone’s mind. But to really make your PHP tech stack impenetrable and unhackable, you have to ensure rock-solid security.

To help you with that, we have put together this extensive PHP security guide. This guide will help you identify PHP security threats and ways to strengthen your website’s security. It also has some effective security measures that you can follow to keep its security intact.

All that in a minute, but first, let’s look at these PHP hacking statistics.

Some statistics about PHP security

  • WordPress uses PHP as its scripting language. Over 35% of websites use WordPress and it has one of the highest numbers of vulnerabilities. In 2018 alone, WordPress had 542 vulnerabilities.
  • The most common attack techniques on a PHP based website are – SQL Injection and XSS attacks.
  • According to a report, hackers steal about 75 records every second.
  • In 2019, there was an attack every 39 seconds with over 30,000 websites hacked every day.

PHP Security threats and fixes

Over the years hackers have invented smart ways to trick and bypass every little feature on a PHP website. Some of the most popular attacks with hackers are:

1. SQL Injection

SQL Injection is a very common form of attack accounting for about two-thirds of all web attacks. With improper or ineffective code leading to a SQL Injection attack, a data breach can occur resulting in the leakage of important details such as credit card details and credentials, to name a few. It can also compromise an entire web server. Below is an example of an insecure code snippet:

PHP security
Type caption (optional)

An attacker can send in a query that will be executed along with the query, like below:

php security
Type caption (optional)

The above query will modify the code as follows:

php security
Type caption (optional)

By using scripts similar to the above code, attackers can get access to all data tables and sensitive information.

The solution to this is to use parameterized SQL queries and PHP Data Objects (PDO). Using parameterized queries will let the database differentiate between the data and query parts. Thus, it can then treat the two parts separately. PDO is included in PHP version 5.1 and later, and you can use it to execute prepared snippets in your code.

To further protect your website you can do the following:

  • Filtering your data: With proper filters for your input data you can stop any suspicious or malicious codes from entering your system
  • Using quotes in your data: If allowed in your database, then use quotes in all values in SQL statements
  • Use escape characters: In some cases, genuine data can interfere with SQL statement formats. To avoid that you can use functions such as mysql_escape_string()

2. Directory Traversal

In this attack, one can view or execute crucial files and folders that should be inaccessible to everyone but the administrators. These files may reside outside the root folders and with incorrect file permissions or coding error these files may be vulnerable to unauthorized access. The below code sample will allow for queries that can access files:

Type caption (optional)

If an attacker enters “/etc/passwd” as an argument then it will return this file as it is accessible to all. To prevent it you need to apply proper permissions based on the user’s status.

3. Cross-Site Scripting (XSS attacks)

XSS vulnerabilities are very common and this makes this attack widely used. In this attack, client-side scripts are inserted into the output of a webpage and then these scripts are executed on the user’s system. Attackers use this attack to steal information, credentials, or cookies, to name a few. XSS attacks are also common in websites that display external data.

The following vulnerable code snippet can be exploited to launch an XSS attack:

Type caption (optional)

When the attacker passes codes such as <script>alert(“XSS”);</script> to this webpage, it will get executed and display “XSS”. This shows how external malicious codes can be injected and executed to cause damage.

You can prevent such attacks by following the below steps:

  • Filtering all external data: If you filter all incoming and outgoing data from your website you can stop most of the XSS attacks
  • Existing functions: PHP has a couple of functions you can use such as htmlentities(), utf8_decode() and strip_tags(). Using these functions will save your time and since they are inbuilt they will have less vulnerability
  • Using strict naming conventions: Using a strict naming convention will help in distinguishing between filtered and unfiltered data, which will be beneficial in the development phase

4. Cross-site request forgery

Cross-site request forgery attacks are done from the user side and exploit the trust that webpages have on users. Users having higher privileges face the highest threats. This attack is less popular than others and is thus more dangerous. Protecting your website from such attacks is also more complicated as compared to the ones mentioned above. When users log into a website, they receive certain privileges such as accessing pages not available to others. Using these privileges, attackers can design HTTP requests that are then executed by the webpage. Attackers can use this technique to access the database or extract important information.

The below PHP security steps will help you prevent such attacks:

  • Using POST instead of GET in all forms: You can use POST in forms that allow it, specifically those that can perform any actions
  • Using HTTPS: Using HTTPS has become the new standard and rightly so. HTPPS encrypts the connection between your website and the user. It might not be the one-stop solution to prevent CSRF attacks but it strengthens your PHP security and protects your website from a range of other attacks
  • Adding basic challenge-response authentication mechanisms: One way to verify the authenticity of forms is to hide a form attribute in every form. And populate the attribute with a randomly generated cryptic value that can be verified and matched to ensure that the form is safe

5. Password storage

With the increasing cases of credential theft and data dumping on the dark web, storing credentials such as passwords securely has become much more important. Attackers can leverage vulnerabilities such as SQL Injection or XSS attacks and access passwords stored within the website. In case there is a breach of security, it is important to ensure that attackers are unable to decode the passwords and cause further damage. There are two important ways to securely store passwords, using a hashing algorithm and salt.

The most common hashing algorithm is MD5 and it is the fastest. However, it is easy and fast to crack. You can use the password_hash() function instead of MD5, as it is more secure. This function generates a sixty character hash based on BCRYPT (CRYPT_BLOWFISH algorithm). It accepts three parameters: the password, hashing algorithm (by default uses BCRYPT), and an optional value such as cost. You can verify the hashed password by using password_verify().

Type caption (optional)

Salt is a random string that is added to the password before hashing it. A long and random salt will effectively make cracking methods ineffective.Some more PHP security tips to ensure that passwords are safely stored:

  • As mentioned above, avoid using basic and weak hashing algorithms
  • If using salt, do not reuse weak salts. Password_hash() can select random strong salts by default
  • Find a sweet spot between the cost and strength of hashing algorithms. Having a higher cost value will result in stronger hashes but it might affect server performances

6. Session hijacking

Session hijacking attacks are the most common form of session attacks. This attack includes accessing an unsuspecting user’s session and then launch further attacks. Once hijacking is successful the attacker can perform all tasks that the original user had permission for. In case the user’s session was to log into their bank accounts, attackers can make transfers or take over the account entirely. This attack can also provide access to company-wide networks, in case the session belongs to an employer in an organization.

This attack can be done by simply having the session identifier. To prevent session hijacking attacks, websites have to verify a couple of details in the HTTP request and analyze them to identify a genuine session. Attackers trick the website by passing in such information that is then interpreted to be authentic and allows the session to continue. An effective way to stop such attacks is to look for such fields that will be difficult for the attacker to generate. These fields can then be used to verify the authenticity of the session. Fields such as user-agent are difficult to replicate by an attacker. Also, checking for location details and browser information and matching them with historical data can provide some insights as to the current session.

In order to not impact the user experience, if, in doubt, websites can request a password entry to authenticate. Users will appreciate the extra precaution and the system will not lock out a genuine user.

7. Session Fixation

In session fixation, the attacker sends the user a valid session ID and then uses that to get into the website. The attacker creates a session and then waits for a user to use the attacker’s session ID to log into the website. Then the website will consider the session authentic and allow the attacker to use this session without any interruptions.

If a website extracts session IDs from URLs or forms, it is easy for attackers to use this method of attack. In this case, the user only has to click on the link, and the website will then append the attacker’s session ID to the user. This can also be done with cookies by setting it to the attacker’s session ID.There are two major ways to stop such attacks:

  • Using cookies: Though this method is vulnerable to this attack, it is much more difficult for the attacker as compared to websites accepting session ID from POST or GET variables. Additionally, you will have to protect the cookies from XSS attacks by using the steps mentioned above
  • Session ID regeneration: Once the user has logged in, the website can be configured to provide the user with a fresh ID. This will ensure that even if the user was using the attacker’s ID to log in, it will be detached once the user receives the new ID. Thus, the attacker will not have access once the user has logged in

Session data exposed

If you use a shared server then your sessions might be stored in a shared session store. If this is the case with your server, then your website’s sessions are vulnerable to unauthorized access. In this, with the below code, attackers can easily access the session stored in the “/tmp” folder by default:

Type caption (optional)

This is a simple PHP query that can use the server privileges to access and read the files. To prevent this, you can use safe_mode directives but as it only works for PHP, attackers can use other languages to do this. A better solution is to avoid using a shared session store. Store the data in a database that has unique access credentials related to your account. To do this, you can use session_set_save_handler() function to replace PHP’s default handling of sessions with your own functions.

Related guide – Clickjacking in PHP

XML Attacks

For this attack, attackers exploit the parsing feature of XML inputs. If XML parser is weakly configured then it will parse an XML input with reference to external sources. There are two major vulnerabilities that can be exploited: XML External Entity and XPath Injection. These attacks form a base for further attacks such as remote file inclusion exploits.XPath Injection is similar to SQL Injection but is applicable to XML documents. As this type of attack is rare, there is comparatively less inbuilt functions and mechanisms to protect against it. You can use a set of whitelisted characters to make sure that unwanted or special characters are not accepted.

Type caption (optional)

PHP security tips and tricks

Security is an essential part of the development and just as attacks have evolved over time, security has to evolve too, to match the pace. Security of a website is not only important to the website owner but also users who risk their information in case of cyber-attacks. We need to understand a few points regarding security to enable us to take proper steps:

  • Security is not a characteristic: There is no single answer to whether a website is secure or not. Security is ever-changing and there is always a chance that an attack will breakthrough. Regular evaluation and updates are required to keep PHP security up-to-date and protect against newer methods of attacks
  • Security and expense: Basic levels of security will protect your website against most of the attacks. However, if your website handles high-value information then you will need to spend more to get more advanced security as threat levels me higher. While in the development phase, you will have to account for the security expense based on your website and threat perception
  • Security and usability: The convenience of using your website matters a lot to users. Very often too many security checkpoints might be hindering the usability of your website. Multiple login requests, quick session timeouts, and multiple authentications can be seen as obstacles by users. There is no one size fits all security protocol. Security has to be determined based on various factors such as application or information being handled. Usability and security need to be balanced for great user experience and sufficient levels of security
  • Security as a part of the design: Security is an inherent part of a website. Development needs to be done by taking security into account so as to make sure that security is present at all levels of your website

As discussed above, PHP security is always under threat but it can be tackled if we implement a few essential security protocols and follow guidelines. Below are some security tips that will help in strengthening PHP security:

Validating inputs

For PHP security, having client-side data validation is not enough. It can be easily broken through, for example, if an attacker removes any JavaScript from the source code of a website and then submits a form without any verification, it will not be detected if there is no server-side validation. This opens up a way for attacks such as SQL Injection, XSS or CSRF attacks. Both the user side and server-side validation is essential for PHP security.

Blacklisting

Blacklisting can be circumvented by attackers through trial and error methods. It does not always protect against malicious inputs but in some cases, it can protect against known or common attack methods. You can blacklist common strings used by attackers or special characters that are known to be dangerous.

PHP security issues & prevention steps

Research

In the development phase, researching about bugs or security threats is useful as we come across several methods and solutions. However, copy-pasting those codes is not a good idea. Your website might be different from the one the solution if from. Also, they might be outdated and you will be putting your entire website server at risk. If you copy codes from several sources then there is a change that all code snippets might not work together and linking them will require substantial effort. Research helps in answering a lot of questions, however, using it as a source of understanding is a better option than copying codes.

Strong passwords

This cannot be stressed enough. A major portion of attacks is possible due to weak or easily breakable credentials. A strong password can be alphanumeric with both lower and upper case characters. Another option is to use phrases as it will take considerable time and computational power to crack such passwords. Also, make sure that all default passwords are changed, by both users and admins. Assist your users in using a stronger password by making them aware of its importance and guidelines they can follow.

Multi-factor authentication

Multiple level authentication has become the new security standard. In this case, attackers will be unable to cause any damage if they have the credentials as it will require an additional field such as OTP (One-time passwords) to log in. In 2 Factor Authentication, users will have to enter an additional code after they use their credentials. To get through this, attackers will require the credentials as well as control of the device receiving OTP.

Related Guide – PHP File Permissions

Data filtering

Proper data filtering will protect your website from malicious code snippets and code injection attacks. There are multiple ways to enable effective data filtering. Include method means having a single module dedicated to security that is placed at the beginning of all scripts that are publicly accessible. Multiple security checkpoints and protocols can be included. For filtering data, you can use a whitelist approach and include several combinations of characters and strings.

Using a firewall

A firewall is all-round protection for your website. It filters all unwanted and malicious data and requests from reaching your website. A strong firewall like Astra will offer complete protection from attacks such as SQL Injection, DDoS, and malware, to name a few.

At Astra, we have intelligent & efficient tools and security expertise to offer you complete protection against all cyber threats. Dashboard and reports will keep you updated with everything that goes on with your website.

Firewall working
How Astra Web Application Firewall protects your website

PHP security tips listed in this guide will help you keep your website safe and ensure that data on your website stays safe. Security is dynamic and ever-changing, so staying updated with all the latest developments will help you protect your website from advanced attacks. Using a security service will help you in this without any hassle. Leaving your PHP security to an expert like Astra is probably a good idea. A lot of effort and hard work goes into creating a website, and protecting it is a tough but important task. With proper understanding and accurate information, you can keep attackers at bay.

Don’t take our words for it. See it for yourself!

Peek inside Astra

Was this post helpful?

Ananda Krishna

Ananda Krishna is the co-founder & CTO of Astra Security, a SaaS suite that secures businesses from cyber threats. He has been acknowledged by the Indian Navy, Microsoft, United Airlines, etc. for finding critical security vulnerabilities in their systems. Winner of the Best Security Product at Global Conference on Cyberspace 2017 (awarded by Narendra Modi, Prime Minister of India) & French Tech Ticket, Paris (awarded by François Hollande, former President of France).At Astra he's building an intelligent security ecosystem - web application firewall (WAF), malware detection & analysis, large scale SaaS applications, APIs & more. He's actively involved in the cybersecurity community and shared his knowledge at various forums & invited talks.
guest

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

0 Comments
Inline Feedbacks
View all comments

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 firewall, malware scanner and security audits 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