开发者

Is it good practice to also trim form inputs as well as escape characters?

Like this,

$type = mysqli_real_escape_string($d开发者_运维知识库bc, trim($_POST['type']));

Does the trim improve security or does the mysqli_real_escape_string do enough already?


  • mysqli_real_escape_string is not enough.

  • and it's extremely bad idea to do it for the form inputs

  • it shouldn't be used at all anyway

Speaking of escaping, mysql[i]_real_escape_string is not make-my-data-magically-safe() kind of function but it's merely escaping string delimiters, to prevent strings from being broken. So, it won't help with numbers for example.
In fact, it has nothing to do with injection attacks, because this function should be used regardless of any attack, but only to make your strings SQL syntax rules compliant. And it will do no help with any other parts of query.

Also, it has nothing to do with "form inputs" nor with forms in general. It's database-related function, not forms-related. It's strings that going to the query should be escaped, and nothing else.

Anyway it shouldn't be used at all, as you have to use mysqli prepared statements instead.

And oh, yes - trim() has nothing to do with security, it's rather to make data look neat.


mysqli_real_escape_string will only escape the string to prevent injection attacks. If you don't want stray whitespace you should probably trim too.


Using the mysqli_real_escape_string will do enough to prevent injection in your database.

When displaying the posted value to the user, you should make sure to use htmlentities on it though.


trimming the whitespace of the string will do nothing to improve security. escaping the string should be enough to prevent sql injection.


Your example will help prevent SQL Injection, as any "Special Characters" will be escape (so " becomes \" and so on), but won't prevent XSS (Cross-Site Scripting), as it could still contain HTML characters like < and >

You can use the following code to help prevent both type of attacks

<?php
    //Get the variable
    $userValue = $_GET['value'];
    //Remove any preceding/leading whitespace
    $userValue = trim($userValue);
    //Convert any HTML characters to their entity value
    $userValue = htmlspecialchars($userValue);
    //Escape any SQL special characters
    $userValue = mysqli_real_escape_string($dbc, $userValue);
?>

For more information on XSS, check out this link https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)

Another useful resource is this PHP library, it's designed to filter any user input to protect against (pretty much) all methods of XSS http://htmlpurifier.org/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜