PHP Conference Nagoya 2025

pg_unescape_bytea

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_unescape_bytea 反转义 bytea 类型的二进制数据

说明

pg_unescape_bytea(string $string): string

pg_unescape_bytea() 反转义 PostgreSQL bytea 数据值。返回反转义后的字符串,可能包含二进制数据。

注意:

SELECT bytea 类型时,PostgreSQL 返回前缀为“\”的八进制字节值(例如 \032)。用户需要手动将其转换回二进制格式。

本函数需要 PostgreSQL 7.2 及其以后的版本。在 PostgreSQL 7.2.0 和 7.2.1 中,当启用了多字节支持时 bytea 值必需进行类型转换,例如 INSERT INTO test_table (image) VALUES ('$image_escaped'::bytea); ;PostgreSQL 7.2.2 及其以后的版本不需要类型转换。唯一的例外是当客户端和后端的字符编码不匹配时,有可能出现多字节流错误。用户必须将其转换为 bytea 来避免此错误。

参数

string

string,包含 PostgreSQL bytea 数据,需要转换为 PHP 二进制字符串。

返回值

包含反转义数据的 string

示例

示例 #1 pg_unescape_bytea() 示例

<?php
// Connect to the database
$dbconn = pg_connect('dbname=foo');

// Get the bytea data
$res = pg_query("SELECT data FROM gallery WHERE name='Pine trees'");
$raw = pg_fetch_result($res, 'data');

// Convert to binary and send to the browser
header('Content-type: image/jpeg');
echo
pg_unescape_bytea($raw);
?>

参见

添加备注

用户贡献的备注 2 notes

up
5
liviu dot mirea at gmail dot com
14 years ago
PostgreSQL 9.0 introduced "hex" as the new default format for encoding binary data. Because "pg_unescape_bytea" only works with the old "escape" format, you need to do pg_query('SET bytea_output = "escape";'); before executing your select queries.

More details can be found here: http://www.postgresql.org/docs/9.0/static/datatype-binary.html

[Ed: Recent PostgreSQL versions support unescaping the "hex" format.]
up
0
muralito at montevideo dot com dot uy
13 years ago
The workaround is to configure a property in the postgres database for the user, to make postgres behave as the old default.

ALTER USER username SET bytea_output = 'escape';

(or using the pgadmin interface)
To Top