sql injection with escape php function code

  • 2020-06-12 08:45:42
  • OfStack

sql injection:

Under normal circumstances:

delete. php? id = 3;
$sql = 'delete from where id = '.$_GET['id'];

Malicious case:

delete. php? 3 or id = 1;
$sql = 'delete from news where id = 3 or 1'; -- After this execution, all records will be deleted

Measures should be taken to... For example, whether it is a number or not before using it.

Make yourself believe that information from the client is never reliable!!

Escape:

Sometimes data coming from the client may contain special characters, such as single quotes, slashes, etc., so it needs to be escaped and converted to normal characters. In this case, string addslashes (string $str) is used to escape a variable. However, if you escape the elements in the array, loop through the array with foreach, as follows:


  foreach($_POST as $k=>$v) {
      if(is_string($v)) {
        $_POST[$k] = addslashes($v);
      }
  }

But if the array also contains an array, then you're going to escape recursively, and that's what you're going to use

array_walk_recursive (array & $input , callback $funcname [, mixed $userdata ])

Apply the user custom function funcname to each cell in the array array. This function will recurse into a deeper array. funcname typically takes two parameters. The value of the input parameter is the first and the key name is the second. If the optional userdata parameter is provided, it is passed to callback funcname as the third parameter. Returns TRUE on success or FALSE on failure

In other words: with a custom function, you must be able to receive at least two arguments, while addslashes () can only receive one argument, so the custom function is as follows:


      function a(&$v,$k){
        $v=addslashes($v);
      }
      array_walk_recursive(&$arr,'a');

Automatic system escape:

In PHP, there is the concept of a magic quote. How to open it? Answer: in ES82en. ini,magic_quotes_gpc=On; Restart apache

After the magic quotes is opened, the system will automatically to $_GET, $_POST, $to escape _COOKIE data, without knowing it, to manually escape again, have turned many, to a reasonable escape, must first know, magic symbols have opened, use magic_quotes_gpc judging (), value is not required, closing returns 0, close returns 1


  if(!get_magic_quotes_gpc()) {  //  If the magic quotes are not open 
      function _addslashes(&$v,$k) {
          $v = addslashes($v);
      }
      array_walk_recursive(&$_GET,'_addslashes');
      array_walk_recursive(&$_POST,'_addslashes');
      array_walk_recursive(&$_COOKIE,'_addslashes');
  }


Related articles: