使用 PHP 清理 GET 输入.是不是太晚了,我甚至需要这样做吗?



我正在尝试通过数组清理搜索中的用户输入。我想知道我是否以正确的方式清理了输入,以及我什至需要在这样的函数中使用它。你会得到它:

主要问题#1:我是在正确的地方以正确的方式"消毒"输入还是为时已晚。

HTML ->

<div >
<form class="theform"> 
Jeg vil gerne have: <input class="theinputbox" type="text" onkeyup="showHint(this.value)">
</form>
</div>
<div id="theHint"><span id="txtHint"></span></div>

带有 showHint((; -> 的 javascript

function showHint(str) {
if (str.length === 0) { 
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "ToostGetHint.php?q=" + str, true);
xmlhttp.send();
}
}

带有数组和结果的 PHP ->

<?php
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$q = test_input($_REQUEST["q"]);
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

$hint = "";
// lookup all hints from array if $q is different from "" 
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint =  '<p class="txtHint">' . $name . '</p>';
} else {
$hint .= '<p class="txtHint">' . $name . '</p>';
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values 
echo $hint === "" ? "no suggestion" : $hint;
?>

在您的特定情况下,您不需要消毒。您永远不会输出输入,因此没有 XSS 的机会,并且您永远不会在 SQL 语句中使用输入,因此没有 SQL 注入的机会。

如果要清理,对于此特定情况,则应将要允许的字符列入白名单。由于您是匹配名称,因此实际上只需要允许大写和小写字母。您可以通过使用正则表达式来实现白名单。

相关内容

最新更新