PDO::quote

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.1)

PDO::quote Заключает строку в кавычки для использования в запросе

Описание

string PDO::quote ( string $string [, int $parameter_type = PDO::PARAM_STR ] )

PDO::quote() заключает строку в кавычки (если требуется) и экранирует специальные символы внутри строки подходящим для драйвера способом.

Если вы используете эту функцию для построения SQL запросов, настоятельно рекомендуется пользоваться методом PDO::prepare() для подготовки запроса с псевдопеременными вместо использования PDO::quote() для вставки данных введенных пользователем в SQL запрос. Подготавливаемые запросы с параметрами не только компактней, удобней, устойчивей к SQL иньекциям, но и работают быстрее, нежели вручную построенные запросы, так как и клиент и сервер могут кэшировать такие запросы в уже скомпилированном виде.

Не все PDO драйверы реализуют этот метод (особенно PDO_ODBC). Предполагается, что вместо него будут использоваться подготавливаемые запросы.

Предостережение

Безопасность: набор символов по умолчанию

Для корректной работы PDO::quote() набор символов должен быть задан либо на сервере, либо задаваться самим соединением с базой данных (это зависит от драйвера). Подробнее см. документацию к драйверу базы данных.

Список параметров

string

Экранируемая строка.

parameter_type

Представляет подсказку о типе данных первого параметра для драйверов, которые имеют альтернативные способы экранирования.

Возвращаемые значения

Возвращает экранированную строку, которую теоретически безопасно использовать в теле SQL запроса. Возвращает FALSE, если драйвер не поддерживает экранирование.

Примеры

Пример #1 Экранирование обычной строки

<?php
$conn 
= new PDO('sqlite:/home/lynn/music.sql3');

/* простая строка */
$string 'Nice';
print 
"Неэкранированная строка: $string\n";
print 
"Экранированная строка: " $conn->quote($string) . "\n";
?>

Результат выполнения данного примера:

Неэкранированная строка: Nice
Экранированная строка: 'Nice'

Пример #2 Экранирование небезопасной строки

<?php
$conn 
= new PDO('sqlite:/home/lynn/music.sql3');

/* небезопасная строка */
$string 'Naughty \' string';
print 
"Неэкранированная строка: $string\n";
print 
"Экранированная строка:" $conn->quote($string) . "\n";
?>

Результат выполнения данного примера:

Неэкранированная строка: Naughty ' string
Экранированная строка: 'Naughty '' string'

Пример #3 Экранирование сложной строки

<?php
$conn 
= new PDO('sqlite:/home/lynn/music.sql3');

/* сложная строка */
$string "Co'mpl''ex \"st'\"ring";
print 
"Неэкранированная строка: $string\n";
print 
"Экранированная строка: " $conn->quote($string) . "\n";
?>

Результат выполнения данного примера:

Неэкранированная строка: Co'mpl''ex "st'"ring
Экранированная строка: 'Co''mpl''''ex "st''"ring'

Смотрите также

  • PDO::prepare() - Подготавливает запрос к выполнению и возвращает ассоциированный с этим запросом объект
  • PDOStatement::execute() - Запускает подготовленный запрос на выполнение

Коментарии

Note that this function just does what the documentation says: It escapes special characters in strings. 

It does NOT - however - detect a "NULL" value. If the value you try to quote is "NULL" it will return the same value as when you process an empty string (-> ''), not the text "NULL".
2008-05-20 11:33:38
http://php5.kiev.ua/manual/ru/pdo.quote.html
One have to understand that string formatting has nothing to do with identifiers.
And thus string formatting should NEVER ever be used to format an identifier ( table of field name).
To quote an identifier, you have to format it as identifier, not as string.
To do so you have to

- Enclose identifier in backticks.
- Escape backticks inside by doubling them.

So, the code would be:
<?php
function quoteIdent($field) {
    return 
"`".str_replace("`","``",$field)."`";
}
?>
this will make your identifier properly formatted and thus invulnerable to injection. 

However, there is another possible attack vector - using dynamical identifiers in the query may give an outsider control over fields the aren't allowed to:
Say, a field user_role in the users table and a dynamically built INSERT query based on a $_POST array may allow a privilege escalation with easily forged $_POST array. 
Or a select query which let a user to choose fields to display may reveal some sensitive information to attacker.

To prevent this kind of attack yet keep queries dynamic, one ought to use WHITELISTING approach.

Every dynamical identifier have to be checked against a hardcoded whitelist like this:
<?php
$allowed 
= array("name","price","qty");
$key array_search($_GET['field'], $allowed));
if (
$key == false) {
    throw new 
Exception('Wrong field name');
}
$field $db->quoteIdent($allowed[$key]);
$query "SELECT $field FROM t"//value is safe
?>
(Personally I wouldn't use a query like this, but that's just an example of using a dynamical identifier in the query).

And similar approach have to be used when filtering dynamical arrays for insert and update:

<?php
function filterArray($input,$allowed)
{
    foreach(
array_keys($input) as $key )
    {
        if ( !
in_array($key,$allowed) )
        {
             unset(
$input[$key]);
        }
    }
    return 
$input;
}
//used like this
$allowed = array('title','url','body','rating','term','type');
$data $db->filterArray($_POST,$allowed); 
// $data now contains allowed fields only 
// and can be used to create INSERT or UPDATE query dynamically
?>
2013-05-13 13:02:54
http://php5.kiev.ua/manual/ru/pdo.quote.html
Автор:
When converting from the old mysql_ functions to PDO, note that the quote function isn't exactly the same as the old mysql_real_escape_string function. It escapes, but also adds quotes; hence the name I guess :-)

After I replaced mysql_real_escape_string with $pdo->quote, it took me a bit to figure out why my strings were turning up in results with quotes around them. I felt like a fool when I realized all I needed to do was change ...\"".$pdo->quote($foo)."\"... to ...".$pdo->quote($foo)."...
2013-09-28 15:40:14
http://php5.kiev.ua/manual/ru/pdo.quote.html
This function also converts new lines to \r\n
2014-01-27 16:17:14
http://php5.kiev.ua/manual/ru/pdo.quote.html
In foundation quoting is bad idea,there always will be possibillity to escape or fraud quote function ,better solution,i mean best solution is using this function : htmlentities($string, ENT_QUOTES, 'UTF-8') which translate quote into &#39; and $string translated like this can't affect on your code.
2015-04-15 19:11:28
http://php5.kiev.ua/manual/ru/pdo.quote.html
PDO quote (tested with mysql and mariadb 10.3) is extremely slow.

It took me hours of debugging my performance issues until I found that pdo->quote is the problem.

This function is far from fast, and it's PHP instead of C code:
function escape($value)
    {
        $search = array("\\",  "\x00", "\n",  "\r",  "'",  '"', "\x1a");
        $replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");

        return str_replace($search, $replace, $value);
    }

It is 50 times faster than pdo->quote()
(note, it's without quotes just escaping and only used here as an example)
2018-07-21 20:10:32
http://php5.kiev.ua/manual/ru/pdo.quote.html

    Поддержать сайт на родительском проекте КГБ