PHP security basics – common vulnerabilities and how to protect against them.
Why it matters
PHP runs a large chunk of the web, which makes it a common target. Secure coding protects user data, keeps people trusting your site, and helps you stay on the right side of legal obligations.
Common threats
SQL injection
An attacker manipulates a SQL query through user input, potentially reading or changing your database.
Prevention:
- Use prepared statements with bound parameters.
- Do not build SQL queries by concatenating user input.
Example using PDO:
<?php
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();
?>
Cross-site scripting (XSS)
Untrusted data from a request gets included in HTML sent to the browser, allowing an attacker to run scripts in other users’ sessions.
Prevention:
- Escape user input with
htmlspecialchars(). - Set Content Security Policy (CSP) headers.
Example:
<?php
echo 'Hello, ' . Htmlspecialchars($_GET["name"]) . '!';
?>
Cross-site request forgery (CSRF)
Tricks a logged-in user into performing an action they did not intend – submitting a form, changing a password, that sort of thing.
Prevention:
- Use anti-CSRF tokens in forms.
- Validate the HTTP
Refererheader.
Example anti-CSRF token:
<?php
session_start();
if (empty($_SESSION['token'])) {
$_SESSION['token'] = bin2hex(random_bytes(32));
}
$token = $_SESSION['token'];
?>
<form method="post">
<input type="hidden" name="token" value="<?php echo $token; ?>">
<!-- form fields -->
</form>
Session hijacking
An attacker steals or forges a session cookie to impersonate a user.
Prevention:
- Use secure, HTTP-only cookies.
- Regenerate session IDs after login.
Example:
<?php
ini_set('session.cookie_httponly', 1);
session_start();
?>
Best practices
Keep PHP updated
Run a supported PHP version. Updates include security patches for known vulnerabilities.
Validate and sanitise user input
Do not trust user input. Check type, length, format, and range. Sanitise to strip harmful content.
Error handling
Show generic messages to users. Log the details server-side.
File uploads
If your app accepts uploads:
- Check file types and sizes.
- Rename files on upload.
- Store files outside the web directory.
Use HTTPS
Encrypts data between the server and the client.
Secure database connections
Keep credentials out of your codebase. Use environment variables or config files outside the webroot.
Regular security audits
Review your code periodically. Tools like PHP CodeSniffer can automate some of the checking.
Security is ongoing, not a one-off task. Know the common threats, apply the fixes, and keep checking.

