Dealing With SQL Injection

sqlinjectionIf you have no idea about what sql injection is, read this wiki article.

How can we prevent SQL injection attacks?

As with XSS attacks, you must never trust user input. The best way of cleaning user input is using PHP’s built in mysql_real_escape_string() function; this will escape characters such as ‘, ” and others, making them useless in “breaking out” of a quoted string as in the above example. If you’re using a number in your query, then you should use intval() on the inputted number to ensure it is numeric.

I have also made the following function that can be used to discard any characters that can be used to manipulate the SQL queries. So, you can use this functions just as well to validate your SQL queries:

function is_valid($input)
{
    $input = strtolower($input);

    if (str_word_count($input) > 1)
    {
        $loop = true;
        $input = explode(" ",$input);
    }

    $bad_strings = array("'", "--", "select", "union", "insert", "update", "like", "delete", "1=1", "or", "#", "//");

    if ($loop == true)
    {
        foreach($input as $value)
        {
            if (in_array($value, $bad_strings))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }
    else
    {
        if (in_array($input, $bad_strings))
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

Function Usage

This is how you can use the above function:

if (is_valid($_POST["username"]) == true && is_valid($_POST["password"]) == true)
{
    //login now
}

However, don’t depend on this function alone, you must still use the mysql_real_escape_string() function in your SQL query. You can also modify this function or you can get a new idea to work out of this function.