Created
March 7, 2018 06:40
-
-
Save KevinWang15/b4f7ba0f2986b0f421af75b597624198 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* 如果$_REQUEST中出现可能导致sql注入的字符,就返回400。 | |
* 需要在程序一开始的时候就运行。 | |
* | |
* 注意:本方法只对默认的html表单类型(application/x-www-form-urlencoded)有效 | |
* 如果有文件上传类型的(enctype="multipart/form-data"),则不能执行本方法 | |
*/ | |
function guardAgainstBadCharactersInRequest() | |
{ | |
foreach ($_REQUEST as $key => $value) { | |
// 以key、value的方式遍历所有request参数(包括$_GET和$_POST) | |
if (containsBadCharacters($value)) { | |
header('HTTP/1.1 400 Bad Request', true, 400); | |
echo "请求中含有非法字符,请修正后重试(请不要使用英文引号('与\")和英文反斜线(\))\n\n\n\n"; | |
die(); | |
} | |
} | |
} | |
/** | |
* 检查值中是否有非法字符 | |
* @param $value | |
* @return bool | |
*/ | |
function containsBadCharacters($value) | |
{ | |
// 只检查\和"', | |
// 因为: MySQL requires only that backslash and the quote character used to quote the string in the query be escaped | |
// (https://dev.mysql.com/doc/refman/5.7/en/mysql-real-escape-string.html) | |
$bad_characters = ["\"", "'", "\\"]; | |
foreach ($bad_characters as $bad_character) { | |
if (strpos($value, $bad_character) !== false) { | |
return true; | |
} | |
} | |
return false; | |
} | |
guardAgainstBadCharactersInRequest(); | |
?> | |
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" | |
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Document</title> | |
</head> | |
<body> | |
Welcome! | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment