Security Basics
PHP applications that handle user input and data need to defend against a handful of well-known, common vulnerabilities from the very first line of code.
The Core Threats
Most real-world PHP vulnerabilities fall into a small number of well-understood categories, each with a standard, reliable defence.
- SQL Injection — prevented by always using prepared statements with bound parameters.
- Cross-Site Scripting (XSS) — prevented by escaping output with htmlspecialchars() before printing user data into HTML.
- Insecure passwords — prevented by hashing with password_hash(), never storing plain-text passwords.
- Cross-Site Request Forgery (CSRF) — mitigated with unique, per-session tokens in forms that change data.
Password Hashing
PHP's built-in password functions handle salting and hashing correctly out of the box, and should always be used instead of a custom or outdated hashing approach.
$hashedPassword = password_hash($plainPassword, PASSWORD_DEFAULT);
// Later, when checking a login attempt:
if (password_verify($enteredPassword, $hashedPassword)) {
echo "Login successful";
} else {
echo "Invalid credentials";
}
Common Mistakes
- Storing passwords in plain text or with a weak, outdated hashing algorithm like MD5.
- Trusting any data that comes from the browser — form fields, cookies, URLs — without validating and sanitising it server-side.
- Printing user-submitted content directly into HTML without escaping it with htmlspecialchars(), enabling XSS attacks.
- Disabling error display in a way that also silently hides security-relevant warnings during development.
Professional Tip
Treat every piece of data coming from the browser — form fields, URL parameters, cookies, uploaded files — as untrusted until validated. This single mindset shift prevents the overwhelming majority of real-world web application vulnerabilities.
Your Turn
Build a simple registration form that hashes the submitted password with password_hash() before storing it, and a login form that verifies it with password_verify().
Mini Quiz
What is the recommended way to store user passwords in a PHP application?
password_hash() uses a strong, salted, one-way hashing algorithm — passwords should never be stored in plain text, encrypted reversibly, or merely encoded (Base64 is not encryption).