What are the best PHP input sanitizing functions?

后端 未结 13 1470
抹茶落季
抹茶落季 2020-11-21 23:31

I am trying to come up with a function that I can pass all my strings through to sanitize. So that the string that comes out of it will be safe for database insertion. But t

13条回答
  •  孤独总比滥情好
    2020-11-21 23:49

    Database Input - How to prevent SQL Injection

    1. Check to make sure data of type integer, for example, is valid by ensuring it actually is an integer
      • In the case of non-strings you need to ensure that the data actually is the correct type
      • In the case of strings you need to make sure the string is surrounded by quotes in the query (obviously, otherwise it wouldn't even work)
    2. Enter the value into the database while avoiding SQL injection (mysql_real_escape_string or parameterized queries)
    3. When Retrieving the value from the database be sure to avoid Cross Site Scripting attacks by making sure HTML can't be injected into the page (htmlspecialchars)

    You need to escape user input before inserting or updating it into the database. Here is an older way to do it. You would want to use parameterized queries now (probably from the PDO class).

    $mysql['username'] = mysql_real_escape_string($clean['username']);
    $sql = "SELECT * FROM userlist WHERE username = '{$mysql['username']}'";
    $result = mysql_query($sql);
    

    Output from database - How to prevent XSS (Cross Site Scripting)

    Use htmlspecialchars() only when outputting data from the database. The same applies for HTML Purifier. Example:

    $html['username'] = htmlspecialchars($clean['username'])
    
    • Buy this book if you can: Essential PHP Security
    • Also read this article: Why mysql_real_escape_string is important and some gotchas

    And Finally... what you requested

    I must point out that if you use PDO objects with parameterized queries (the proper way to do it) then there really is no easy way to achieve this easily. But if you use the old 'mysql' way then this is what you would need.

    function filterThis($string) {
        return mysql_real_escape_string($string);
    }
    

提交回复
热议问题