PHP Application Security: Top 10 Vulnerabilities for Beginners
PHP remains one of the most popular languages for web development, but its flexibility often leads to serious security mistakes. For a beginner, it's easy to miss a critical vulnerability that could lead to data leakage or complete server compromise. In this article, we will break down the 10 most common PHP application vulnerabilities, show examples of dangerous code, and teach you how to properly protect yourself. The material is prepared specifically for beginner developers who want to write secure code from day one.
1. SQL Injection
This is the most well-known and dangerous vulnerability. It occurs when user input is directly inserted into an SQL query without escaping. An attacker can gain access to the database, modify, or delete data.
Dangerous code:
<?php$id = $_GET['id'];$query = "SELECT * FROM users WHERE id = $id";$result = mysqli_query($conn, $query);?>How to protect: Use prepared statements with PDO or MySQLi.
<?php$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");$stmt->execute(['id' => $_GET['id']]);?>2. XSS (Cross-Site Scripting)
XSS allows an attacker to inject malicious JavaScript code into a page that is displayed to other users. This can lead to theft of session cookies or redirection to phishing sites.
Dangerous code:
<?phpecho "Hello, " . $_GET['name'];?>How to protect: Always escape output using htmlspecialchars().
<?phpecho "Hello, " . htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');?>3. CSRF (Cross-Site Request Forgery)
A CSRF attack forces an authenticated user to perform an unwanted action on the site (e.g., change a password or transfer money). The attack occurs when a user clicks a link on a third-party site.
How to protect: Use CSRF tokens for all forms and state-changing requests.
<?phpsession_start();if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32));}?><form method="POST"> <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>"> <button type="submit">Delete Account</button></form>4. Insecure File Handling
Allows an attacker to read or write arbitrary files on the server. For example, through path traversal or uploading PHP shells.
Dangerous code:
<?phpinclude($_GET['page'] . '.php');?>How to protect: Never use user input in file paths. Use a whitelist of allowed values.
<?php$allowed_pages = ['home', 'about', 'contact'];$page = $_GET['page'] ?? 'home';if (in_array($page, $allowed_pages)) { include($page . '.php');} else { include('404.php');}?>5. Authentication and Session Management Flaws
Weak passwords, lack of brute force protection, session fixation — all of these open the door to account takeover.
Recommendations:
- Store passwords only in hashed form using
password_hash(). - Use HTTPS for all pages with authentication.
- Regenerate the session ID after login:
session_regenerate_id(true). - Set a short session lifetime.
6. Insecure Direct Object Reference (IDOR)
ID