2

I just read about SQL injection and found this function on the blog i was reading I am wondering if it is safe for SQL injection.. say if i pass do remove_mq($_POST) to it, could i be using $_POST["var"] inside a query without a problem?

function remove_mq($array){
    foreach($array as $key => $value){
        if(is_array($value)){
            $array[$key] = remove_mq($value);
        }
        else{
            $array[$key] = addslashes($value);
        }
    }
    return $array;
}
Dany Khalife
  • 1,850
  • 3
  • 20
  • 47

4 Answers4

5

No. Addslashes is not the proper function to escape for a query. You need to use mysql_real_escape_string

Besides that, you should not perform SQL escaping before actually using a value in a query. Assume you have something like <input name="foo" value="$_POST[foo]" - then you need it htmlspecialchars()-escaped and not addslashes(etc.)-escaped


Besides that, the best solution would be using PDO with prepared statements since you separate SQL queries from params so you do not need any escaping at all.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 2
    PDO prepared statements are superior to using mysql_real_escape_string with ad-hoc queries. The reason addslashes isn't secure, btw, is that there are certain multibyte characters that will allow an attacker to still make a malicious query. – Jeff Day Oct 31 '11 at 13:27
  • thanks for your comments, looks like more research to be done for me ;) – Dany Khalife Oct 31 '11 at 15:51
2

Best practice nowadays is prepared queries. Example:

$stmt = $pdo->prepare('SELECT username FROM users WHERE id = :id');
$stmt->execute(array(':id' => $_GET['id']));
$result = $stmt->fetchAll();

This code is totally secure

Nanocom
  • 3,696
  • 4
  • 31
  • 46
2

Well, all the answers above missing the point.

  1. addslashes() is good enough as long as your data encoding is either utf-8 or any single-byte one.
  2. but the whole approach, despite of the function used, is utterly wrong

Doing massive escaping over $_POST makes no sense and doesn't guarantee full protection.
No addslashes nor mysql_real_escape_string do any actual protection. It does as little as string delimiters escaping. So, you have to use this function:

  • only on strings
  • only on strings actually going into query.

all other required manipulations are described in the link in the comments

and some info for ones who feel extremely educated in the matter:
your beloved PDO, when used out of the box, do use the same defamed addslashes

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
1

Nope - just use the built in function for it! mysql_real_escape_string() is always going to be more reliable than any function you can write yourself.

Here's an article explaining why you should use mysql_real_escape_string over addslashes.

Of course, the best approach is to use prepared queries. Here's some information on them.