SQL injections / Escape special characters like ‘,”,

In the simplest case, special characters may simply break your query. In a more extreme case, a hacker might use SQL injections to gain access to your application. So it is important that we escape these special characters with a (backslash). That is, insert a backslash before each special character.

We can escape special characters (prepend backslash) using mysql_real_escape_string or addslashes functions. In most cases PHP will this do automatically for you. But PHP will do so only if the magic_quotes_gpc setting is set to On in the php.ini file. We first check whether this setting is on or not. If the setting is off, we use mysql_real_escape_string function to escape special characters. If you are using PHP version less that 4.3.0, you can use the addslashes function instead.

A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated.

If the magic quotes setting is on, we do not need escape special characters since PHP has already done it for us. We can check the magic_quotes_gpc by using get_magic_quotes_gpc function.

<?php
if(!get_magic_quotes_gpc()) {
	$login=mysql_real_escape_string($_POST['login']);
}else {
	$login=$_POST['login'];
}
?>

Permanent link to this article: https://blog.openshell.in/2010/11/sql-injection-php/

Leave a Reply

Your email address will not be published.