Falci
Falci

Reputation: 1873

Store/Read file in Postgres-DB

I'm trying to save a file in the database and I'm having trouble retrieving it. The result is not a valid file.

Isolating part of the code, I think this should work:

$content = pg_escape_bytea (file_get_contents($tmp)); //image.jpg   
header('Content-type: ' . $mime); // image/jpg
echo pg_unescape_bytea($content); exit;

$content is stored, but I can't read it again!

What to do?

Upvotes: 1

Views: 1551

Answers (1)

Daniel Vérité
Daniel Vérité

Reputation: 61606

A possible explanation would be that you're in this configuration:

  • the PHP side uses a 8.4 or older libpq library
  • Server is 9.0 or newer
  • the bytea_output config parameter is left to its default value (hex)

In this case, pg_unescape_bytea will not properly decode the bytea contents coming in text format from the database. As a workaround, you may add to the php code:

pg_query("SET bytea_output=escape");

before SELECTing the bytea contents and see if that makes a difference. If it does solve the problem you may make it a persistent setting for the database by issuing:

ALTER DATABASE mydb SET bytea_output=escape;

until upgrading libpq to a newer version.

Upvotes: 1

Related Questions