Understanding SQL Injection Vulnerabilities in PHP and How to Prevent Them

This article explains the causes, impacts, and various techniques of SQL injection attacks in PHP applications, demonstrates vulnerable code examples, and provides practical mitigation measures such as input validation, error handling, character encoding considerations, and secure coding practices.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Understanding SQL Injection Vulnerabilities in PHP and How to Prevent Them

This article introduces the various SQL injection vulnerabilities caused by insecure PHP coding, explains why they are among the most severe web security issues, and illustrates their potential damage, including data leakage, website defacement, remote code execution, and complete system compromise.

1. What is SQL Injection

SQL injection occurs when an attacker manipulates client‑side input to inject malicious SQL commands into the server, often by concatenating user‑controlled strings directly into queries without proper validation.

Typical vulnerable PHP code:

<?php
$username=$_GET['username'];
$conn=mysql_connect("localhost","root","root") or die("数据库连接失败");
mysql_select_db('hacker',$conn);
$sql="select * from hacker where name='{$username}'";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)) {
    echo "username:".$row['name']."<br>";
    echo "email:".$row['email']."<br>";
}
mysql_close($conn);
?>

2. Error‑Based Injection

Attackers force the database to produce error messages that reveal internal details. Example query: select * from hacker where name = '{$username}' If username is hacker'attack, the resulting SQL becomes malformed, causing an error that leaks MySQL version information. Disabling display_errors in production mitigates this.

3. Classic (Union) Injection

By appending logical conditions or UNION statements, attackers can retrieve arbitrary data. Example request:

http://localhost:8080/mysql.php?name=name' OR 'a'='a

Resulting SQL:

select * from hacker where name = 'name' OR 'a'='a'

This makes the WHERE clause always true, allowing data extraction or even file writes such as INTO OUTFILE '/tmp/backup.sql', leading to full database dumps.

4. Implicit Type Conversion Injection

When the data type of a column does not match the supplied value, MySQL performs implicit conversion, which can be abused. Example: select * from hacker where email=0; Because email is a string, MySQL converts 0 to a string, matching all rows.

5. Blind Injection

Even without visible errors, attackers can infer information via time‑based or boolean‑based techniques. Example time‑delay payload:

select * from hacker where if(MID(version(),1,1) LIKE 5, sleep(5), 1)

If the query sleeps for 5 seconds, the attacker knows the MySQL major version is 5.

6. Wide‑Byte (GBK) Injection

When both the database and application use GBK encoding, a single‑byte high‑ASCII character combined with a backslash can bypass addslashes(). Example URLs:

http://localhost:8080/mysql.php?id=1
http://localhost:8080/mysql.php?id=1'

Because GBK treats two bytes as one character, the backslash can be absorbed, allowing injection.

7. Double‑Encoding Injection

If input is URL‑encoded twice, PHP’s automatic escaping may miss it. Example: http://localhost:8080/mysql.php?name=name%2527 PHP decodes once to name%27, then a second decode (via urldecode()) yields name', resulting in a vulnerable query.

Overall, preventing SQL injection requires using prepared statements or parameterized queries, rigorous input validation, disabling error display in production, proper character set handling, and avoiding unsafe functions like addslashes() and manual string concatenation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

databasePHPSQL injectionVulnerabilityWeb Security
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.