- Jul 01, 2021
- by Word Candy
As a responsible website owner, you likely want to do everything in your power to keep your visitors safe. However, there’s one aspect of security that’s easy to overlook: Hypertext Preprocessor, better known as PHP.
PHP is the backbone of many websites and applications, including WordPress sites. So it’s important to familiarize yourself with relevant security practices for it and follow them carefully. Fortunately, out-of-the-box PHP has all of the features and functions you need to protect your site against hackers.
In this post, we’ll discuss what PHP is and why it’s essential for website security. We’ll then share eight ways that PHP can protect your site against a range of attacks, including session hijacking, Cross-Site Request Forgery (CSRF), and Cross-Site Scripting (XSS). Let’s get started!
An Introduction to PHP (And Why It’s Important for Web Security)
PHP is a server-side programming language that’s used in many Content Management Systems (CMS). This includes WordPress, which uses it as the scripting language:
PHP is used by 79 percent of all the websites whose server-side programming language is known. Since most sites are created with PHP, it’s a popular target for hackers. If an attacker manages to uncover a PHP vulnerability, they could potentially use the same attack against millions of websites – including yours.
If your site is compromised, a hacker could steal your data. Even worse, if you take payments on your site, a security breach could result in your customers’ credit card information being hijacked or even published.
This will have immediate consequences for your business by damaging customer trust and your reputation. However, it can also have long-term financial implications. In 2020, researchers estimated that the average total cost of a data breach was $3.86 million. By learning proven security practices for PHP, you’ll be in a strong position to fend off these attacks.
Top 8 Security Practices for PHP
Hackers are always looking for ways to break into your site, including exploiting your website’s PHP. Let’s look at eight actions you can take to ensure that PHP doesn’t give attackers a route into your data.
1. Update Your Version of PHP Regularly
New versions of PHP often introduce fixes for security vulnerabilities. If you’re not running the latest version, hackers could potentially expose those known weaknesses. Therefore, keeping your software up-to-date is one of the most important security practices for PHP.
You can check the latest stable release of PHP over at the official website. If you’re not running this version, your site may be at risk.
If you’re unsure which version of PHP you’re currently using, don’t worry. You can find this information on the WordPress Site Health screen. Assuming that you have WordPress 5.0 or higher installed, navigate to Tools > Site Health > Info > Server:
The PHP version is set at the server level, so if you’re running an outdated version, you may need to contact your hosting provider. If you have an A2 Hosting managed Virtual Private Server (VPS) or managed server account, you can open a support ticket specifying the version of PHP that you want to use. Our Guru Crew will upgrade you to your chosen version.
If you have a shared or managed hosting account, you can switch between different PHP versions using the cPanel control panel. Simply log into your cPanel account and launch the Select PHP Version tool:
Next, open the Current PHP drop-down menu and choose any release from the list. We’ll change you over to that version immediately.
Alternatively, if you manage your account using the Plesk control panel, you can log into the A2 Hosting Customer Portal and navigate to Services > My Services:
Under My Products & Services, locate your hosting package, then click on Manage > Open Control Panel. Next, in Plesk, select Websites & Domains > PHP Selector. Finally, you can select the desired version of PHP and click on Set as current.
2. Install a Secure Sockets Layer (SSL) Certificate
A Secure Sockets Layer (SSL) certificate is essential for securely transferring files via HyperText Transfer Protocol Secure (HTTPS) instead of HyperText Transfer Protocol (HTTP). This certificate is important for any website, but it’s particularly vital if you collect or transmit sensitive information, such as customers’ payment details. If your site features login functionality, an SSL certificate can also prevent malicious third parties from eavesdropping and stealing visitors’ usernames and passwords.
At A2 Hosting, we provide a range of SSL certificates from a wide variety of providers. We’re confident you’ll find a solution that meets your exact needs:
After purchasing a certificate, we’ll send you an SSL Token via email. This is the key to installing your certificate and protecting your data against hackers.
If you’re a cPanel user, you can log into your account and launch the AutoInstall SSL tool. Next, you can paste your SSL Token into the field and click on Verify token:
After submitting a valid token, cPanel will prompt you to enter more information about your certificate and your website. After providing these details, AutoInstall SSL will upload your certificate, and after a few moments, your site will be protected with SSL.
If you manage your site using Plesk, you can log into your account and select Websites & Domains > SSL Certificates. You should then see the SSL certificates page for your domain.
In the Upload, the certificate as text section, paste all of the text from your SSL certificate, including the
BEGIN CERTIFICATE and
END CERTIFICATE headers. Next, go ahead and click on Upload Certificate, and Plesk will install your SSL certificate.
3. Protect Against XSS Attacks
XSS attacks occur when a hacker exploits a vulnerability on your website. As part of this intrusion, the agent will upload a malicious script, which can then be executed on the client-side in the browser. The cybercriminal may also execute the script on your server.
Nefarious third parties often use XSS attacks to steal data, including your customers’ passwords and payment information. Some invasions can even change how your site looks or behaves. For example, hackers might use an XSS to redirect your visitors to another website.
XSS attacks are hugely popular with cybercriminals. In 2020, Wordfence identified 330 million attempted XSS attacks, making it the fourth most commonly attacked category of vulnerabilities.
You can protect against this frequent attack by sanitizing your data. PHP’s
filter_var contains disinfection indicators that enable you to check all user-submitted data. You can then remove all values that aren’t of the expected type. For example, if you make a call to
filter_var ($ val, FILTER_SANITIZE_NUMBER_INT), all characters that are not numbers will be deleted. This can help ensure that you’re receiving legitimate data and not malicious scripts.
You can also use validation to verify that user-submitted values match your expectations. You can perform this validation using the
filter_var security practices for PHP function, such as
filter_var ($ _GET [’email’], FILTER_VALIDATE_EMAIL).
If this function provides an error, the data is likely invalid. You can learn more about these important security practices for PHP at the official validation features documentation.
4. Use Prepared SQL Statements
If you insert any user input directly into an SSL statement, you’re leaving your site vulnerable to SQL injection attacks. This is where a malevolent third party attempts to break the intended SQL query and instead queries for different information, such as a customer’s payment details.
To protect against these injection attacks, it’s important to ensure that the inputted values are properly escaped. You can achieve this by using a prepared statement to execute all of your SQL statements.
As part of a prepared statement, the SQL statement template is created and sent to the database. The database then parses, compiles, and performs query optimization on the SQL template and stores the result without executing it.
The application then binds the values to the parameters and executes the statement. Since the parameters are transferred later using a different protocol, this leaves no room for an SQL injection attack.
You can also validate the data type of the input using the
bind_param function. This function binds the parameters to the SQL query and tells the database what these parameters are. For example:
$stmt->bind_param("sss", $firstname, $lastname, $email);
Here, SSS lists the types of data that these parameters should include. These arguments can either be:
s (string), or
b (BLOB). By telling the database what type of data to expect, you can further minimize the risk of SQL injections.
5. Protect Against CSRF Attacks
CSRF occurs when a hacker performs unwanted actions on your website. As part of this attack, the nefarious third party attempts to transfer malicious commands to your site.
The intruder cannot see the responses to the forged requests, so CSRF attacks mostly target state-changing requests. The cybercriminal may send a link or alter data in an HTML tag, which triggers a change of state, such as transferring funds or modifying the user’s login credentials.
To launch a CSRF invasion, a hacker must know the parameters and value combinations that you use in your user-input fields. You can help the server spot invalid requests by adding an extra parameter with a value that is unknown to the hacker.
One approach is to use an anti-CSRF token. This is a random string that is known only to the visitor’s browser and your web application. It is typically stored inside a session variable. You can add this token in a hidden field that gets sent with the request.
The server will only accept your request if the values of the session variable and the hidden form field match. Due to the same-origin policy, hackers cannot read the response that contains the token.
Alternatively, you can use the SameSite cookie attribute. This prevents browsers from automatically adding cookies to requests, regardless of where they originate. You can add the SameSite attribute to the SetCookie response header when the server issues a cookie:
SetCookie: SessionId=sYMnfCUrAlmqVVZn9dqevxyFpKZt30NN; SameSite=Strict;
If you set the
SameSite attribute to
Strict, the browser won’t include the cookie in any requests that originate from another site. However, this can impact the User Experience (UX). For example, if a logged-in user follows a link to a third-party site, they will appear not to be logged into their account.
6. Bind Your IP Address With Session ID
Session hijacking occurs when a hacker secretly steals the visitor’s session ID. This ID is then sent to the server, where the
$_SESSION array validates its storage in the stack.
At this point, the hacker will have access to the web application. Session hijacking can occur via an XSS attack, or when the agent gains entry into the directory where you store session data.
To prevent this from happening, we recommend binding the session ID to other user or client properties. One possible way to do this is by binding the session to the client IP address:
$IP = getenv ( "REMOTE_ADDR" );
If the web application detects any changes to this property in the middle of an established session, it is a strong indication that a third party is attempting to seize the session. You can then take action to protect your website and your visitors. For example, you can terminate the suspicious session.
Just be aware that a skilled hacker may be able to reuse the same IP address that’s assigned to the visitor. They can achieve this by using the same outbound web proxy or manually modifying the User-Agent to mimic the visitor. However, while the binding isn’t guaranteed to protect you against this kind of sophisticated session hijacking attack, it can make your site less susceptible to one.
7. Hide All Errors in Production
Error messages are vital when building and testing your website. These messages can provide valuable information about any problems with your site, which can help you resolve the issues more efficiently. Error notifications can also highlight subtle problems you may not otherwise have noticed.
Unfortunately, hackers can weaponize error messages against you. A cybercriminal might use the information contained within them to learn more about your site and identify any security loopholes that they can exploit.
For this reason, it’s important to hide error messages when deploying your site on a live server. To achieve this, we recommend that you set the following parameter in your site’s php.ini file:
Typically, you won’t want to discard these error messages entirely, as they can be useful for diagnosing any future issues that occur. You can log PHP errors in a specific file using the following command:
This will record all of your PHP errors to a file named php_error.log. You can change the name of this file if desired.
8. Choose a Reliable Hosting Provider
Hosting is a crucial factor in securing your site against a wide range of attacks, including those that specifically target PHP. At A2 Hosting, all our hosting packages come with a range of built-in security features, including HackScan Protection, which can help block hackers before they damage your site:
We also offer KernelCare rebootless kernel updates, a dual firewall, and Cloudflare as standard. Cloudflare in particular can identify and block malicious requests before they reach your site, which can prevent hackers from exploiting a wide range of PHP vulnerabilities:
We also understand that every website’s security needs are unique. That’s why we ensure you have easy access to all the add-ons you need to secure your particular website. All of our packages include the user-friendly cPanel control panel and Softaculous installer:
This installer provides you with easy access to software, tools, and extra configurations. By taking advantage of Softaculous, you can feel confident that your site is properly protected against malicious third parties.
Security is an important topic that generates lots of attention. However, many website owners focus on protecting their sites against attack and sometimes overlook their programming language.
By following security practices for PHP, you can close a potential loophole and defend your site against a wide range of common intrusions. To start, it’s essential to get the fundamentals right by installing the latest version of PHP. Then you can shift your focus to protecting the data submitted to your website via advanced security practices for PHP, such as prepared SQL statements and data sanitization.
To set your site up for success, it’s also critical to choose a hosting provider that takes security seriously. At A2 Hosting, all of our packages come with built-in security features that can help strengthen your defenses against all the popular PHP-based attacks, including XSS!
Image credit: Pexels.