通过AJAX将特殊字符传递给PHP
我正在收集表单数据,并通过AJAX调用将其发送到PHP验证脚本。 问题是在特殊字符的PHP验证脚本没有按预期工作。
HTML:
<input type="text" name="firstName" class="firstName"
placeholder="[first name]" required autofocus maxlength="25" size="25" />
JS:
$(".button").click(function () {
var firstName = encodeURIComponent($("input.firstName").val());
var datastring = "firstName=" + firstName;
$.ajax({
type: "POST",
url: "/scripts/validateSignup.php",
data: datastring,
cache: false,
success: function (errorMessage) {
//print to screen
}
});
});
PHP验证
$postData = $_POST;
if (Filter::validateString($postData['firstName']) == false) {
echo "Oops! Some characters used in your first name are not valid.";
}
PHP过滤器
//Returns true if string is good, false otherwise
public static function validateString($string) {
$string = trim($string);
if ($string == null || $string == "") {
return false;
} else {
if (preg_match("/[^.,-_'"@?!:;$#%&+= a-zA-Z0-9()]/", $string) == true) {
return false;
} else {
return true;
}
}
}
在一个空字符串上,它会将错误输出到屏幕上。 但是,如果我做了类似“〜!@#$%^&*()”的操作,那么它会接受字符串为好,并且不会抛出错误,即使preg_match == false的结果。
$string = trim($string);
if ($string == null || $string == "") {
return false;
} else {
if (preg_match("/[^.,-_'"@?!:;$#&+=sa-zA-Z0-9()]/", $string) == true) {
return false;
} else {
return true;
}
}
这是更有效的正则表达式,但不是你想要的结果:你正在检查几乎所有的输入,所以它会匹配“abcd”并返回false。 有11个字符对正则表达式有特殊含义,只有那些和“需要被转义:^ $ []()|。* + -
尝试这个:-
<?php
$string = "tes$%tname"; // invalid string
//$string = "testname"; // valid string
if(test($string) == false)
{
echo "String is invalid";
}
function test($string){
$string = trim($string);
if ($string == null || $string == "") {
return false;
} else {
if (preg_match("/[^.,-_'"@?!:;$#&+=sa-zA-Z0-9()]/",$string) == true) {
return false;
} else {
return true;
}
}
}
?>
PHPFiddle在这里: - http://phpfiddle.org/main/code/cdu-xg2
链接地址: http://www.djcxy.com/p/92703.html