Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

php - Storing Zip file in Postgres

I've been storing the contents of zip files in a LONGBLOB in a MySQL database, but I'm moving to Postgres. From what I've read, the equivalent to LONGBLOB in Postgres is bytea. Unfortunately, I can't get the zip contents to write to the database. First, I got this error:

Warning: pg_query(): Query failed: ERROR:  invalid byte sequence for encoding "UTF8"
 0x5c

Then I created a new database with SQL_ASCII encoding (the previous had UTF8), and got this error:

PHP Warning:  pg_query(): Query failed: ERROR:  syntax error at or near "v╘▓ú5"
LINE 2: ...√╢V[úB√?┌???2└ù╙±b±≡?▼┐π}°??┌G╜?╧εo?~°0o╞W/_╝?L¢'v╘▓ú5;Ω?#╩...

Is there any way to create a database/table/column in Postgres without encoding? If not, how should I store this information? I tried using pg_escape_bytea but that produces errors when I try to unzip the contents. Not sure that this really matters, but here's the PHP I'm using to write to the database:

$content = file_get_contents($zipLocation);
$content = addslashes($content);

$sql="INSERT INTO ZIP_TBL ( BUILD, CONTENT)
    VALUES ('$build', '$content')";

if (!pg_query($con,$sql)) {
    die('Error: ' . pg_last_error($con));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One of the bytea input formats is hexadecimal. So use bin2hex

$content = file_get_contents($zipLocation);
$content = '\x' . bin2hex($content);

$sql="
    insert into zip_tbl ( build, content)
    values ('$build', E'$content')
";

http://www.postgresql.org/docs/current/static/datatype-binary.html#AEN5318

http://php.net/manual/en/function.bin2hex.php

BTW, if you are not aware, you are susceptible to SQL injection.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...