问题描述:

so, I have this piece of code:

if ($_SERVER["REQUEST_METHOD"] == "POST") {

if (empty($_POST["name"])) {

$nameErr = "This field is required";

} else {

$name = test_input($_POST["name"]);

if (!preg_match("/^[a-zA-Z ]*$/",$name)) {

$nameErr = "Only letters allowed";

}

And it works fine, but there is one problem, what if the users writes ' (Apostrophe)?

I tried it myself, and it ruins the code somehow, as it never reaches the database, and I can't add the Apostrophe to the preg_match because that ruins the code itself and doesn't run correctly!

So my question is, how can I stop the user from writting ' (Apostrophe)?

Thanks for reading.

网友答案:

Should you stop the user writing apostrophe, or should you prepare your code for this kind of situation? Today's an apostrophe, tomorrow's a double quote, and you can't manage every single symbol (think of other alphabets).

If you are directly adding that to a database, escape the symbols using either Mysqli's or PDO's (or any database management system you use) escape methods. Otherwise, your code might be in real danger, especially because of SQLInjection. A fairly good example of what could happen is shown here, in this comic from xkcd, but just imagine this input:

test'); drop table important_data;--

Yes, you are (at least in this case and after validating it with your regex) covering from that issue, but that could happen in every single place around your code (suppose a comment form, where you could write anything). ALWAYS escape every single user input. It will defend you from lots of future issues.

相关阅读:
Top