How to Secure Your PHP Website: A Practical Guide for Developers
This practical guide shows PHP developers how to secure their websites, from prepared statements and output escaping to php.ini hardening, safe uploads and secure sessions, mapped to the OWASP Top 10:2025.
PHP powers a large share of the world's websites. WordPress, Laravel, Drupal, Magento and many custom-built business websites all run on PHP. That popularity is also why PHP websites are attacked so often: attackers use automated tools that scan the internet around the clock, looking for the same common weaknesses on many websites at once.
The PHP2Shell vulnerability of October 2026 was a reminder that even PHP itself can have critical flaws. But updating PHP is only one part of the job. Many successful attacks start with everyday mistakes in code, configuration and maintenance, and those are in the hands of developers.
This guide walks through the security practices every PHP developer should follow, mapped to the OWASP Top 10:2025, with short examples you can apply today. Website owners will also find a quick checklist and a list of questions to ask their developer.
How to use this guide: the examples assume a supported PHP version (8.2 or newer) and are kept short and procedural so that the idea is easy to see. The same principles apply to object-oriented code and to frameworks such as Laravel and Symfony. Security works in layers: no single step makes a website safe on its own, but together they make attacks much harder.
Why PHP Websites Are a Frequent Target
Automated bots do not care who you are. They look for easy openings, such as:
- Outdated PHP versions, CMS cores, plugins and themes with known vulnerabilities
- Exposed files such as .env, .git folders, database dumps, backup archives and phpinfo pages
- Login pages without rate limiting, and weak or reused passwords
- File upload forms that accept any file
- Debug mode and detailed error messages left on in production
- Old applications still running on end-of-life versions such as PHP 5 or PHP 7
Shared hosting adds another risk. When many websites share one server and isolation is weak, one compromised website can put its neighbours at risk.
The OWASP Top 10:2025 at a Glance
The OWASP Top 10 is a widely used awareness list of the most critical web application security risks. Its latest edition, the OWASP Top 10:2025, looks like this in PHP terms:
- A01 Broken Access Control: users reaching data or actions they should not, including server-side request forgery (SSRF)
- A02 Security Misconfiguration: debug mode on, default settings and exposed files
- A03 Software Supply Chain Failures: vulnerable or malicious Composer packages, plugins and themes
- A04 Cryptographic Failures: weak password storage, missing HTTPS and home-made encryption
- A05 Injection: SQL injection, command injection, code injection and cross-site scripting (XSS)
- A06 Insecure Design: missing rate limits and unsafe business logic
- A07 Authentication Failures: weak login, password reset and session handling
- A08 Software or Data Integrity Failures: unsafe deserialisation and unverified updates or scripts
- A09 Security Logging and Alerting Failures: no useful logs and no alerts
- A10 Mishandling of Exceptional Conditions: unsafe error handling and failing open
Most steps below note the OWASP categories they help with.
1. Use a Supported PHP Version and Patch Quickly
OWASP: A02, A03
As of October 2026, PHP 8.2, 8.3, 8.4 and 8.5 are the supported versions. PHP 8.2 reaches end of life on 2026-12-31, so choose PHP 8.3 or newer for new projects and upgrades. PHP 8.1 and older no longer receive security fixes.
This matters in real life. When PHP2Shell was fixed in October 2026, fixes were released only for PHP 8.2, 8.3, 8.4 and 8.5. Websites on older versions got no fix at all.
- Follow PHP's security announcements and apply security releases within days, not months.
- If PHP comes from your Linux distribution, install the distribution's security updates. The version number may look older, because distributions often add fixes to their own packages.
- Restart PHP-FPM or your web server after every update, so that the new version is actually loaded.
- Check the version your website really runs, not just the command line version. The two can be different.
- Keep the operating system, web server and database server updated as well.
2. Harden Your php.ini for Production
OWASP: A02, A10
Start from the php.ini-production file that ships with PHP, then review these settings:
; Hide the PHP version from HTTP headers
expose_php = Off
; Never show errors to visitors in production, log them instead
display_errors = Off
display_startup_errors = Off
log_errors = On
error_log = /var/log/php/error.log
; Keep function arguments, which may contain passwords, out of stack traces
zend.exception_ignore_args = On
; Block remote file inclusion
allow_url_include = Off
; Turn off if your code does not open remote URLs with file functions
allow_url_fopen = Off
; Safer sessions
session.use_strict_mode = 1
session.use_only_cookies = 1
session.cookie_httponly = 1
session.cookie_secure = 1
session.cookie_samesite = Lax
; Sensible limits: adjust to what your application really needs
max_execution_time = 30
memory_limit = 256M
post_max_size = 8M
upload_max_filesize = 5M
; Turn off file uploads completely if your website does not need them
; file_uploads = Off
Two more settings can add an extra layer, but test them carefully because they can break applications and plugins:
; Block shell commands if your code never needs them
disable_functions = exec,passthru,shell_exec,system,proc_open,popen
; Limit the folders PHP can read and write
open_basedir = /var/www/example.com/:/tmp/
Treat disable_functions and open_basedir as helpful extra layers, not as your main defence. After any change, restart PHP-FPM (or Apache when using mod_php) and confirm the values as the web server sees them, for example with a temporary check page that you delete immediately afterwards. The command line can use a different php.ini file.
3. Validate Every Input on the Server
OWASP: A05, A06
Treat everything that comes from outside your code as untrusted: $_GET, $_POST, $_COOKIE, $_FILES, request headers, JSON bodies and even data from third-party APIs. Browser-side validation is only for user convenience, because attackers can skip it easily.
Use allowlists: define exactly what is allowed and reject everything else.
declare(strict_types=1);
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($id === false || $id === null) {
http_response_code(400);
exit('Invalid request');
}
$email = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);
if ($email === false) {
exit('Please enter a valid e-mail address');
}
$sort = $_GET['sort'] ?? 'name';
if (!in_array($sort, ['name', 'price', 'created_at'], true)) {
$sort = 'name';
}
A few more rules:
- Check type, length, format and range, for example a quantity between 1 and 10.
- Reject bad input instead of trying to repair it.
- Do not build links such as password reset URLs from $_SERVER['HTTP_HOST'], because visitors can change that header. Use a fixed base URL from your configuration.
- Remember that validation and escaping are different jobs: validate input when it arrives, and escape output when you use it.
4. Stop SQL Injection Using Prepared Statements
OWASP: A05
SQL injection happens when user input is joined directly into a query, so the database treats part of the input as SQL. Escaping functions such as addslashes() are not a reliable fix. Prepared statements are, because the query and the data travel separately.
With mysqli in PHP 8.2 or newer, a single function does the job:
$result = mysqli_execute_query(
$conn,
'SELECT id, name FROM users WHERE email = ?',
[$email]
);
$user = mysqli_fetch_assoc($result);
In older code, the classic version looks like this:
$stmt = mysqli_prepare($conn, 'SELECT id, name FROM users WHERE email = ?');
mysqli_stmt_bind_param($stmt, 's', $email);
mysqli_stmt_execute($stmt);
$user = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
If you use PDO, the idea is the same: call prepare() with placeholders, pass the values to execute(), switch the error mode to exceptions and set the utf8mb4 charset in the connection string.
Also keep in mind:
- Placeholders cannot be used for table names, column names or the sort direction. Use an allowlist for these, as in the sort example above.
- ORMs such as Eloquent and Doctrine bind parameters for you, but raw query methods (for example whereRaw() or DB::raw() in Laravel) can bring injection back if you join user input into them.
- Set the connection character set with mysqli_set_charset($conn, 'utf8mb4').
- Connect with a database user that has only the permissions the application needs (see step 17).
5. Escape Output to Prevent Cross-Site Scripting (XSS)
OWASP: A05
Cross-site scripting (XSS) happens when user-controlled data is placed into a page without escaping. The attacker's script then runs in other visitors' browsers, where it can steal sessions or change what users see.
Escape data at the moment you output it, using a small helper:
function e(?string $value): string
{
return htmlspecialchars($value ?? '', ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
echo e($comment);
The right escaping depends on where the data goes:
- HTML text and attributes: use e() and always put attribute values in quotes.
- Inside JavaScript: pass data with json_encode() and the JSON_HEX flags shown below.
- URLs: encode parameters with rawurlencode(), and accept user-supplied links only if they start with http:// or https://, which blocks javascript: links.
- User-written HTML (rich text): clean it with an allowlist-based library such as HTML Purifier. strip_tags() on its own is not a security control.
- Templates: Twig and Laravel Blade escape output by default. Avoid raw output ({!! !!} in Blade or the raw filter in Twig) unless the data is already sanitised.
For JavaScript, encode data like this:
$json = json_encode($settings, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
A Content Security Policy (step 18) adds a second layer of protection if an escaping mistake slips through.
6. Add CSRF Tokens to Every Form
OWASP: A01
Cross-site request forgery (CSRF) tricks a logged-in user's browser into sending a request they did not intend, such as changing their e-mail address or password. Every request that changes data needs a secret token, and data should never change on a GET request.
session_start();
// When showing the form: create one token per session
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
// When the form is submitted: compare in constant time
$sent = $_POST['csrf_token'] ?? '';
if (!is_string($sent) || !hash_equals($_SESSION['csrf_token'] ?? '', $sent)) {
http_response_code(403);
exit('Invalid request. Please reload the page and try again.');
}
Add the token to every form as a hidden field named csrf_token (escaped with e()), and send it in a custom header such as X-CSRF-Token for AJAX requests. SameSite cookies help, but they are not a full replacement for tokens. If you use a framework, keep its built-in CSRF protection switched on.
7. Hash Passwords Using password_hash()
OWASP: A04, A07
Never store passwords in plain text, and never use md5(), sha1(), plain SHA-256 or base64 for passwords. Do not encrypt them either: passwords must be hashed, not stored in a form that can be reversed. PHP's built-in functions do this properly, with a random salt and a deliberately slow algorithm.
// When the user registers or changes the password
$hash = password_hash($password, PASSWORD_DEFAULT);
// When the user logs in
if (password_verify($password, $hash)) {
if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
$newHash = password_hash($password, PASSWORD_DEFAULT);
// Save $newHash in the database
}
// Continue with the login
}
- Store hashes in a VARCHAR(255) column so that future algorithms fit.
- PASSWORD_ARGON2ID is a strong option if your PHP build supports it.
- Allow long passphrases, and consider checking new passwords against lists of known breached passwords.
8. Build Secure Login and Session Handling
OWASP: A07
Attackers who want to take over accounts focus on three places: the login page, the password reset flow and the session.
session_start();
// Right after password_verify() succeeds
session_regenerate_id(true);
$_SESSION['user_id'] = $userId;
$_SESSION['login_time'] = time();
Regenerating the session ID after login stops session fixation attacks. Also:
- Limit login attempts per account and per IP address, with growing delays or temporary lockouts.
- Use one generic message such as Invalid e-mail or password, so attackers cannot find out which accounts exist. Do the same on the password reset page.
- Turn on multi-factor authentication (MFA), at least for admin accounts.
- Make reset tokens safe: generate them with random_bytes(), store only a hash of the token, make them single-use and expire them quickly, for example within 30 minutes.
- Set session timeouts for idle sessions and a maximum session lifetime.
Log out properly by clearing the session data, destroying the session and expiring the session cookie:
session_start();
$_SESSION = [];
session_destroy();
9. Enforce Access Control on Every Request
OWASP: A01
Broken access control sits at the top of the OWASP Top 10:2025. Common PHP mistakes include hiding the admin menu but not checking permissions inside admin scripts, and trusting an ID from the URL without checking who owns the record. This second mistake is called an insecure direct object reference (IDOR).
The rules are simple: deny by default, check permissions on the server for every request and every action, and keep the checks in one central place.
function require_role(string $role): void
{
if (($_SESSION['role'] ?? '') !== $role) {
http_response_code(403);
exit('Access denied');
}
}
require_role('admin');
To prevent IDOR, always include the owner in the query:
$result = mysqli_execute_query(
$conn,
'SELECT id, amount, status FROM invoices WHERE id = ? AND user_id = ?',
[$invoiceId, $_SESSION['user_id']]
);
$invoice = mysqli_fetch_assoc($result);
if ($invoice === null) {
http_response_code(404);
exit('Invoice not found');
}
Also avoid mass assignment: never pass the whole $_POST array into an insert or update, and pick only the fields a user is allowed to change. Never trust roles, prices or user IDs sent from the browser in hidden fields or cookies.
10. Handle File Uploads Safely
Upload forms are a favourite target. If an attacker manages to upload a PHP file (often called a web shell) into a folder where the server runs PHP, they can take control of the website.
$file = $_FILES['photo'] ?? null;
if ($file === null || $file['error'] !== UPLOAD_ERR_OK) {
exit('Upload failed');
}
$allowed = ['image/jpeg', 'image/png', 'image/webp'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
if (!in_array($mime, $allowed, true)) {
exit('Only JPG, PNG or WebP images are allowed');
}
$extension = explode('/', $mime)[1];
$newName = bin2hex(random_bytes(16)) . '.' . $extension;
$target = '/var/www/example.com/storage/uploads/' . $newName;
if (!move_uploaded_file($file['tmp_name'], $target)) {
exit('Could not save the file');
}
Key rules for uploads:
- Check the real file content with finfo, never only the extension or the type sent by the browser.
- Give every file a new random name, and never use the original file name in a path.
- Store uploads outside the public web folder, as in the example above.
- Limit file size with upload_max_filesize and post_max_size.
- Re-save images with GD or Imagick to remove hidden content, and scan documents with an antivirus such as ClamAV.
- Serve files through a script that sends the correct Content-Type and checks that the user may download them.
If uploads must stay inside the public folder, make sure the server never runs PHP there. For Nginx, place this block before your main PHP location block, because Nginx uses the first regular expression that matches:
location ~* ^/uploads/.*[.](php[0-9]?|phtml|phar)$ {
deny all;
}
For Apache, place this in a .htaccess file inside the uploads folder. It needs mod_rewrite and AllowOverride to be enabled:
RewriteEngine On
RewriteRule [.](php[0-9]?|phtml|phar)$ - [F,NC]
11. Never Pass User Input to Dangerous Functions
OWASP: A05, A08
Some PHP functions are risky whenever user input reaches them:
- eval(): avoid it completely.
- include and require: never build file paths from user input. Use an allowlist instead, as shown below.
- exec(), system(), shell_exec(), passthru() and backticks: prefer native PHP functions. If you must run a command, escape every argument with escapeshellarg() and allow only known values.
- unserialize(): never use it on data from users or cookies, because it can create objects an attacker controls. Use json_decode() instead. If you cannot avoid unserialize(), set its allowed_classes option to false.
- extract(): never use it on $_GET or $_POST, because it can overwrite your variables.
- mail(): avoid putting user input into headers. Use a maintained library such as PHPMailer or Symfony Mailer.
A safe way to load pages:
$pages = ['home', 'about', 'contact'];
$page = $_GET['page'] ?? 'home';
if (!in_array($page, $pages, true)) {
$page = 'home';
}
require __DIR__ . '/pages/' . $page . '.php';
The same idea stops open redirects, where a link on your website sends visitors to a malicious site:
$allowedNext = ['/account', '/orders', '/settings'];
$next = $_GET['next'] ?? '/account';
if (!in_array($next, $allowedNext, true)) {
$next = '/account';
}
header('Location: ' . $next);
exit;
12. Use Strict Comparisons and Secure Randomness
OWASP: A04, A07
PHP's loose comparison (==) converts types before comparing, which has caused login and token checks to pass when they should fail. PHP 8 made these comparisons safer, but strict comparison is still the right habit:
- Use === and !==, and pass true as the third argument to in_array().
- Add declare(strict_types=1); at the top of your files.
- Compare secrets such as tokens and signatures with hash_equals(), which takes the same time whatever the input.
For anything security-related, such as tokens, one-time codes and reset links, use PHP's secure random functions. Never use rand(), mt_rand(), uniqid() or time-based values.
$token = bin2hex(random_bytes(32)); // 64-character token
$otp = random_int(100000, 999999); // 6-digit one-time code
For encryption, use the Sodium extension that comes with PHP (for example sodium_crypto_secretbox()) or a well-reviewed library. Never invent your own encryption, and keep keys out of your code.
13. Prevent Path Traversal, SSRF and XXE
OWASP: A01, A02
Path traversal lets an attacker read files outside the intended folder by using file names that contain ../ to climb up the folder tree. Resolve the real path and make sure it stays inside the allowed folder:
$base = realpath(__DIR__ . '/downloads');
$requested = basename($_GET['file'] ?? '');
$path = realpath($base . '/' . $requested);
if ($path === false || !str_starts_with($path, $base . DIRECTORY_SEPARATOR)) {
http_response_code(404);
exit('File not found');
}
// Also check that this user is allowed to download this file
readfile($path);
Server-side request forgery (SSRF) happens when your application fetches a URL supplied by a user, for example for webhooks, link previews or image imports, and an attacker points it at internal systems or cloud metadata addresses. Allow only https, prefer an allowlist of trusted domains, block private and reserved IP addresses, use short timeouts and do not follow redirects blindly.
$host = parse_url($url, PHP_URL_HOST);
if (!is_string($host)) {
exit('Invalid URL');
}
$ip = gethostbyname($host);
$isPublic = filter_var(
$ip,
FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
);
if ($isPublic === false) {
exit('This address is not allowed');
}
A check like this is only a minimum, and an allowlist of trusted domains is stronger.
XML external entities (XXE) can leak files when untrusted XML is parsed with unsafe options. Modern PHP does not load external entities by default, so never enable LIBXML_NOENT or LIBXML_DTDLOAD for XML that comes from users, and prefer JSON where you can.
14. Handle Errors and Exceptions Safely
OWASP: A09, A10
The OWASP Top 10:2025 added a new category for this: Mishandling of Exceptional Conditions. It covers applications that crash in unsafe ways, leak details in error messages or fail open, which means they allow an action when something goes wrong. PHP2Shell was also, at its heart, a problem in how errors were handled, in that case inside PHP itself.
set_exception_handler(function (Throwable $e): void {
error_log((string) $e);
http_response_code(500);
echo 'Something went wrong. Please try again later.';
});
Good habits:
- Show users a short, generic message, and keep the details in your private logs.
- Fail closed: if a permission check or payment verification throws an error, deny the action.
- Check return values, and let json_decode() throw an exception on bad input by passing JSON_THROW_ON_ERROR.
- Use database transactions, so that a failure halfway does not leave half-saved data.
For example, failing closed looks like this:
try {
$paid = verify_payment($orderId);
} catch (Throwable $e) {
error_log((string) $e);
$paid = false; // Fail closed: deny when unsure
}
15. Secure Your Dependencies, Plugins and Themes
OWASP: A03, A08
Software Supply Chain Failures is now third in the OWASP Top 10:2025. In PHP projects, that means Composer packages, WordPress plugins and themes, and JavaScript libraries.
# Check installed packages for known vulnerabilities
composer audit
# See which direct dependencies are outdated
composer outdated --direct
# Production install without development packages
composer install --no-dev --optimize-autoloader
- Commit composer.lock so that every server installs exactly the versions you tested.
- Run composer audit regularly and in your CI pipeline, and use automated update tools such as Dependabot or Renovate.
- Before adding a package, check that it is actively maintained and that its name is exactly right, since look-alike names are a known trick.
- Remove packages, plugins and themes you no longer use. Deactivated plugin files can still be reachable on the server.
- Never install nulled (pirated) premium themes or plugins. They often contain hidden backdoors.
- Load scripts from public CDNs with Subresource Integrity (SRI) hashes, or host them yourself.
16. Protect Secrets and Configuration Files
OWASP: A02, A07
- Never hard-code database passwords, API keys or SMTP credentials in your code. Read them from environment variables or from a .env file stored outside the public folder.
- Never commit .env files to Git. Add them to .gitignore and use a secret scanner such as gitleaks.
- If a secret leaks, rotate it immediately. Deleting the commit is not enough.
- Make the public folder (for example public/) your document root, and keep application code, configuration, vendor/, storage and logs outside it.
- Delete phpinfo() pages, test scripts, database dumps and backup archives (.zip, .sql, .bak) from the server.
- Use different keys and passwords for development, staging and production.
Reading a secret from the environment is simple:
$dbPassword = getenv('DB_PASSWORD');
Block hidden files such as .env and .git at the web server too. For Nginx:
location ~ /[.](?!well-known) {
deny all;
}
The well-known exception keeps paths such as /.well-known/security.txt and certificate renewal checks working.
17. Harden the Web Server and Database
OWASP: A02
Web Server
- Turn off directory listing with Options -Indexes in Apache. Nginx keeps autoindex off by default.
- Hide version details with ServerTokens Prod and ServerSignature Off in Apache, or server_tokens off; in Nginx, together with expose_php = Off.
- In each PHP-FPM pool, set security.limit_extensions = .php so that only .php files can run.
- Run each website in its own PHP-FPM pool with its own system user, so that one compromised site cannot read another.
- Restrict admin areas by IP address or VPN where possible, and protect them with MFA.
- Put a web application firewall (WAF) and rate limiting in front of the website.
File Permissions
Files should usually be 644 and folders 755, owned by a deploy user rather than the PHP process user. Only folders that PHP must write to, such as uploads, cache and logs, should be writable by PHP. Never use 777.
find /var/www/example.com -type d -exec chmod 755 {} +
find /var/www/example.com -type f -exec chmod 644 {} +
Database
- Create a separate database user for each application, with only the permissions it needs, and never connect as root.
- Keep the database listening only on localhost or a private network, never on the public internet.
- Use long, unique passwords and encrypt your backups.
After creating the application's database user, grant only what it needs:
GRANT SELECT, INSERT, UPDATE, DELETE ON shop.* TO 'shop_app'@'localhost';
Server Access
- Use SSH keys, disable password logins and direct root login, and open only the ports you need.
- Use a tool such as fail2ban to block repeated login attempts, and turn on automatic security updates.
18. Add HTTPS and Security Headers
OWASP: A02, A04
Serve every page over HTTPS, redirect all HTTP traffic to HTTPS and use TLS 1.2 or newer. Free certificates are available from Let's Encrypt.
Then add security headers, either in your web server or in PHP:
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
header("Content-Security-Policy: default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'");
- HSTS tells browsers to always use HTTPS. Turn it on only after HTTPS works everywhere, including all subdomains if you use includeSubDomains.
- Content Security Policy (CSP) limits where scripts can load from. Start with the Content-Security-Policy-Report-Only header, fix what breaks, then enforce it. Avoid 'unsafe-inline' where you can.
- X-Content-Type-Options stops browsers from guessing file types, and X-Frame-Options together with frame-ancestors helps prevent clickjacking.
19. Log, Monitor and Back Up
OWASP: A09
You cannot respond to an attack you cannot see. Log security events such as:
- Successful and failed logins, password resets and MFA changes
- Permission denials and admin actions
- File uploads and payment failures
error_log(sprintf(
'[security] failed_login account=%s ip=%s',
$accountId,
$_SERVER['REMOTE_ADDR'] ?? 'unknown'
));
- Never log passwords, OTPs, session IDs, tokens or full card numbers.
- Keep logs outside the public folder, limit who can read them and send them to a central system with alerts, for example for many failed logins or a new admin account.
- Use file integrity monitoring to spot changed core files.
For backups, follow the 3-2-1 rule: three copies of your data, on two different types of storage, with one copy offsite. Keep at least one copy offline or unchangeable so that ransomware cannot delete it, encrypt your backups and test a restore regularly.
20. Test Your Security Regularly
- Code review: review every change with a short security checklist, such as the one at the end of this guide.
- Static analysis: tools such as PHPStan, Psalm (with taint analysis) and Semgrep catch many problems before release.
- Dependency checks: run composer audit in your CI pipeline.
- Dynamic testing: scan your staging website with a tool such as ZAP.
- VAPT: get a vulnerability assessment and penetration test by qualified testers before launch, after major changes and at regular intervals.
- Responsible disclosure: publish a security.txt file at /.well-known/security.txt so that researchers know how to report problems to you.
- Incident plan: decide in advance who does what if something goes wrong, including how to isolate the website and whom to inform.
Framework and CMS Notes
Laravel
- Keep APP_DEBUG=false and APP_ENV=production on live servers. Debug pages can expose secrets.
- Use the validator, Eloquent and the query builder with bindings. Take extra care with whereRaw(), DB::raw() and {!! !!} output.
- Keep CSRF protection on, and protect models against mass assignment with $fillable.
Symfony
- Run with APP_ENV=prod and APP_DEBUG=0, and never expose the web profiler in production.
- Use the Security component, CSRF-protected forms and Twig's automatic escaping.
WordPress
- Update core, plugins and themes promptly, and remove anything unused.
- Give admin rights to as few people as possible and turn on MFA for them.
- Use WordPress's own escaping functions (esc_html, esc_attr and esc_url), nonces (wp_nonce_field and check_admin_referer) and the prepare() method of $wpdb for queries.
- Turn off the built-in theme and plugin file editor in wp-config.php, as shown below.
define('DISALLOW_FILE_EDIT', true);
Indian Compliance Points Every Developer Should Know
If your website serves users in India or handles their data, two sets of rules matter:
- CERT-In directions (2022-04-28): service providers, intermediaries, data centres, body corporates and government organisations must report specified cyber incidents to CERT-In within 6 hours of noticing them. They must also enable logs of all their ICT systems and keep them securely for a rolling period of 180 days.
- DPDP Act, 2023 and DPDP Rules, 2025: organisations that handle personal data must take reasonable security safeguards, such as encryption or masking, access control, logging and monitoring, and backups. These obligations, along with personal data breach reporting, come into force in May 2027, 18 months after the Rules were notified in November 2025.
Most steps in this guide directly support these requirements, so building them in now makes compliance easier later. This is general information, not legal advice, so please check the details with your legal or compliance team.
PHP Security Checklist
Use this as a quick reference before every release:
- PHP is on a supported version (8.3 or newer recommended) and security updates are applied quickly
- display_errors is off, errors are logged and debug mode is off in production
- php.ini is hardened (expose_php, allow_url_include and session cookie flags)
- Every input is validated on the server with allowlists
- Every SQL query uses prepared statements
- Every output is escaped for its context
- Every form that changes data has a CSRF token
- Passwords are stored with password_hash()
- Session IDs are regenerated after login, and login attempts are rate-limited
- Admin accounts use MFA
- Permissions and record ownership are checked on every request
- Uploads are type-checked, renamed and stored where PHP cannot run them
- No user input reaches eval(), include, shell commands or unserialize()
- Tokens use random_bytes() or random_int(), and secrets are compared with hash_equals()
- Errors fail closed and show only generic messages
- composer audit runs regularly, and unused packages, plugins and themes are removed
- Secrets live outside the code and outside the public folder
- .env, .git and backup files are not reachable from the web
- HTTPS, HSTS and security headers are in place
- Security events are logged and alerts are set up
- Backups follow the 3-2-1 rule and restores are tested
- A VAPT has been done recently and its findings are fixed
Questions Website Owners Should Ask Their Developer
If you own a PHP website but do not write code, these questions will tell you a lot:
- Which PHP version does our website run, and is it still supported?
- How quickly are PHP, CMS, plugin and Composer updates applied?
- Are passwords stored using password_hash()?
- Do all database queries use prepared statements, and do all forms have CSRF protection?
- Is debug mode switched off, and are error details hidden from visitors?
- Do admin accounts use multi-factor authentication?
- Where are our backups kept, and when did we last test a restore?
- When was our last security test (VAPT), and were all findings fixed?
Frequently Asked Questions
Is PHP Secure Enough for Business Websites?
Yes. PHP is a mature language used by major platforms such as WordPress. How secure a PHP website is depends on its PHP version, its code, its configuration and how well it is maintained.
Is PDO or mysqli More Secure?
Both are secure when you use prepared statements. PDO works with many databases and has a consistent interface, while mysqli is specific to MySQL and MariaDB. Pick one and use prepared statements everywhere.
Does Using Laravel or Symfony Make My Website Secure Automatically?
No. Frameworks give you strong defaults, such as CSRF protection, output escaping and parameter binding. But debug settings, raw queries, raw output, access control logic and outdated packages are still your responsibility.
How Often Should I Update PHP and Composer Packages?
Apply security releases as soon as possible, ideally within days for critical issues. Review other updates at least once a month, and plan each PHP upgrade well before your version reaches end of life.
Do I Still Need a VAPT if I Follow This Checklist?
Yes. A checklist removes common weaknesses, but a qualified tester can find logic flaws, chained issues and configuration gaps that are easy to miss from the inside.
Which Fixes Should I Do First?
Start with the steps that block very common attacks: update PHP and your dependencies, switch off debug mode and error display, use prepared statements and output escaping, store passwords with password_hash(), turn on MFA for admins and make sure your backups work.
Final Word
PHP websites are not unsafe by nature. Problems often come from outdated software, risky settings and small coding mistakes that add up over time. The good news is that each of these can be fixed with clear, repeatable habits.
At TrojanByte Labs, our advice is to treat security as part of everyday development, not a task for the end of a project. Start with the checklist above, fix the gaps one by one and test your website regularly. If you are unsure where your website stands, a qualified security professional can review it through a VAPT.
Written By
Vicky Choudhary
TrojanByte Labs tests, investigates and trains from Jaipur. We write about what we see in our work, in plain English.
Need This Looked at Properly?
Our team tests, investigates and trains. Tell us what you are dealing with.