PHP: Prevent SQL Injection Attacks

by Yang Yang on January 25, 2009

Share This Article:
Subscribe to Kavoir: blog feed

SQL injection is a typical code injection attack that exploits weaknesses of application in the database layer. SQL injection vulnerability is created when one scripting or programming language is embedded in or used as input in another with failure to verify the legality or filter for potential dangerous codes.

SQL injections are possible when input from user is either incorrectly filtered for string literals embedded in SQL query statements or it’s not strongly typed thereby incurring unexpected execution.

The solution to this is to never trust user input data by default, especially those that will be used in a SQL statement. Check for data type and escape string literals before committing them into a query.

Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 5 comments… read them below or add one }

somename July 31, 2009 at 11:10 pm

alert(‘oh, no…’);

Reply

Yang Yang February 26, 2010 at 4:25 pm

i.spank(you);

Reply

Nayan Paul April 24, 2010 at 10:19 pm

function makeEncode($sql)
{
$sql = preg_replace(sql_regcase(“/(from|select|insert|delete|where|drop table|like|show tables|\’|'\| |=|-|;|,|\|’||#|\*|–|\\\\)/”), “” ,$sql);
$sql = trim($sql);
$sql = strip_tags($sql);
$sql = (get_magic_quotes_gpc()) ? stripslashes($sql) : mysql_real_escape_string($sql);
$sql = htmlentities($sql);
return $sql;
}

Reply

Yang Yang April 25, 2010 at 3:18 pm

What is this?

Reply

Nayan@Howtotechie January 25, 2011 at 7:32 pm

Write a function like that
function makeEncode($value)
{
$value = trim(htmlentities($value));
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
else
{
$value = mysqli_real_escape_string($this->dbLink,$value);
}
return $value;
}
then use this when entering data into mysql database

Reply

Leave a Comment

{ 2 trackbacks }

Previous post:

Next post: