通过AJAX将特殊字符传递给PHP


Passing Special Characters to PHP via AJAX

我正在收集表单数据,并通过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;
    }
}

这是更有效的regex,但不是您想要的结果:您正在检查几乎所有的输入,因此它将匹配"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