PHP Application Security: Top 10 Vulnerabilities for Beginners
\nPHP remains one of the most popular languages for web development, but its flexibility often leads to vulnerabilities if basic security rules are not followed. According to OWASP, most hacks occur due to 10 common mistakes made by beginner developers. In this article, we will analyze each vulnerability with real code examples and show how to protect your application.
\n\n1. SQL Injection
\nThe most common attack. An attacker injects malicious SQL code through user input.
\nVulnerable code:
\n<?php\n$id = $_GET['id'];\n$query = "SELECT * FROM users WHERE id = $id";\n$result = mysqli_query($conn, $query);\n?>\nProtection: Use prepared statements:
\n<?php\n$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");\n$stmt->bind_param("i", $_GET['id']);\n$stmt->execute();\n$result = $stmt->get_result();\n?>\n\n2. XSS (Cross-Site Scripting)
\nInjecting JavaScript code into a page through unvalidated data.
\nVulnerable code:
\n<?php\necho "Hello, " . $_GET['name'];\n?>\nProtection: Escape output using htmlspecialchars():
<?php\necho "Hello, " . htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');\n?>\n\n3. CSRF (Cross-Site Request Forgery)
\nAn attack where a user performs unwanted actions on their behalf.
\nVulnerable code:
\n<form action="/delete.php" method="POST">\n <input type="submit" value="Delete account">\n</form>\nProtection: Add a CSRF token:
\n<?php\nsession_start();\n$_SESSION['csrf_token'] = bin2hex(random_bytes(32));\n?>\n<form action="/delete.php" method="POST">\n <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">\n <input type="submit" value="Delete account">\n</form>\n\n4. Insecure Password Storage
\nStoring passwords in plain text or with outdated hashes (MD5, SHA1).
\nVulnerable code:
\n<?php\n$password = md5($_POST['password']);\n// or\n$password = sha1($_POST['password']);\n?>\nProtection: Use password_hash() and password_verify():
<?php\n$hash = password_hash($_POST['password'], PASSWORD_BCRYPT);\n// Verification:\nif (password_verify($input_password, $hash)) {\n echo "Password is correct";\n}\n?>\n\n5. Insecure File Handling (Local/Remote File Inclusion)
\nIncluding files via user input without validation.
\nVulnerable code:
\n<?php\ninclude($_GET['page'] . '.php');\n?>\nProtection: Use a whitelist of allowed files:
\n<?php\n$allowed_pages = ['home', 'about', 'contact'];\n$page = $_GET['page'] ?? 'home';\nif (in_array($page, $allowed_pages)) {\n include($page . '.php');\n} else {\n include('404.php');\n}\n?>\n\n6. Incorrect Session Configuration
\nUsing predictable session IDs or lacking regeneration.
\nVulnerable code:
\n<?php\nsession_start();\n$_SESSION['user_id'] = $user_id;\n// Session is not regenerated after login\n?>\nProtection:
\n<?php\nsession_start();\nsession_regenerate_id(true); // Regenerate ID after login\n$_SESSION['user_id'] = $user_id;\n?>\n\n7. Insufficient Input Validation
\nTrusting any data from the user.
\nVu