helloandre
helloandre

Reputation: 10721

is this at least mildly secure php code?

I have a BUNCH of $_POST variables being sent in via a long form and instead of hard coding each one with a mysql_escape_string() is it ok for me to do the following? I don't know if this is actually safe and/or viable code.

foreach ($_POST as &$post_item){
    $post_item = mysql_escape_string($post_item);
}

I'm fairly certain that because i'm using the &, it's passing it in by reference, not value, so i'm actually changing the value in the $_POST.

Also, should I use mysql_real_escape_string() instead?

EDIT: I am using PDO and prepare() along with the above method. Does this take care of it for me?

Upvotes: 1

Views: 305

Answers (3)

Tomalak
Tomalak

Reputation: 338406

Why not use array_map()?

array_map(mysql_real_escape_string, $_POST);

But in reality you should be using parametrized/prepared statements.

mysql_real_escape_string() takes the current database character set into account, mysql_escape_string() does not. So the former is the better alternative in comparison.

Edit (following up the OP's edit to the question):

Since you already do PDO prepared statements, there is no need to modify your values. PDO takes care of everything, that's the whole point of it (If you really put all data in parameters, that is - just concatenating strings to build SQL statements leads to disaster with PDO or without). Escaping the values beforehand would lead to escaped values in the database.

Upvotes: 10

1800 INFORMATION
1800 INFORMATION

Reputation: 135463

In addition to the previous comments, another benefit to using parameterised queries is that the database will be able to do better optimisations and probably use a cached query plan so you will get better performance.

Upvotes: 1

Chad Birch
Chad Birch

Reputation: 74658

Yes, you should be using mysql_real_escape_string(), if you're going to go that route. But the correct way to make sure the variables are safe to send to the database is using Parameterized Queries which are provided in PHP through either the mysqli functions or PDO.

Upvotes: 3

Related Questions