Share on Google+Share on Google+

PHP SQL Injection Example

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

  $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;




Download Source Code



Posted on: December 10, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null