Search code examples
phpfunctionsecuritymysql-real-escape-string

get_magic_quotes_gpc() and mysql_real_escape_string - security


i am practicing php and I am puzzled while interpreting a function to escape dangerous sql characters. i want to know how it works especially the $value in the second if. its quiet puzzling for me to understand the actual flow of function.

function quote_smart($value, $handle) {

   if (get_magic_quotes_gpc()) {
       $value = stripslashes($value);
   }

   if (!is_numeric($value)) {
       $value = "'" . mysql_real_escape_string($value, $handle) . "'";
   }
   return $value;
}

Solution

  • What the code does is basically;

    • First it removes the effect of magic_quotes_gpc if and only if it's enabled in the server. It should not be since magic_quotes has been deprecated for a while (and removed entirely in new PHP versions).

    • Second, it encloses all non numeric values of $value in single quotes, and escapes the value using mysql_real_escape_string to avoid SQL injection in your value string.

    Using recent versions of PHP, this method should not exist at all, since magic_quotes_gpc should never be enabled, and you'd be using PDO or MySQLi parameterized queries that do not need their values to be escaped.