Escaping

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
MarK (CZ)
Forum Contributor
Posts: 239
Joined: Tue Apr 13, 2004 12:51 am
Location: Prague (CZ) / Vienna (A)
Contact:

Escaping

Post by MarK (CZ) »

Hi all,

I have a question about escaping strings into queries. I didn't use any escaping and it works even when user inputs data with " or '. When echo the sql query, it looks like it's already escaped.

So I wonder if I should use any of those escaping commands such as

Code: Select all

mysql_escape_string()
or

Code: Select all

AddSlashes()
and which and why if yes.

Thx in advance,
MarK
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

Seems like you have magic_quotes_gpc on. Use mysql_escape_string anyway, this function is specifically designed to escape the strings before embedding in sql query. Personally I use this snippet often:

Code: Select all

$var = $_GET['var'];
  if( ini_get('magic_quotes_gpc') ) {
     $var = strip_slashes($var);
  }
  $query = 'select * from something where a = "' . mysql_escape_string($var) . '"';
User avatar
MarK (CZ)
Forum Contributor
Posts: 239
Joined: Tue Apr 13, 2004 12:51 am
Location: Prague (CZ) / Vienna (A)
Contact:

Post by MarK (CZ) »

So every data to store or compare from user input: first strip slashes (if mag. qout. on) and second mysql escape... This should be safe enough against hacking attacks like passing "admin OR username = 'admin" as username, right?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

Yes, it should. Keep in mind that magic_quotes_gpc affects only GET, POST and COOKIES variables. It's important to know that some items in $_SERVER array are supplied by user's browser or intermediate proxy servers, so you can't trust them. X_FORWARDED_FOR is a good example of such item.
Post Reply