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

问题描述:

I'm collecting form data, sending that to PHP validation script through AJAX call. The issue is on special characters the php validation script is not working as expected.

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 Validation

$postData = $_POST;

if (Filter::validateString($postData['firstName']) == false) {
    echo "Oops! Some characters used in your first name are not valid.";
}

PHP Filter

//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;
        }
    }
}

On an empty string it prints error to screen just fine. But if I do something like "~!@#$%^&*()", then it accepts the string as good and doesnt throw and error, even though the result of 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;
    }
}

That is more valid regex, but not the result you want: you're checking for pretty much all input, so it'll match "abcd" and return false as well. There are 11 characters with special meanings to regular expressions, only those and the " need to be escaped: ^$[]()|.*+-

Try this:-

<?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 is here:- http://phpfiddle.org/main/code/cdu-xg2