Should I mysql_real_escape_string all the cookies I get from the user to avoid mysql injection in php?

When a user goes to my site, my script checks for 2 cookies which store the user id + part of the password, to automatically log them in. Its possible to edit contents of cookies via a cookie editor, so I guess its possible to add some malicious content to a written cookie?

Should I add mysql_real_escape_string (or something else) to all my cookie calls or is there some kind of built in procedure that will not allow this to happen? I never really thought about this until just now.....


What you really need to do is not send these cookie values that are hackable in the first place. Instead, why not hash the username and password and a (secret) salt and set that as the cookie value? i.e.:

define('COOKIE_SALT', 'secretblahblahlkdsfklj');
$cookie_value = sha1($username.$password.COOKIE_SALT);

Then you know the cookie value is always going to be a 40-character hexidecimal string, and can compare the value the user sends back with whatever's in the database to decide whether they're valid or not:

if ($user_cookie_value == sha1($username_from_db.$password_drom_db.COOKIE_SALT)) {
  # valid
} else {
  #not valid

mysql_real_escape_string makes an additional hit to the database, BTW (a lot of people don't realize it requires a DB connection and queries MySQL).

The best way to do what you want if you can't change your app and insist on using hackable cookie values is to use prepared statements with bound parameters.

Need Your Help

PDO Exception could not find driver

php postgresql symfony2 pdo mamp

I know this question have been asked a thousand of times, but I can't find a solution. I'm running Symfony 2 with a PostgreSql database (php running in MAMP, and PG DB on an another port and instal...

Jquery selector question for form labels

jquery label selector

I'm trying to make a selector using form labels.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.