1

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! :-(

4
  • Sidenote: Missing quotes around [submit] Commented Oct 3, 2014 at 15:10
  • Base yourself on this Q&A on Stack => stackoverflow.com/q/14418725 Commented Oct 3, 2014 at 15:15
  • Are you trying to store the file in the database (i.e. in a BLOB), or a reference to the file (as in a filepath or URL)? Has a big effect on the answer. Commented Oct 3, 2014 at 15:17
  • No I want store it in the database. Commented Oct 3, 2014 at 15:28

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.