Security is a core requirement of modern web applications. An insecure website risks data exposure, search engine blacklisting, and loss of user trust. Web developers must implement secure coding practices to protect their applications from attacks.
1. Defeating SQL Injection (SQLi)
SQL Injection occurs when untrusted user inputs are concatenated directly into SQL query strings, allowing attackers to execute unauthorized commands. The rule to prevent SQL injection is simple: Never concatenate user input directly into queries. Use prepared statements.
// INSECURE (Concatenating Input)
$email = $_POST['email'];
$query = "SELECT * FROM users WHERE email = '$email'"; // Vulnerable to SQLi!
// SECURE (Using PDO Prepared Statements)
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();
Prepared statements separate the query structure from the user data, preventing the database from executing malicious input as code.
2. Preventing Cross-Site Scripting (XSS)
Cross-Site Scripting occurs when malicious client-side script code is injected into a website and executed in a user's browser. This is common when displaying user inputs without escaping them first.
To prevent XSS, apply context-aware escaping to all data before rendering it in the browser. In PHP, use functions like htmlspecialchars() or framework helpers like CodeIgniter's esc() function.
// INSECURE
echo $user_profile_comment; // Vulnerable to HTML/JS injection
// SECURE
echo htmlspecialchars($user_profile_comment, ENT_QUOTES, 'UTF-8');
// SECURE (Within MVC Framework views)
<span><?= esc($user_profile_comment) ?></span>
3. Mitigating Cross-Site Request Forgery (CSRF)
CSRF attacks trick authenticated users into executing unwanted actions on a trusted web application. For example, an attacker could host a hidden form that sends a post request to change a logged-in user's email address on your site.
To prevent CSRF, use cryptographically secure **CSRF tokens** for all post and put requests. The server generates a unique token for the user session, embeds it in forms, and validates it upon form submission.
<!-- CSRF Form Integration -->
<form action="/profile/update" method="POST">
<!-- Generate a hidden CSRF token input field -->
<input type="hidden" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>">
<input type="email" name="email" value="user@example.com">
<button type="submit">Update Email</button>
</form>
4. Secure Password Hashing with Argon2id
Storing passwords in plain text is a critical security vulnerability. Even MD5 or SHA1 algorithms are insecure due to modern GPU cracking speeds. PHP provides built-in functions for secure, modern password hashing.
Always use the native password_hash() function with strong algorithms like PASSWORD_ARGON2ID or PASSWORD_BCRYPT.
// Hash a user password before storing in a database
$password = $_POST['password'];
$hashedPassword = password_hash($password, PASSWORD_ARGON2ID, [
'memory_cost' => 65536,
'time_cost' => 4,
'threads' => 2
]);
// Verify the password during login
if (password_verify($password, $hashedPassword)) {
// Password is correct
}
5. Content Security Policy (CSP) Headers
Content Security Policy is an HTTP response header that declares approved resource domains that the browser is allowed to load. Setting a strong CSP helps mitigate XSS and data injection attacks.
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://pagead2.googlesyndication.com; style-src 'self' https://cdn.jsdelivr.net https://fonts.googleapis.com; img-src 'self' data: https://pagead2.googlesyndication.com;
Summary
Securing your code protects user data and ensures your site remains operational and trusted. Integrating prepared statements, input escaping, CSRF protection, and secure hashing protects your site from common threats, providing a secure platform for AdSense monetization.