문제

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;
}
도움이 되었습니까?

해결책

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.

다른 팁

This function doesn't "escape dangerous sql characters". It does format $value as a correct mySQL literal. But does it wrong,

  • because it deals with get_magic_quotes_gpc() while it shouldn't.
  • and it does some magic, trying to format either numbers or strings
  • and it's intended to format values inserted into query directly, not via placeholder.

Correct version have to be

function quote_string($value, $handle)
{
    return = "'" . mysql_real_escape_string($value, $handle) . "'";
}

and it should be used only to process a placeholder.

While magic quotes have to be dealt with in a bootstrap file, for all input values, not only ones going into query, though for compatibility purpose only.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top