let's consider i will always do a
开发者_如何学编程SET NAMES 'utf8'
to mysql connection (so I need multibyte escapes).
Is there a safe alternative to mysql_real_escape_string that doesnt' need a mysql connection?
In the official page i found a comment that uses str_replace like this:
if(!empty($inp) && is_string($inp)) {
return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"),
array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z') , $inp);
}
is this enough?
And why mysql_real_escape_string needs the current charcaterset if it will only escape the same values? (as described in the official page php.net/mysql_real_escape_string)
thanks
first off, there are lots of database abstraction libraries out there
(i have used dbFacile before : https://github.com/alanszlosek/dbFacile).
also sql prepaired statements are ALWAYS a great idea.
but for your actual question...
from this post: Alternative to mysql_real_escape_string without connecting to DB
i really think this is a good alternative:
public function escape($string) {
$return = '';
for($i = 0; $i < strlen($string); ++$i) {
$char = $string[$i];
$ord = ord($char);
if($char !== "'" && $char !== "\"" && $char !== '\\' && $ord >= 32 && $ord <= 126)
$return .= $char;
else
$return .= '\\x' . dechex($ord);
}
return $return;
}
There is a question similar to yours:
Alternative to mysql_real_escape_string without connecting to DB
You should use mysql_real_escape_string. When you make a filter yourself you'll always have a chance a hacker makes a workaround. Mysql_real_escape_string on the other hand, is always up to date. Making a mysql connection isn't to much work if that's what you mean. Most of my sites establish a connection every pageview, and they are still working;)
精彩评论