Just a little function which mimics the original mysql_real_escape_string but which doesn't need an active mysql connection. Could be implemented as a static function in a database class. Hope it helps someone.
<?php
function mysql_escape_mimic($inp) {
if(is_array($inp))
return array_map(__METHOD__, $inp);
if(!empty($inp) && is_string($inp)) {
return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp);
}
return $inp;
}
?>mysql_real_escape_string
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
mysql_real_escape_string
Референца за `function.mysql-real-escape-string.php` со подобрена типографија и навигација.
mysql_real_escape_string
(PHP 4 >= 4.3.0, PHP 5)
mysql_real_escape_string — (PHP 4 >= 4.3.0, PHP 5)
Предупредување MySQLi or PDO_MySQL Овој екстензија беше депрецирана во PHP 5.5.0, и беше отстранета во PHP 7.0.0. Наместо тоа, екстензијата треба да се користи. Видете исто така MySQL: избирање на API водич. Алтернативи на оваа функција вклучуваат: PDO::quote()
= NULL
$unescaped_string, resource $link_identifier Ги ескејпува специјалните знаци во): string
, земајќи го предвид тековниот сет на знаци на конекцијата за да биде безбедно да се стави во unescaped_string. Ако треба да се внесат бинарни податоци, оваа функција мора да се користи. mysql_query()ги повикува библиотечната функција на MySQL mysql_real_escape_string, која додава коси црти пред следните знаци:
mysql_real_escape_string() Оваа функција мора секогаш (со малку исклучоци) да се користи за да се направат податоците безбедни пред испраќање на прашање до MySQL.
\x00, \n,
\r, \, ',
" and \x1a.
Внимание
Сет на знаци мора да се постави или на серверско ниво, или со API функцијата
за да влијае на mysql_set_charset() . Видете го делот за концепти на mysql_real_escape_string(). Погледнете го делот за концепти на скупови знаци Користење на PHP од командната линија
Параметри
unescaped_string- Низата што треба да се избегне.
-
link_identifier MySQL конекцијата. Ако идентификаторот на врската не е специфициран, последната отворена врска од mysql_connect() се претпоставува. Ако не се најде таква врска, ќе се обиде да создаде една како да mysql_connect() била повикана без аргументи. Ако не се најде или воспостави конекција,
E_WARNINGсе генерира грешка од ниво.
Вратени вредности
Враќа избегната низа, или false при грешка.
Errors/Exceptions
Извршувањето на оваа функција без присутен MySQL конекција исто така ќе емитува E_WARNING PHP грешки од ниво. Извршувајте ја оваа функција само со присутен валиден MySQL конекција.
Примери
Пример #1 Едноставен mysql_real_escape_string() example
<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
OR die(mysql_error());
// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
?>Пример #2 mysql_real_escape_string() пример што бара конекција
Овој пример покажува што се случува ако MySQL конекцијата не е присутна при повикување на оваа функција.
<?php
// We have not connected to MySQL
$lastname = "O'Reilly";
$_lastname = mysql_real_escape_string($lastname);
$query = "SELECT * FROM actors WHERE last_name = '$_lastname'";
var_dump($_lastname);
var_dump($query);
?>Горниот пример ќе прикаже нешто слично на:
Warning: mysql_real_escape_string(): No such file or directory in /this/test/script.php on line 5 Warning: mysql_real_escape_string(): A link to the server could not be established in /this/test/script.php on line 5 bool(false) string(41) "SELECT * FROM actors WHERE last_name = ''"
Пример #3 Пример за SQL напад за инјектирање
<?php
// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);
// This means the query sent to MySQL would be:
echo $query;
?>Запитот испратен до MySQL:
SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''
Ова би му дозволило на секого да се најави без валидна лозинка.
Белешки
Забелешка: MySQL конекција е потребна пред да се користи mysql_real_escape_string() инаку се генерира грешка од ниво
E_WARNINGи се враќа.falseсе враќа. Акоlink_identifierне е дефинирано, се користи последната MySQL конекција.
Забелешка: Ако оваа функција не се користи за бегство од податоци, прашањето е ранливо на SQL Инјекциски Напади.
Забелешка: mysql_real_escape_string() не бега од
%and_. Овие се џокери во MySQL ако се комбинираат соLIKE,GRANT, илиREVOKE.
Види Исто така
- mysql_set_charset() - Поставува сет на знаци на клиентот
- mysql_client_encoding() - Враќа име на сет на знаци
Белешки од корисници 4 белешки
For further information:
http://dev.mysql.com/doc/refman/5.5/en/mysql-real-escape-string.html
(replace your MySQL version in the URL)Note that mysql_real_escape_string doesn't prepend backslashes to \x00, \n, \r, and and \x1a as mentionned in the documentation, but actually replaces the character with a MySQL acceptable representation for queries (e.g. \n is replaced with the '\n' litteral). (\, ', and " are escaped as documented) This doesn't change how you should use this function, but I think it's good to know.No discussion of escaping is complete without telling everyone that you should basically never use external input to generate interpreted code. This goes for SQL statements, or anything you would call any sort of "eval" function on.
So, instead of using this terribly broken function, use parametric prepared statements instead.
Honestly, using user provided data to compose SQL statements should be considered professional negligence and you should be held accountable by your employer or client for not using parametric prepared statements.
What does that mean?
It means instead of building a SQL statement like this:
"INSERT INTO X (A) VALUES(".$_POST["a"].")"
You should use mysqli's prepare() function (http://php.net/manual/en/mysqli.prepare.php) to execute a statement that looks like this:
"INSERT INTO X (A) VALUES(?)"
NB: This doesn't mean you should never generate dynamic SQL statements. What it means is that you should never use user-provided data to generate those statements. Any user-provided data should be passed through as parameters to the statement after it has been prepared.
So, for example, if you are building up a little framework and want to do an insert to a table based on the request URI, it's in your best interest to not take the $_SERVER['REQUEST_URI'] value (or any part of it) and directly concatenate that with your query. Instead, you should parse out the portion of the $_SERVER['REQUEST_URI'] value that you want, and map that through some kind of function or associative array to a non-user provided value. If the mapping produces no value, you know that something is wrong with the user provided data.
Failing to follow this has been the cause of a number of SQL-injection problems in the Ruby On Rails framework, even though it uses parametric prepared statements. This is how GitHub was hacked at one point. So, no language is immune to this problem. That's why this is a general best practice and not something specific to PHP and why you should REALLY adopt it.
Also, you should still do some kind of validation of the data provided by users, even when using parametric prepared statements. This is because that user-provided data will often become part of some generated HTML, and you want to ensure that the user provided data isn't going to cause security problems in the browser.