June 28, 2007

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.

Filed under: PHP — Michi @ 9:42 am

Share this

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Reddit
  • StumbleUpon
  • del.icio.us
  • description
  • Technorati
  • Slashdot
  • co.mments
  • NewsVine

Related

Today, I'm going to give away some source code! Celebrate! I wrote the code to address a relatively common problem among new programmers: the over-reliance on Magic Quotes. Do you know what Magic Quotes are? It's the annoying feature in...
I just discovered a bug today in PHP 5.1 (haven't confirmed if it was fixed in newer versions). When trying to enforce interface arguments on constructors, PHP behaves unexpectedly. Normally, interfaces allow you to enforce argument counts or types in...

No Comments »

TrackBack URI | Blog RSS | Comment RSS

No comments yet.

What do you think?