PHP/MySQL: The Escape Method Done Right

The issue is that PHP has some built in methods for escaping data. No, addslashes() is insufficient to protect you from SQL injection attacks (read: these get you fired). Here’s the solution for an escape function that does everything you could hope for. The @ symbols suppress PHP warnings so that I can use them to my advantage (newbies, please don’t try it at home). This goes inside a Database class.

/**
 * Escapes the passed value so it is ready to be inserted into the database. Takes magic quotes into
 * consideration as well.
 *
 * @param    string    parameter
 * @return    string    escaped parameter
 */
public function escape($value) {
    /*
     * stripslashes only if necessary
     */
    if (get_magic_quotes_gpc()) {
        $value = stripslashes($value);
    }
    /*
     * if this fails ($newValue is false), we know we need to fall back on the PHP4 way
     */
    $newValue = @mysql_real_escape_string($value);
    /*
     * if no connection handler can be found use this instead
     */
    if(FALSE === $newValue) {
        $newValue = @mysql_escape_string($value);
    }
    return $newValue;
}

Feel free to post suggestions.

Comments are closed.