SQL injections
1. What Is SQL Injection?
SQL Injection is a vulnerability that happens when user input is inserted into an SQL query without proper validation or parameterization.
If an attacker can control part of the query, they can:
-
Bypass login
-
Read sensitive data
-
Modify or delete data
-
In some cases, take over the server
2. Vulnerable Example (Classic Login Form)
❌ Vulnerable PHP Code (DO NOT USE)
Why Is This Dangerous?
Because user input is directly inserted into the SQL query.
If someone types:
The query becomes:
And since '1'='1' is always true, the login can be bypassed.
3. How SQL Injection Works (Step by Step)
-
The application builds SQL as a string.
-
User input is concatenated directly.
-
The database executes the final string.
-
Malicious input changes query logic.
The database cannot distinguish between code and data unless you use parameterized queries.
4. Common SQL Injection Techniques
4.1 Authentication Bypass
Input:
Example query:
-- comments out the rest of the query.
Result: attacker logs in without password.
4.2 Data Extraction
If a page shows user data by ID:
Attacker sends:
Query becomes:
All products are returned.
4.3 UNION-Based Injection
If results are displayed, attacker may try:
This merges results from another table into the response.
4.4 Error-Based SQLi
If database errors are displayed, attacker may use:
This may reveal:
-
Database type
-
Table names
-
SQL structure
Never show raw database errors in production.
5. Realistic Modern Example (Laravel)
You’re into Laravel, so here’s a dangerous example:
❌ Vulnerable
Even inside Laravel, raw queries are dangerous.
6. The Proper Defense
✅ 1. Use Prepared Statements (Parameterized Queries)
Safe PHP (MySQLi)
Here:
-
?are placeholders -
Input is sent separately
-
Database treats it strictly as data
Even if user enters:
It becomes a string value — not executable SQL.
✅ 2. PDO Example (Better Practice)
✅ 3. Laravel Eloquent (Safe by Default)
Eloquent automatically uses parameter binding.
7. Additional Protection Measures
✔ Validate Input
-
Use type casting:
✔ Limit Database Privileges
-
App user should NOT have:
-
DROP privileges
-
SUPER privileges
-
✔ Hide Database Errors
Disable error display in production.
✔ Use Web Application Firewall (WAF)
8. Why Escaping Is Not Enough
Old method:
This is better than nothing but:
-
Easy to misuse
-
Not reliable across encodings
-
Doesn’t protect against all cases
9. Blind SQL Injection (Concept Overview)
Sometimes application:
-
Does not show errors
-
Does not show query results
Attacker then uses logic-based queries:
Example:
If page behavior changes, attacker can extract data bit by bit.
This is slower but still dangerous.