What is SQL Injection
Sql Injection is a technique where malicious users tries to update sql query in a webpage by inputting some special characters like
1 or 1=1
or 1
or may be other set of such characters
lets study a webpage with url
www.somedomain.com/news.php?id=2
This page showing news which is saved at number 2, and in PHP coding it has a query like
1 2 |
//sql query $query = "SELECT * FROM news where id = ".GET['id']; |
with above url where id=2 this query becomes
1 2 |
//sql query $query = "SELECT * FROM news where id = 2"; |
but if someone tries to change id=2 to some thing like above set of characters, lets try 1 or 1=1 URL will look like this
www.somedomain.com/news.php?id=1 or 1=1
query will become something like
1 2 |
//sql query $query = "SELECT * FROM news where id =1 or 1=1"; |
this query has 2 conditions
where id =1 or 1=1
id=1 is true for record where id=1 this is ok but or 1=1 is true which will return all records which is what the hacker is looking for.
Trying such set of characters sql query may generate error and if errors are not well handled it will display table name may be the database name also in error message. now if someone know table name he/she can also run the following URL.
www.somedomain.com/news.php?id=1; delete from news;
see what kind of query become
1 2 |
//sql query $query = "SELECT * FROM news where id =1; delete from news;"; |
wawo these are 2 queries in first it selects a record while the second query deletes all records from news table.
he/she can also delete the whole table or database too. but this might be his last option, before deleting everything he/she must want to access everything and play with it.
In such a way hacker finds Users, Members or Admins table and wants to get password of some user with admin privilege an then logs in to your CMS with that username and password, If could not find one then he will tries to insert new user by issuing an insert query.
but do not worry these issues has easy solutions.
How to Prevent Sql Injection
To prevent SQL Injection in PHP or any other language you have to CLEAN user input before attaching it into SQL queries, by Cleaning I mean to replace special characters from user input, special characters are
- single quote
- double quote
- hash sign (#) it is used for comment in sql
we can write our own function for it but PHP has already a function called
mysql_real_escape_string() or for mysqli mysqli_real_escape_string()
(PHP 4 >= 4.3.0, PHP 5)
mysql_real_escape_string — Escapes special characters in a string for use in an SQL statement
this makes sure to convert user input into string instead of SQL operators.
hope with this article you got the idea of SQL Injection, its risk and prevention.
Comments