Chủ Nhật, 4 tháng 6, 2017

Php the best way prevent SQL Injection

Description: hacker add query sql to input _POST, _GET param. So need clean each input value.
Solution: Filter all  _POST, _GET param. 2 case:
#Case 1: Number, String with htmlspecialchars.
#Case 2: _Post as array - Multi select box need array_walk_recursive check each item.
The code will convert all special character to UTF-8.
<?php
/*prevent Sql Injection*/
function _CleanInputChars(&$value){
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
foreach ($_POST as $key => $value) {
/*Array*/
if(is_array($value)){
array_walk_recursive($value, "_CleanInputChars");
}
else{
/*Number,String*/
$_POST[$key] = _CleanInputChars($value);
}
}
foreach ($_GET as $key => $value) {
/*Array*/
if(is_array($value)){
array_walk_recursive($value, "_CleanInputChars");
}
else{
/*Number,String*/
$_GET[$key] = _CleanInputChars($value);
}
}
/*END prevent Sql Injection*/
?>

Example for Mysqli
Mysli '#' mean mysql no execute query after '#'.
Form username input:
nouser" or 1=1#
nouser' or 1=1#