Preventing SQL Injection in PHP Tutorial

Introduction

In this tutorial, I will teach you how to Prevent SQL Injection in writing your PHP Queries for your current and future PHP Projects. This tutorial aims to give the IT/CS Students or those new to PHP Language a reference to learn for securing their database data in PHP. Here, I will be providing some snippets with a sample source code that demonstrates our topic for this tutorial.

What is SQL Injection?

An injection attack known as SQL Injection (SQLi) enables the execution of malicious SQL commands. These commands manage a database server that sits in front of a web application. SQL Injection flaws allow attackers to get around application security safeguards. The full content of a SQL database can be retrieved by getting past authentication and authorization of a web page or online application. They can also add, alter, and delete records in the database using SQL Injection.

How to Prevent SQL Injection in PHP?

To prevent SQL Injection in your PHP Project that uses MySQL Database. You must practice the following step for writing your PHP Code and MYSQL Queries.

  1. Validate and Sanitize Input Data
  2. Use a Prepared Statement
  3. Bind Query Parameters
  4. Execute the Queries

The above step can be achieved by using PDO and MySQLi.

Example

Below are the sample snippets for both vulnerable and prevents SQL Injection. You will see the sample result for both.

Database Schema and Data

Let's pretend that we have the following database schema and data in our database. The table is the user list of your web application which contains the user access.

  1. CREATE TABLE `users` (
  2. `first_name` text NOT NULL,
  3. `last_name` text NOT NULL,
  4. `username` text NOT NULL,
  5. `password` text NOT NULL
  6.  
  7. INSERT INTO `users` (`id`, `first_name`, `last_name`, `username`, `password`) VALUES
  8. (1, 'Super', 'Administrator', 'super_admin', 'super_admin#123'),
  9. (2, 'Admin 1', 'Administrator', 'admin1', 'admin1#123'),
  10. (3, 'Admin 2', 'Administrator', 'admin2', 'admin2#123');

Sample Form

Here is the sample login form for fetching and checking the user credential. I will only be using text type for the password input field just for demonstration purposes only for this tutorial.

  1. <fieldset class="border px-2 py-3 mb-3">
  2. <form action="" method="POST">
  3. <div class="mb-2">
  4. <label for="" class="control-label">Username</label>
  5. <input type="text" name="username" class="form-control" value="<?= (isset($_POST['username'])) ? $_POST['username'] :'' ?>">
  6. </div>
  7. <div class="mb-2">
  8. <label for="" class="control-label">Password</label>
  9. <input type="text" name="password" class="form-control" value="<?= (isset($_POST['password'])) ? $_POST['password'] :'' ?>">
  10. </div>
  11. <div class="mb-2">
  12. <button class="btn btn-primary btn-sm" name="login">Submit</button>
  13. </div>
  14. </form>

Output

PHP Preventing SQL Injection -sample form

Sample Data

Use the "anything' or 'x' = 'x" as the username and password to the form and see the result for both PHP Queries execution of the snippets below.

Sample Vulnerable PHP Script

The following PHP Code is an example of vulnerable to SQL Injection.

  1. <?php
  2. if($_SERVER['REQUEST_METHOD'] == 'POST'){
  3. $username = $_POST['username'];
  4. $password = $_POST['password'];
  5.  
  6. $sql = "SELECT * FROM `users` where `username` = '{$username}' and `password` = '{$password}' ";
  7. $query = $conn->query($sql);
  8. $results = $query->fetch_all(MYSQLI_ASSOC);
  9. }
  10. ?>

Output

PHP Preventing SQL Injection -Vulnerable Result

Sample PHP Script that Prevents SQL Injection

The following PHP script is an example of a PHP Query that prevents SQL Injections. The script below is using MySQLi Prepared statement and sanitizes input data.

  1. <?php
  2. if($_SERVER['REQUEST_METHOD'] == 'POST'){
  3. // Sanitizing Input Value
  4. $username = addslashes($conn->real_escape_string($_POST['username']));
  5. $password = addslashes($conn->real_escape_string($_POST['password']));
  6.  
  7. $sql2 = "SELECT * FROM `users` where `username` = ? and `password` = ? ";
  8. // Prepare Statement
  9. $stmt = $conn->prepare($sql2);
  10. // binding query paramters "s = string"
  11. $stmt->bind_param('ss', $username, $password);
  12. $stmt->execute();
  13. $results2 = $stmt->get_result();
  14. $data = $results->fetch_all(MYSQLI_ASSOC);
  15. }
  16. ?>

Output

PHP Preventing SQL Injection -Invulnerable Result

That's it! I also created and provided a simple web application that demonstrates How to Prevent SQL Injection in PHP. The download button is located below this article. Feel free to download and modify it.

That's the end of this tutorial. I hope this tutorial will help you learn to secure your PHP Projects. Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment