• php 22.09.2008 No Comments

    This guide goes over the basics of cleaning user input for safe use. This includes escaping strings correctly, stripping html and tags, preventing SQL injection, and other security issues. Anytime you use a $_POST, $_GET, or are receiving any information that the user can modify, you must be sure that you properly escape it, and clean it in some cases. This guide will show you how to do that, and more.

      

    Clean All User Input

    Anytime you use a $_POST, $_GET, or are receiving any information that the user can modify, you must be sure that you properly escape it, and clean it in some cases.

    Preventing SQL Injection

    I’m going to use a login form as an example. To query our database and check to see if they logged in correctly, you might use a query like…

    select `username`, `password` from `users` where `username` = '$var' and `pass` = '$var2';

    If someone were to type in ‘ or username like’%admin%’; — into the login form, they would be logged in with an account that has the word admin in it. To fix this problem, after connecting to the MySQL server, you can use…

    mysql_real_escape_string($var);

    Using this will escape all characters that need to be escaped to prevent tampering with the MySQL query. Another problem for MySQL is % and _, which can be escaped using…

    addslashes($var);

    HTML filtering

    Sometimes you may want to clean certain html entities in strings. To do this, you can use…

    $var = “<b>bold</b>”;
    htmlentities($var);

    This would output: & l t ; b & g t ; bold & l t ; / b & g t ;

    To change it back to a usable form, you can use…

    html_entity_decode($var);

    To strip the HTML tags from a string, and specify which strings you want to allow, you can use…

    $var = “<a><b>link</a></b>”;
    strip_tags($var, '<a><b>');

    The second argument is not needed, passing just the variable you want to clean will strip all tags from the string. This example would only allow b and a tags through. However, it is important to note that strip_tags() is not failsafe; that is, malformed tags can remove more or less than you’d ideally like to.

    To make sure that html does not render if it gets shown, you can use…

    htmlspecialchars($var);

     
    If you have a string that is escaped from using mysql_real_escape_string() or addslashes(), you can use stripslashes($var) to remove all of the slashes.

    Tags: , ,

 

January 2009
M T W T F S S
« Dec    
 1234
567891011
12131415161718
19202122232425
262728293031