29. OWASP Top 10 Web Vulnerabilities
29.2 A03 Injection: SQL Injection
SQL injection (SQLi) tevha hoto jevha user cha input thet SQL query madhe jato, ani attacker to query badalto. Chapter 21 madhe aapan sqlmap ne he baghitla; aata concept ani fix.
Vulnerable code (never do this):
// user input goes straight into the query
$id = $_GET['id'];
$sql = "SELECT * FROM users WHERE id = '$id'";
If the attacker sends id = 1' OR '1'='1, the query becomes ... WHERE id = '1' OR '1'='1' – which is always true and returns every row. Worse: 1'; DROP TABLE users;--.
The fix – prepared statements (parameterised queries):
// PDO: the input can never change the query structure
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_GET['id']]);
$rows = $stmt->fetchAll();
The database treats the input strictly as data, never as SQL. This is exactly the approach you used in the Chapter 16 reels app. Also apply least-privilege DB users (Chapter 11) so a compromised app cannot drop tables.
Ravindra Bagale's Tip
"Remove quotes from the input (escaping)" is an old, incomplete fix. Prepared statements are the only correct fix – they keep the query and the data separate. We did exactly this in Chapter 16. Never join user input directly into a query.
Ravindra Bagale's Tip – मराठी
"Input मधून quotes काढून टाका (escaping)" हा जुना, अपुरा उपाय आहे. Prepared statements हाच एकमेव बरोबर fix आहे – तो query आणि data वेगळे ठेवतो. Chapter 16 मध्ये आपण हेच केले. कधीही user input थेट query मध्ये जोडू नका.
Ravindra Bagale's Tip – हिंदी
"Input से quotes हटा दो (escaping)" पुराना, अधूरा उपाय है. Prepared statements ही एकमात्र सही fix है – यह query और data को अलग रखता है. Chapter 16 में हमने यही किया था. कभी भी user input को सीधे query में मत जोड़ो.
Lab
In DVWA (SQL Injection, security = low), use 1' OR '1'='1 to dump all users. Then set security to "high" and try again – it fails. Open your reels app code and confirm every query uses prepared statements; fix any that do not.