Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Injection, Quotes and PHP

I'm quite confused now and would like to know, if you could clear things up for me.

After the lateste Anon/Lulsec attacks, i was questioning my php/mysql security.

So, i thought, how could I protect both, PHP and Mysql.

Question: Could anyone explain me, what's best practice to handle PHP and Mysql when it comes to quotes?

  • Especially in forms, I would need some kind of htmlspecialchars in order to protect the html, correct?
  • Can PHP be exploitet at all with a form? Is there any kind of protection needed?
  • Should I use real_escape_string just before a query? Would it be wrong/bad to use it already within PHP (see sanitize_post function)?

Currently i'm using the following function. The function "sanitizes" all $_POST and $_GET variables. Is this "safe"?

function sanitize_post($array) {
    global $db;
    if(is_array($array)) {
        foreach($array as $key=>$value) {
            if(is_array($array[$key])) {
                $array[$key] = sanitize_post($array[$key]);
            } elseif(is_string($array[$key])) {
                $array[$key] = $db->real_escape_string(strtr(stripslashes(trim($array[$key])), array("'" => '', '"' => '')));
            }
        }            
    } elseif(is_string($array)) {
        $array = $db->real_escape_string(strtr(stripslashes(trim($array)), array("'" => '', '"' => '')));
    }
    return $array;
}

I'm using PHP 5.3.5 with Mysql 5.1.54.

Thanks.

like image 382
ptmr.io Avatar asked Dec 02 '22 02:12

ptmr.io


1 Answers

mysql_real_escape_string deserves your attention.

However direct queries are a quagmire and no longer considered safe practice. You should read up on PDO prepared statements and binding parameters which has a side benefit of quoting, escaping, etc. built-in.

like image 71
Mr Griever Avatar answered Dec 05 '22 12:12

Mr Griever