PDO
在线手册:中文  英文

PDO::quote

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

PDO::quote Quotes a string for use in a query.

说明

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

PDO::quote() places quotes around the input string (if required) and escapes special characters within the input string, using a quoting style appropriate to the underlying driver.

If you are using this function to build SQL statements, you are strongly recommended to use PDO::prepare() to prepare SQL statements with bound parameters instead of using PDO::quote() to interpolate user input into an SQL statement. Prepared statements with bound parameters are not only more portable, more convenient, immune to SQL injection, but are often much faster to execute than interpolated queries, as both the server and client side can cache a compiled form of the query.

Not all PDO drivers implement this method (notably PDO_ODBC). Consider using prepared statements instead.

Caution

Security: the default character set

The character set must be set either on the server level, or within the database connection itself (depending on the driver) for it to affect PDO::quote(). See the driver-specific documentation for more information.

参数

string

The string to be quoted.

parameter_type

Provides a data type hint for drivers that have alternate quoting styles.

返回值

Returns a quoted string that is theoretically safe to pass into an SQL statement. Returns FALSE if the driver does not support quoting in this way.

范例

Example #1 Quoting a normal string

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

/* Simple string */
$string 'Nice';
print 
"Unquoted string: $string\n";
print 
"Quoted string: " $conn->quote($string) . "\n";
?>

以上例程会输出:

Unquoted string: Nice
Quoted string: 'Nice'

Example #2 Quoting a dangerous string

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

/* Dangerous string */
$string 'Naughty \' string';
print 
"Unquoted string: $string\n";
print 
"Quoted string:" $conn->quote($string) . "\n";
?>

以上例程会输出:

Unquoted string: Naughty ' string
Quoted string: 'Naughty '' string'

Example #3 Quoting a complex string

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

/* Complex string */
$string "Co'mpl''ex \"st'\"ring";
print 
"Unquoted string: $string\n";
print 
"Quoted string: " $conn->quote($string) . "\n";
?>

以上例程会输出:

Unquoted string: Co'mpl''ex "st'"ring
Quoted string: 'Co''mpl''''ex "st''"ring'

参见


PDO
在线手册:中文  英文

用户评论:

lalithaprasad dot velamuri at verizon dot com (2013-07-02 09:27:02)

Hello,
I am unable to fetch information from "systables" from an external schema. Find below query which I am trying to execute from PHP
"SELECT * FROM {schema_name}:systables"
When we pass this query to "prepare" function then it is failing because we used column(:) in the FROM part. The reason is we can't bind values to identifiers like tables and columns. But here my intention is not to bind the table name but to refer a table in that schema.
Is there a way that I can run this query in PHP. I tried several ways but no use and also I posted it in other forums but no one is able to reply. Please provide me a solution asap.
--
Regards,
Lalith

col dot shrapnel at gmail dot com (2013-05-13 10:02:54)

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
?>

hungry dot rahly at gmail dot com (2010-09-27 09:31:08)

For those of you who do want to have null returned as NULL, it is fairly easy to add.

<?php
class Real_PDO extends PDO {
  public function 
quote($value$parameter_type PDO::PARAM_STR ) {
    if( 
is_null($value) ) {
      return 
"NULL";
    }
    return 
parent::quote($value$parameter_type);
  }
}
?>

then all you have to do is change your creation of the PDO object to this new class, and you shouldn't have to change any other function calls.  The nice thing about this method is that you can override any PDO function or add your own.  IMO, PDO should natively handle this, as there is a difference in databases between NULL and an empty string(''), the quoting of numeric values is another issue altogether.

php at deobald dot org (2008-05-20 08:33:38)

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".

易百教程