-2

I am borrowing a code from w3schools.com to validate a name. Unfortunately, the regex only allows letters and whitespace. How can I amend this code so that a name like O'Shaughnessy does not produce an error message? Also, another part of my general codes is causing a user input to appear on MySQL with a backslash which was not intended. I had used mysqli_real_escape_string to prevent SQL injection attacks, and I believe this is the reason why the backslash is appearing in the data. How do I get rid of it?

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
            $name = "";
            $nameErr = "Only letters and white space allowed";
        }
    }
}
WeSt
  • 2,628
  • 5
  • 22
  • 37
user3972671
  • 169
  • 1
  • 1
  • 6

1 Answers1

1

The best way to combat SQL injection is to ditch mysqli_real_escape_string completely and use prepared statements instead. This way, you don't have to worry about cleaning up your strings until you want to display them afterwards. Prepared statements can be used with both mysqli and PDO and essentially means that you send the query and the data separately. This means that the users can't change your query.

As for the name; first think about if you really want to validate it. There are some wierd names out there and validating them isn't really useful most of the time. Still, if that's the way you want to go, all you have to do is make sure that ' is included in your regex. Like this:

Original:

/^[a-zA-Z ]*$/

Edited:

/^[a-zA-Z' ]*$/

That's it. One small addition and then you're golden. And you'll annoy people with umlauts in their names. Or numbers.

Szandor
  • 363
  • 1
  • 12