PHP SQL Injection Example


 

PHP SQL Injection Example

This Example illustrates how to injection is used in the sql query.

This Example illustrates how to injection is used in the sql query.

PHP SQL Injection Example

 This Example illustrates how to injection is used in the sql query. 

The "SQL Injection" is subset of the an unverified/insanities user input vulnerability ("buffer overflows" are a different subset), and the idea is to convince the application to run SQL code that was not intended. If the application is creating SQL strings naively on the fly and then running them, it's straightforward to create some real surprises.

In the below source code, the first query is the normal query which has no problem in execution, as our MySQL statement will just select everything from "emp" table where name equal to "sandeep".

However, the injection attack has actually made our query behave differently than we intended. By using a single quote (') they have ended the string part of our MySQL query

  • name = ' '

and then added on to our WHERE statement with an OR clause of 1 (always true).

  • name = ' ' OR 1

This OR clause of 1 will always be true and so every single entry in the "emp" table would be selected by this statement!

 

Source Code of phpSqlInjection.php

<?php
  $name = "sandeep"
  $query = "SELECT * FROM emp WHERE name = '$name'";
  echo "Normal: " . $query . "<br>";

  $wrongName = "'OR 1'";
  $query1 = "SELECT * FROM emp WHERE name = '$wrongName'";
  echo "Injection: " . $query1 . "<br>";

  $name1 = "'; DELETE FROM emp WHERE 1 or name = '"
  $query2 = "SELECT * FROM emp WHERE name = '$name1'";
  echo "Injection: " . $query2;
?>

 

Output:

 

Download Source Code

Ads