Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The mysql use of addslashes() [duplicate]

Tags:

sql

php

mysql

Possible Duplicate:
What does mysql_real_escape_string() do that addslashes() doesn't?

If you are trying to prevent sql injection, the first thing you would do is use mysql_real_escape_string. Is it possible to inject a database using addslashes()?

like image 423
blake305 Avatar asked Jan 19 '11 02:01

blake305


People also ask

What is use of Addslashes in PHP?

Definition and Usage The addslashes() function returns a string with backslashes in front of predefined characters. The predefined characters are: single quote (') double quote (")

When should I use mysqli_real_escape_string?

You use mysqli_real_escape_string or any variation of it to make sure data form any user input field is properly escaped. For example, you have a form with a few inputs. You click submit and the data is sent as a request to your PHP script. In your script you insert into a database the values the user posted.

What is mysqli_real_escape_string?

The real_escape_string() / mysqli_real_escape_string() function escapes special characters in a string for use in an SQL query, taking into account the current character set of the connection. This function is used to create a legal SQL string that can be used in an SQL statement.

Do I need mysqli_real_escape_string?

Graham recently asked me: Do I still need to used mysqli_real_escape_string when used prepared statements in PHP? The simple answer is no. The way it used to work is that you would take form input data, put that into a variable, and inject that data into your MySQL query in order to add that data to the database.


2 Answers

addslashes is the rough equivalent of str_replace($str, "'", "\\'"). You can bypass it trivially with any number of unicode sequences that evaluate down to ' in mysql, but look completely different to addslashes().

Mysql_real_escape_String() on the other hand, uses the actual internal mysql escaping function, which knows exactly what to look for and fix to make it "safe" for mysql. What works for mysql may not work for another database, as each has slightly different escaping semantics and requirements, but if you're working with mysql, then the "real escape string" is the way to go.

like image 90
Marc B Avatar answered Sep 30 '22 07:09

Marc B


This is what happens when you only add slashes in a language which understands unicode encodings (or mix up encodings while sending the query): http://bugs.mysql.com/bug.php?id=22243

Basically it's safer to know what the database expects in term of encoding - this way you won't end up escaping half of the character by accident, or leaving later part of a character unescaped.

like image 27
viraptor Avatar answered Sep 30 '22 07:09

viraptor