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; } 
2

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
thanks for your comments, looks like more research to be done for me ;)
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

Comments

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

1 Comment

Thanks Col, always good to have a professional's advice :) Are you by any chance a teacher?
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.