Security threats in mind:

  • SQL Injections!!! --- Solutions: Prepared Statements (PDO) and including $bpdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); in the database connection

  • XSS Attacks!!! --- Solutions: htmlspecialchars(), Content-Security Policy (placed in htaccess).

  • OS Command Attacks!!! --- Solutions: Striping whitespace.

  • DOS Attacks!!! --- Solution: None implemented. I'm unsure if any additional precaution is necessary, since there are no login possibilities on my website.

Is the following script sufficient enough to sanitize user input?

//sanitize user input
$Tmessage = trim(preg_replace('/\s\s+/', ' ', htmlspecialchars($_POST["message"])));
$sanitizedMessage = filter_var($Tmessage, FILTER_SANITIZE_STRING);
//prepare info and submit into table
$stmnt = $pdo->prepare("INSERT INTO submissionsTable (message) VALUES (:message)");
$stmnt->execute(['message' => $sanitizedMessage]);
header("Location: success.html");
exit (0);
  • \$\begingroup\$ You better read something about how htmlspecialchars helps mitigate XSS attacks. It seems you dont get it even after you've been told several times. \$\endgroup\$
    – slepic
    Commented Oct 3, 2020 at 6:18
  • 1
    \$\begingroup\$ In short. Validate your input and sanitize your output. If you sanitize input you are effectivelly forcing your way of correcting clients mistake where the client may prefer a different kind of correction. If input contains invalid charcters or so, just refuse to process the request and thus give the client the opportunity to choose their own way of correcting the input and retry. \$\endgroup\$
    – slepic
    Commented Oct 3, 2020 at 6:25
  • \$\begingroup\$ You should sanitize output So that if i inputted a HTML fragment. On output i will just see it as text that included HTML markup rather then embedding my HTML fragment message as part of your HTML page. \$\endgroup\$
    – slepic
    Commented Oct 3, 2020 at 6:28

1 Answer 1


I am concerned that you are not digesting the advice given in previous reviews, because you are ONLY to call htmlspecialchars() just before you print to an html document (print to screen).

Effectively, you only need to handle whitespace related characters. Since you seem to be concerned with handling multibyte characters, the unicode flag should be used on your regex patterns. See this relevant SO page: Multibyte trim in PHP?

    'message' => filter_var(
            ['/^\s+|\s+$/u', '/\s{2,}/u'],
            ['', ' '],

If you are using FILTER_SANITIZE_STRING to strip tags, please see some potentially buggy behavior in the comments at https://www.php.net/manual/en/filter.filters.sanitize.php

P.s. I'd probably not use a named parameter in the prepared statement; there is only one bound parameter so there is no chance of confusion.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.