Michele M
Michele M

Reputation: 147

Upload/Download file in POSTGRESQL database with PHP

I want to create a php page where a user can upload a pdf file and store it in a Postgresql database. On another page the user may download or read the pdf file.

At the moment I have found this:

POSTGRESQL:

CREATE TABLE schema.tab
(
  id serial NOT NULL,
  a bytea,
  CONSTRAINT tab_pkey PRIMARY KEY (id)
)

PHP UPLOAD:

if ($_POST[submit]=="submit"){

    include_once('../function.php');
    ini_set('display_errors','Off');
    $db=connection_pgsql() or die('Connessione al DBMS non riuscita');

    $data = file_get_contents($_FILES['form_data']['tmp_name']);
    $escaped = pg_escape_bytea($data);
    $result = pg_prepare( "ins_pic",'INSERT INTO schema.tab (a) VALUES ($1)'); 
    $result = pg_execute ("ins_pic",array('$escaped')); 

Now how I can download the pdf stored in tab with id=1?

I have tried:

$sql= "SELECT a FROM schema.tab WHERE id=5";


$resource=pg_query($db, $sql);
$row=pg_fetch_array($resource, NULL, PGSQL_BOTH);


$data = pg_unescape_bytea($row[0]);

$extension ='pdf';
$fileId = 'title';

$filename = $fileId . '.' . $extension;

$fileHandle = fopen($filename, 'w');
fwrite($fileHandle, $data);
fclose($fileHandle);


// We'll be outputting a PDF
header('Content-type: application/pdf');


// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
echo $fileHandle;
exit;

But it doesn't work! :-(

Upvotes: 1

Views: 11063

Answers (1)

Simon Paquet
Simon Paquet

Reputation: 625

You have to use headers in a php file. The output buffer has to be empty. $filecontent reprensent the pdf content from the database.

// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
echo $filecontent;
exit;

This code will make sure that your user will download the pdf file

Upvotes: 1

Related Questions