SQL injection
PHP security
web development
database protection
secure coding techniques

How can I prevent SQL injection in PHP?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design
 
1SQL injection is a common attack vector that allows attackers to interfere with the queries that an application makes to its database. This article focuses on prevention techniques in PHP applications. By understanding how SQL injection works and implementing best practices, developers can reduce the attack surface and protect their applications from vulnerabilities.
2
3## Understanding SQL Injection
4
5SQL injection occurs when an attacker can manipulate the queries an application sends to the database by inserting or "injecting" malicious SQL code. This is often due to improper handling of user input. A basic example is a login form where an attacker inputs `' OR 1=1 --` to bypass authentication.
6
7```php
8<?php
9`$username = $`_POST['username'];
10`$password = $`_POST['password'];
11`$query = "SELECT * FROM users WHERE username = '$`username' AND password = '$password'";
12`$result = mysqli_query($`conn, $query);

In the example above, if an attacker submits ' OR 1=1 --, the query becomes:

sql
SELECT * FROM users WHERE username = '' OR 1=1 --' AND password = ''

This effectively bypasses the password check and logs the attacker in as the first user in the users' table.

Techniques to Prevent SQL Injection

1. Use Prepared Statements

Prepared statements ensure that user input is treated strictly as data and not executable code.

Example:

php
1<?php
2`$conn = new mysqli($`servername, $`username, $`password, $dbname);
3
4// Prepare statement
5`$stmt = $`conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
6`$stmt->bind_param("ss", $`username, $password);
7
8// Execute the prepared statement
9$stmt->execute();
10`$result = $`stmt->get_result();

2. Use PDO (PHP Data Objects)

PDO is a database access layer that provides a uniform method of access to multiple databases. It automatically helps prevent SQL injection through prepared statements.

Example:

php
1<?php
2`$pdo = new PDO("mysql:host=$`servername;dbname=$`dbname", $`username, $password);
3`$stmt = $`pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
4`$stmt->execute(['username' => $`username, 'password' => $password]);
5`$result = $`stmt->fetch();

3. Input Validation

Always validate and sanitize user input. Ensure data types are consistent with the expected input.

Example:

php
<?php
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

4. Escape User Input

If using raw SQL queries, always escape user inputs. This is a less preferred method but can be used with good sanitation practices.

Example with mysqli real escape function:

php
1<?php
2`$username = $`conn->real_escape_string($_POST['username']);
3`$password = $`conn->real_escape_string($_POST['password']);
4`$query = "SELECT * FROM users WHERE username = '$`username' AND password = '$password'";
5`$result = mysqli_query($`conn, $query);

Summarizing Key Prevention Techniques

TechniqueExample Code Snippet/Explanation
Use Prepared Statements$stmt = $conn->prepare("SELECT ... WHERE username = ?");
Use PDO$stmt = $pdo->prepare("SELECT ... WHERE username = :username");
Input Validation$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
Escape User Input$username = $conn->real_escape_string($_POST['username']);

Additional Considerations

Use of Stored Procedures

Stored procedures are precompiled SQL queries. Use them to encapsulate the logic within the database, reducing reliance on client-side constructs.

Least Privilege Principle

Ensure database users have the minimal privileges necessary for the tasks they need to perform. For instance, avoid using an account with DROP or DELETE privileges for read-only operations.

Regular Security Audits

Regularly review and test your code for SQL injection vulnerabilities. Use automated tools and conduct code reviews to identify potential vulnerabilities.

Secure Configuration

Always keep your PHP and database server configurations secure and up-to-date with the latest security patches. Disable any functions and features that are not needed.

Preventing SQL injection is all about securing all entry points to your application where SQL queries are performed. Using the techniques outlined above, developers can build more secure applications that are robust against SQL injection attacks.

 

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.