For those who escape their single quotes with a backslash (ie \') instead of two single quotes in a row (ie '') there has recently been a SERIOUS sql injection vulnerability that can be employed taking advantage of your chosen escaping method. More info here: http://www.postgresql.org/docs/techdocs.50
Even after the postgre update, you may still be limited to what you can do with your queries if you still insist on backslash escaping. It's a lesson to always use the PHP functions to do proper escaping instead of adhoc addslashes or magic quotes escaping.
pg_escape_string
(PHP 4 >= 4.2.0, PHP 5)
pg_escape_string — クエリに使う文字列をエスケープする
説明
string pg_escape_string
([ resource
$connection
], string $data
)pg_escape_string() は、データベースへの問い合わせに使う文字列をエスケープします。 PostgreSQL フォーマットにエスケープされた文字列を、クォートなしの形式で返します。 PostgreSQL に使う SQL パラメータをエスケープするときには pg_escape_literal() を使うほうがよいでしょう。 addslashes() を PostgreSQL で使ってはいけません。 カラム型が bytea の場合は、代わりに pg_escape_bytea() を使わなければなりません。 識別子 (テーブル名やフィールド名など) のエスケープには pg_escape_identifier() を使わなければなりません。
注意:
この関数は、PostgreSQL 7.2 以降が必要です。
パラメータ
-
connection -
PostgreSQL データベース接続リソース。
connectionが存在しない場合は、 デフォルトの接続を使用します。デフォルトの接続は、 pg_connect() あるいは pg_pconnect() で直近に作成されたものとなります。 -
data -
エスケープするテキスト文字列。
返り値
エスケープされたデータを文字列で返します。
変更履歴
| バージョン | 説明 |
|---|---|
| 5.2.0 | connection が追加されました。 |
例
例1 pg_escape_string() の例
<?php
// データベースに接続する
$dbconn = pg_connect('dbname=foo');
// テキストファイルを読み込む(アポストロフィやスラッシュが含まれている)
$data = file_get_contents('letter.txt');
// テキストデータをエスケープする
$escaped = pg_escape_string($data);
// それをデータベースに挿入する
pg_query("INSERT INTO correspondence (name, data) VALUES ('My letter', '{$escaped}')");
?>
johniskew2 at yahoo dot com ¶
6 years ago
strata_ranger at hotmail dot com ¶
2 years ago
Forthose curious, the exact escaping performed on the string may vary slightly depending on your database configuration.
For example, if your database's standard_conforming_strings variable is OFF, backslashes are treated as a special character and pg_escape_string() will ensure they are properly escaped. If this variable is ON, backslashes will be treated as ordinary characters, and pg_escape_string() will leave them as-is. In either case, the behavior matches the configuration of the database connection.
Nathan Bruer ¶
5 years ago
If your database is a UTF-8 database, you will run into problems trying to add some data into your database...
for securty issues and/or compatability you may need to use the: utf_encode() (http://php.net/utf8-encode) function.
for example:
<?php
$my_data = pg_escape_string(utf8_encode($_POST['my_data']));
?>
strata_ranger at hotmail dot com ¶
1 year ago
This may seem obvious, but remember that pg_escape_string escapes values for use as string literals in an SQL query -- if you need to escape arbitrary strings for use as SQL identifiers (column names, etc.), there doesn't seem to be a PHP function for that so you'll have to do that escaping yourself. (PostgreSQL has an in-database function, quote_ident(), that does this.)
This can be an issue if your database contains mixed-case (or otherwise unusual) column names and you have a class interface managing your database/query interactions (for connecting to different types of databases). If you don't double-quote your column names then postgreSQL will match them case-insensitively, but will label the results in all-lowercase (which differs from MySQL).
For example:
<?php
// Plain column identifier
$res = pg_query("Select columnName from table");
$row = pg_fetch_assoc($res);
var_dump($row['columnName']); // Doesn't work (throws E_NOTICE)
var_dump($row['columnname']); // Works
// Escaped column identifier
$res = pg_query("Select \"columnName\" from table");
$row = pg_fetch_assoc($res);
var_dump($row['columnName']); // Works
var_dump($row['columnname']); // Doesn't
?>
ppp ¶
1 year ago
pg_escape_string() won't cast array arguments to the "Array" string like php usually does; it returns NULL instead. The following statements all evaluate to true:
<?php
$a = array('foo', 'bar');
"$a" == 'Array';
(string)$a == 'Array';
$a . '' == 'Array';
is_null(pg_escape_string($a));
?>
Gautam Khanna ¶
5 years ago
Security methods which you use depend on the specific purpose. For those who dont know, take a look at the following built-in PHP functions:
strip_tags() to remove HTML characters
(also see htmlspecialchars)
escapeshellarg() to escape shell commands etc
escapeshellcmd()
mysql_real_escape_string() to escape mySQL commands.
Enjoy!
web dot expert dot panel at gmail dot com
meng ¶
6 years ago
Since php 5.1 the new function pg_query_params() was introduced. With this function you can use bind variables and don't have to escape strings. If you can use it, do so. If unsure why, check the changelog for Postgres 8.0.8.
otix ¶
7 years ago
Creating a double-tick is just fine. It works the same as the backslash-tick syntax. From the PostgreSQL docs:
The fact that string constants are bound by single quotes presents an obvious semantic problem, however, in that if the sequence itself contains a single quote, the literal bounds of the constant are made ambiguous. To escape (make literal) a single quote within the string, you may type two adjacent single quotes. The parser will interpret the two adjacent single quotes within the string constant as a single, literal single quote. PostgreSQL will also allow single quotes to be embedded by using a C-style backslash.
rich at dicksonlife dot com ¶
7 years ago
Here's some code I knocked up to turn an array of values into a string representation of an array. Note that I also add the external single quotes to make it a full string literal.
//$t is array to be escaped. $u will be string literal.
$tv=array();
foreach($t as $key=>$val){
$tv[$key]="\"" .
str_replace("\"",'\\"', str_replace('\\','\\\\',$val)) . "\"
";
}
$u= implode(",",$tv) ;
$u="'{" . pg_escape_string($u) . "}'";
There's probably a better way of doing this. That's why I'm posting this here :)
tsharek at o2 dot pl ¶
8 years ago
IMO the stripslashes in this case is not very usefull. Because pg_escape_string change ' into '' (double ' - not "). I use in add to database this:
pg_escape_string(stripslashes($_GET['var'])) and is in 100% safe (i hope).
If I use addslashes in this case that well be lost space in database (\''' - this is 3 bytes)
ps. sorry for my english:)
Anonymous ¶
9 years ago
Here with 'abc'efg' the middle ' terminates the string, however 'abc\'def' is one big string with a ' character in the middle.
If the user can terminate the string he can then put in the bad sql. When prompted for Barcode the user could put in DROP TABLE foo; SELECT '1
$query = sprintf ("SELECT * FROM a.tblcards WHERE barcode='%s'", pg_escape_string($barcode));
So you have to "clean" your variable coming in to prevent that.
