Laptop Bed1

Now more than ever, people, developers, and businesses alike consider PHP a dying language and that it might have no place in the IT/Dev World. However, PHP is one of the most popular programming languages still in use today. It is used by millions of websites, roughly around 80% of all websites, including some of the biggest names on the internet. PHP still dominates server-side web development whilst still being flexible and adaptable to a developers needs.

While PHP is a very powerful language, it can also be quite insecure if not used properly. In this article, we will discuss eight best practices for PHP security that will help keep your website safe from hackers and malicious users. We will also talk about application pen testing and how to use it to find vulnerabilities in your code.

How Is PHP Used Today? Is It Still Relevant?

As many programming languages over the years share the same tendency in declining, PHP just happens to be the exact opposite. Being that PHP is widely used for a vast majority of websites out there today, it is only fair to say that PHP is on a continuous rise. Amongst being one of the easiest programming languages to learn and use, it is also considered one of the best server-side languages to use due to it having the functionality of embedded HTML. Moreover, the development of PHP over the recent years, on top of it being open source (AKA Free!), has made it a favorite for many developers and businesses

How Does Application Pentesting Help Businesses?

Application penetration testing is pretty self-defined: you are essentially penetrating your applications/web applications. Simply put, it is the process of identifying vulnerabilities in software by simulating various attacks on the web application. This type of testing can be used to find flaws in the code that could allow attackers to gain access to sensitive data or take over the website. Regular web application pen testing will allow you to find lack of secure coding practices, misconfiguration vulnerabilities, such as XSS and HTTP Headers, broken authentication and access controls and information leakages and remediate these issues before a Cyber Criminal has the chance to exploit them.

8 Best Practices for PHP Security

1. Always use the latest version of PHP

Before anything, always make sure your PHP is UP TO DATE! New versions of PHP are released regularly with security fixes and improvements so by using the latest version, you’ll have the benefit of these fixes and improvements as well as any new features that might be helpful for your website. Look at the link attached for a list of the most recent, and old, releases: PHP: Releases.

2. Properly configure the PHP.ini file and other requisites

Believe it or not, most security flaws come from misconfiguration. There are a couple changes you can make to the PHP.ini file to make it more secure but first, let’s start with the following settings that need to be tailored to your specific system:

session.save_pathPhp 151199  340

session.cookie_path (e.g. /var/www/mysite)

session.cookie_domain

After configuring those settings properly, there are a couple other settings you can edit to keep your PHP application secure. Let's take a look at the checklist below:

  • expose_php = Off
    • This restricts the disclosure of PHP version from being sent in HTTP Headers. When enabled, expose_php tells everyone that PHP is installed on that specific server or system, which includes the PHP version within the HTTP header, e.g (Powered by: PHP/8.1.2). You can do this for any system and works well if you are using nginx.
  • allow_url_include=Off
    • Setting this to off prevents remote code execution attacks.
  • display_errors = Off
    • This displays whether errors should be printed on the screen to everyone visiting the site. This should be disabled as a best security practice. 
  • session.cookie_httponly = 1
    • Setting this to 1 disables access to cookies via Javascript APIs but use this with caution as you could break something
  • session.use_strict_mode = 1
    • Setting this to 1 prevents session fixation attacks
  • session.cookie_secure = 1
    • This requires cookies to strictly transmitted over HTTPS only
  • session.cookie_samesite = Strict
    • Setting this to strict prevents cross-origin attacks
  • session.use_trans_sid = 0
    • This is not needed so set it to zero
  • session.sid_length = 128
    • Here, we are setting the length of the session string which prevents brute force attacks
  • session.sid_bits_per_character = 6
    • This increases the randomness of the session string which also prevents brute force attack
  • file_uploads=off
    • Here, we are disabling file uploads. If anyone needs to upload files, you can set a limit on the size of the files by doing upload_max_filesize = 1M

3. Use up to date code dependencies, third party components, and update your web server!  

In addition to using the latest version of PHP, you should also keep your code and web server up to date! This includes any third-party libraries or frameworks that you’re using. Outdated software is often the target of attacks because hackers know that it is more likely to have vulnerabilities that can be exploited. You want to make sure you only have the necessary libraries installed and that everything is up to date. If you use Apache Web Server, then here are a few common best practices:

  • Always Keep your Apache Version Updated.
  • Turn on Error Logging
  • Get an SSL certificate
  • Add a Firewall
  • Install mod_evasive.
  • Set HTTP Limits
  • Never Keep Unused Modules

One of our favorite practices is installing mod_evasive as that helps your server stay running in the event of an attack. Another one would be getting an SSL certificate. If you are using Apache web server, or any other for that matter, having an SSL certificate is important as it does an SSL handshake before it receives the HTTP request that contains the Host header. Ultimately, it provides more security for online communication.

4. Do not store passwords using reversible encryption

There are a few key reasons why reversible encryption is harmful. Firstly, it can easily be cracked and decrypted, making your data vulnerable to theft or exposure. Second, it can be used to spy on or track your activities, since the encryption and decryption process leaves a clear trail of activity. Finally, it can be used to enumerate all other user passwords also given there is a static key in use for encryption and decryption process.

Instead, you should hash the passwords with a strong hashing algorithm like bcrypt, AES two-way encryption with openssl, or even Argon2 which has won the Password Hashing Award. Outputs prepared using hashing algorithms are less vulnerable to attacks than encryption algorithms. This makes them more secure for storing passwords or other sensitive data due to the sheer computing power required to find clear-text (decryption) equivalents. Additionally, hashing algorithms are much faster than encryption algorithms, making them better suited for use in applications where speed is important. PHP already has bcrypt built in so you wouldn’t have to worry about downloading any external dependencies.

5. Don’t rely on cookies for security

Cookies are often used to store information about users, such as their login status, username, preferences or even sensitive information. However, cookies are not inherently secure and can be easily stolen by attackers. If you need to store sensitive data in a cookie, you should encrypt it first. Just like Password hashing, we are adding another layer of security. You can use tools such as halite powered by libsodium or if you’d like to be more technical, you can use something like openssl or possibly even AES 256 bit with CBC mode encryption.

6. Validate user input

All user input should be validated before it is processed by your PHP code. This includes data entered into form fields, URL parameters, and JSON payloads. PHP has filter_var() function to validate variables. We can set its second parameter to different values and use it to validate emails, URLs, integers, etc and this function returns false on failure or invalid input. A way you can implement the filter_var() function can be seen in the example below:

function is_valid_email($email = "")

 
 

{

 

  return filter_var(trim($email), FILTER_VALIDATE_EMAIL);

 

}

The function above was created by myself. This function checks if an email is valid using filter_var(). 

By validating user input, you can help prevent Cross-Site Scripting (XSS) attacks and other types of malicious input.

7. Perform regular security audits

Regular security audits can help identify vulnerabilities in your website and fix them before they can be exploited by attackers. By auditing your code, you canSecurity 2168233  340 also ensure that it is up to date and follows best practices for PHP security. Moreover, it helps you get faster response times, more reliable application performance, and it eliminates bottlenecks on top of future-proofing your web applications. Performing audits can scan for the following such as:

  • Cross Site Scripting Vulnerabilities (XSS)
  • Cross Site Request Forgery Vulnerabilities (CSRF)
  • SQL Injections
  • PHP Code Injection
  • Cookie Denial of Service Attacks
  • Timing Attacks

8. Use PHP Libraries

PHP does a good job of providing developers with some functionality, meaning that they provide us with functions that we can use to secure our applications better. You can use the following:

urlencode - allows coders to construct valid URLs safely. According to the PHP documentation, the function is useful for encoding a string that will be used in a URL’s query section.

<?php

echo ‘<a href=”mylink?user=’, urlencode($userID), ‘”>’;

?>

Use prepared SQL statements like below:

https://lh3.googleusercontent.com/-h9CFE0EPb6pqB9HuywhuqA9i6L160pbDWkKjKKoRSixRtJREbNURTy6QJCAcSJkFO5_ORwlbuzlUdE8VLuRP_5n3Ht9kzJoSbjMSgW-aMyx6gOS6EnPuHyEISaBUEHjm8ltmTV6pqHSnbT_QQJWK7o

Conclusion

Following these best practices will help you secure your PHP applications and protect them from attack. Remember to always keep your software up to date, properly configure your web server and your PHP, and be sure to perform regular security audits to identify any vulnerabilities that may have slipped through the cracks. We hope you found this article useful and we hope you check out our other articles that may help in keeping your systems secure!