views:

168

answers:

3

Hi,

If I escape data with

addcslashes($input,chr(0x00) . chr(0x0d) . chr(0x0a) . chr(0x1a) . chr(0x5c) . chr(0x27) . chr(0x22));

would that be enough to stop SQLi? I have all required characters there, so, as long as the $input is UTF-8, there should be no problems with that itself. Of course invalid use of the method or something similar can cause SQLi. I'm using this because I'd like to escape without connecting to the database and I know my input is UTF-8, if it's not, I convert it.

A: 

If you're using the MySQL function library, the documentation strongly suggest that you use their method to sanitize DB input.

[mysql_real_escape_string] must always (with few exceptions) be used to make data safe before sending a query to MySQL.

Edit: I am aware that you don't want to connect to the DB first to do this; however, this is considered to be the best practice by PHP. @Bobince's answer explains the details of why this is the case

Justin Johnson
He also said that he also wants to not have to connect to a database.
Mez
I am aware of that. I'm pointing out the best-practice here. @bobince went into the details that I neglected about why he should do as the documentation says.
Justin Johnson
+1  A: 

A better option would be to use the inbuilt filter method, and, like said above, functions dedicated to preventing injection. You can also use prepared statements in addition to all this. Don't try to rely on your own attempts at sanitising like this - there are tried and tested common functions used on a day to day basis that work, and if you find a bug or flaw with them, be sure to let us know.

squeeks
+3  A: 

I'm using this because I'd like to escape without connecting to the database

For the specific case of MySQL that is simply not possible. Until the connection is made, PHP does not know what character encoding is being used to communicate with the database, and hence it doesn't know which ' bytes in your string correspond to ' characters. If your connection is always UTF-8, you'd be safe, but if that code was deployed on a server that defaults to, say, Shift-JIS, you might escape a partial-character ' byte incorrectly and actually cause an SQL injection where there was none previously.

For other databases, that's the wrong sort of escaping entirely; ANSI SQL and most DBMSs use a doubled '' to denote an apostrophe in a string literal, and don't escape any other characters. MySQL can also support this through the NO_BACKSLASH_ESCAPES config option; again, PHP cannot know whether that option is in use before it makes a connection.

bobince
Very good points. +1
Ionuț G. Stan
Yes, that's exactly what I've been thinking. I enforce the connection to UTF-8, and I enforce the input to always be UTF-8, and my escaping method works with UTF-8, so, I guess I'm safe. And this is for MySQL, sorry, forgot to mention that.
rFactor