PHP Velho Oeste 2024

PDO::quote

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

PDO::quote Protège une chaîne pour l'utiliser dans une requête SQL PDO

Description

public PDO::quote(string $string, int $type = PDO::PARAM_STR): string|false

PDO::quote() place des guillemets simples autour d'une chaîne d'entrée, si nécessaire et protège les caractères spéciaux présents dans la chaîne d'entrée, en utilisant le style de protection approprié au pilote courant.

Si vous utilisez cette fonction pour construire des requêtes SQL, vous êtes vivement invités à utiliser PDO::prepare() pour préparer les requêtes SQL avec des paramètres liés au lieu d'utiliser PDO::quote() pour interpréter les entrées utilisateur dans la requête SQL. Les requêtes préparées avec des paramètres liés sont non seulement plus portables, plus souples et plus sécuritaires, mais bien plus rapides à exécuter que d'interpréter les requêtes, étant donné que les côtés client et serveur peuvent mettre en cache une version compilée de la requête.

Tous les pilotes PDO n'implémentent pas cette méthode (comme PDO_ODBC). Utilisez les requêtes préparées à la place.

Attention

Securité : le jeu de caractères par défaut

Le jeu de caractères doit être défini soit au niveau du serveur, soit lors de la connexion à la base de données (suivant le driver utilisé) pour qu'il affecte la méthode PDO::quote(). Voir la documentation spécifique au driver pour plus d'informations.

Liste de paramètres

string

La chaîne à protéger.

type

Le type de données pour les drivers qui ont des styles particuliers de protection. Fournit un indice au type de donnée pour les pilotes qui ont un style d'échappement différent. Par exemple PDO_PARAM_LOB indique au pilote d'échapper des données binaires.

Valeurs de retour

Retourne une chaîne protégée, qui est théoriquement sûre à utiliser dans une requête SQL. Retourne false si le pilote ne supporte pas ce type de protections.

Exemples

Exemple #1 Protection d'une chaîne normale

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

/* Chaîne simple */
$string = 'Nice';
print
"Chaîne non échappée : $string\n";
print
"Chaîne échappée : " . $conn->quote($string) . "\n";
?>

L'exemple ci-dessus va afficher :

Chaîne non échappée : Nice
Chaîne échappée: 'Nice'

Exemple #2 Protection d'une chaîne dangereuse

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

/* Chaîne dangereuse */
$string = 'Chaîne \' particulière';
print
"Chaîne non échappée : $string\n";
print
"Chaîne échappée :" . $conn->quote($string) . "\n";
?>

L'exemple ci-dessus va afficher :

Chaîne non échappée : Chaîne ' particulière
Chaîne échappée : 'Chaîne '' particulière'

Exemple #3 Protection d'une chaîne complexe

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

/* Chaîne complexe */
$string = "Co'mpl''exe \"ch'\"aîne";
print
"Chaîne non échappée : $string\n";
print
"Chaîne échappée : " . $conn->quote($string) . "\n";
?>

L'exemple ci-dessus va afficher :

Chaîne non échappée: Co'mpl''exe "ch'"aîne
Chaîne échappée: 'Co''mpl''''exe "ch''"aîne'

Voir aussi

add a note add a note

User Contributed Notes 6 notes

up
49
mirv
10 years ago
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)."...
up
7
nolife at gmail dot com
5 years ago
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)
up
23
col dot shrapnel at gmail dot com
10 years ago
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
?>
up
8
milosdj at gmail dot com
10 years ago
This function also converts new lines to \r\n
up
9
php at deobald dot org
15 years ago
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".
up
-55
aleksdimitrievski7 at gmail dot com
9 years ago
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.
To Top