How to Secure Your Website From Cyber Attacks With PHP
Your website is the front door to your business. Visitors come in, take a look around and in some cases give their information. This is also known as hackers. They test the handle on each door, every day, all day long.
PHP provides tools that help protect your website from common attacks. But you need to use them correctly and keep the rest of your website secure, too. Bad news: They only work if you use them. No one can guarantee that a website will never be attacked. But you can make it much harder for hackers to break in, which may cause them to move on to easier targets.
In this guide, we'll go through the PHP security steps that are most important. The words are kept simple and the code is kept short. Let's go.
Why PHP Sites Get Attacked So Often
PHP is used by a significant part of the web. It can be used in WordPress, Joomla, Drupal, Magento and Laravel applications. This makes PHP websites a common target for attackers.
Most attacks are not sophisticated. They are bots that are automatically programmed to search for the same things in thousands of sites: outdated software, weak passwords, and forms that assume anything that users type is true. Once those are corrected, most of the problems are eliminated.
The most common attacks on PHP Websites are:
- SQL Injection
- Cross-site scripting (XSS)
- CSRF
- Session hijacking
- Bad file uploads
- Brute force
Let's look at how to prevent these attacks.
1. Keep PHP and Everything Else Updated
This is the most crucial, even if it seems boring. Old PHP versions will no longer be updated for security. If there is one, then all new holes are left open.
- Determine the PHP version you are using. Upgrade to a PHP version that still receives security updates.
- Regularly update your CMS, plugins, themes and libraries.
- Uninstall plugins and tools that are not used. Every unused plugin or tool can create another security risk.
- Use composer audit to find out about known issues with your packages if you're using Composer.
Consider updates as you would think of locking your car. It only takes 2 seconds and a lot of pain.
2. Block XSS by Escaping Output
XSS occurs when your site displays user text on a page without first cleaning it. A hacker can put a small script in a comment box, and it will be executed in each visitor's browser.
The fix is simple: escape user-provided text before displaying it on a page.
| echo htmlspecialchars($comment, ENT_QUOTES, 'UTF-8'); |
A few extra tips:
- Don't escape on input; escape on output.
- If you are using a template engine such as Twig or Blade, enable auto-escaping.
- Include a Content Security Policy header (see below for more on headers). It specifies the scripts that the browser will allow to run.
3. Protect Forms With CSRF Tokens
CSRF attacks your own users. Suppose that a user logs in, clicks a link on another site, and the link makes a "change my email" request to your site without the user realizing it. Your site believes that the user did it.
This is prevented by a CSRF token. You assign a secret code to each form that only your site is aware of.
session_start();
| if (empty($_SESSION['csrf'])) { $_SESSION['csrf'] = bin2hex(random_bytes(32));}Put it in the form:<input type="hidden" name="csrf" value="<?= $_SESSION['csrf'] ?>">Review it upon return of the form:if (!hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) { http_response_code(403); exit('Invalid request');} |
Most frameworks will do this for you. If you do, switch it on and leave it on.
4. Store Passwords the Right Way
Don't store passwords in clear text. Don't use old hash functions such as MD5 or SHA1 for passwords. They're too quick to break.
PHP provides you with two easy functions that will get it done right.
When a user registers:
| $hash = password_hash($password, PASSWORD_DEFAULT); |
When a user logs in:
| if (password_verify($password, $hash)) { // Password is correct} |
These functions securely hash passwords and handle the salt for you. You can also use password_needs_rehash() to update password hashes when needed.
In addition, these are good habits to add:
- Encourage users to choose long and unique passwords.
- Reduce the rate of login attempts or lock out after multiple unsuccessful logins.
- Provide two factor authentication (2FA), particularly for admin areas.
5. Lock Down Your Sessions
A session is a way in which your site keeps track of who is logged in. If a hacker gets hold of it, he/she becomes that user.
Before starting the session, make sure to configure safe cookies:
| session_set_cookie_params([ 'lifetime' => 0, 'path' => '/', 'secure' => true, // only over HTTPS 'httponly' => true, // It cannot be read by JavaScript. 'samesite' => 'Lax',]); |
session_start();
Then immediately after a user logs in, generate a new session ID:
| session_regenerate_id(true); |
This helps protect against session fixation. Completely delete the session when a user logs out.
6. Validate Every Input
The basic guideline: don't trust anything that isn't coming from your server. This includes forms, URLs, cookies, headers and uploaded files.
Use PHP's filter functions to check data:
| $email = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);if ($email === false) { exit('Please enter a valid email.');}$age = filter_var($_POST['age'] ?? '', FILTER_VALIDATE_INT, [ 'options' => ['min_range' => 1, 'max_range' => 120],]); |
Consider using allow lists. Instead of trying to block every bad input, define what is allowed and reject everything else.
7. Handle File Uploads Carefully
Uploads are risky. A hacker can disguise a harmful PHP file as a picture and then run it on your server.
Safe upload rules:
Do not rely on the file name to determine the real file type on the server. Check the content of the file with finfo.
Only accept file types that are required (e.g. JPG and PNG).
Change the names of all the files to random names. Do not store the name that the user has provided.
If possible, save uploads outside of the public web folder.
Do not have PHP files in your uploads folder.
Set a size limit.
| $finfo = new finfo(FILEINFO_MIME_TYPE);$type = $finfo->file($_FILES['photo']['tmp_name']);$allowed = [ 'image/jpeg' => 'jpg', 'image/png' => 'png',];if (!isset($allowed[$type])) { exit('File type not allowed.');}$newName = bin2hex(random_bytes(16)) . '.' . $allowed[$type];if (!move_uploaded_file( $_FILES['photo']['tmp_name'], '/safe/folder/' . $newName)) { exit('Upload failed.');} |
8. Use HTTPS Everywhere
If you don't have HTTPS, then anything your visitors send can be read on the way. This includes passwords and card information.
- Install an SSL/TLS certificate and redirect everything to HTTPS.
- Enable HSTS to ensure that browsers always use the secure version.
- Renew certificates prior to expiration.
9. Hide Errors From Visitors
Error messages are a gold mine for hackers. They can display file paths, database names, and pieces of code. If it's a live site, display a friendly message and record the actual error in private.
In your php.ini file:
| display_errors = Offlog_errors = Onexpose_php = Off |
Then, review your logs regularly. An attack may be the first time that odd errors have been seen.
10. Give Each Part the Least Power Needed
The principle of ‘least privilege’ means giving each user or system only the access it needs.
- You should not be a full admin of your website's database user. Allow it to read and write only the tables it requires.
- Set permissions on files to be restrictive. Most files do not require the web server to be able to write to them.
This limits the damage if a hacker gets in.
Quick PHP Security Checklist
- PHP and all plugins are up to date
- All database queries are done via prepared statements.
- Any output has escaped.
- Forms have CSRF tokens
- Passwords use password_hash()
- Sessions are set with secure cookies.
- All input is checked for correctness.
- Uploads are safe, checked and renamed.
- HTTPS is everywhere!
- Security headers are set
- Errors are masked from visitors
- Access to the database and files is restricted.
- Backups and logs are implemented, and a WAF is in place.
If you can check all of the boxes, you're ahead of most websites.
FAQs
Can PHP really protect a website from every cyber attack?
There is no tool that can guarantee that. PHP provides you with powerful means to prevent the most popular attacks such as SQL injection, XSS and CSRF. However, layers of security – secure code, software updates, a safe server, monitoring, and backups – are the true ingredients of safety.
What is the most common PHP security mistake?
Trusting user input. Any site that enters raw form of data into a database query or onto a page opens the door to injection and XSS. Most of this is addressed by prepared statements, input checks and output escaping.
Is PHP less secure than other languages?
Not by itself. Most PHP issues are not language-related, but rather due to outdated plugins, old versions, and sloppy code. A PHP site can be as secure as any other site built.
Don't Wait for a Hack to Take Security Seriously. Let MSP Depot Guard Your Site 24/7.
Writing secure PHP is a great start. However, maintaining a website's security is a daily task: patches, monitoring, backups, alerts and quick fixes at 2 a.m. when something seems amiss. Most teams don't have the time and people do all that well.
That is where MSP Depot can help. We support growing businesses and IT providers with smart monitoring, remote management and hands-on support to keep them on top of security. We identify issues early, resolve them quickly, and ensure your team can focus on what they do best.
Call MSP Depot today and receive a complimentary security scan of your website. Let's close the doors hackers love to try.