Display pdf from database using php

19.3k Views Asked by At

There is a pdf file stored in my database as a [BLOB - 143.3 KiB]. It's got a userid of 12. I am trying to call it to the page so that when I click on a button, the pdf populates the webpage.

if (isset($_POST["work"]) && !empty($_POST["work"])) 
 {
   $result = mysql_query("SELECT file FROM ce WHERE userid=12", $c) or die("six");
   $document1=mysql_result($result, 0, 'file'); 
   echo $document1;
 }

 echo '
       <form action="yourcase.php" method="post">
          <input type="hidden" name="work" value="1">
          <input type="image" id="work" src="images/papers.png">
       </form>'; 

Currently, it echos out a page of this: ‰ŒA Â@E÷9Å_ê&&Ói[Ž€°£ ZqŠôúÆŽ@ïåÿ&ŠÆÑ,¢Y[«*ÆX%Ó@/RˆOÝçÇ¡.

Using another post, I was able to call a pdf file from my desktop, but I can't figure out how to do it from the database.

$file = 'sample.pdf';
$filename = 'sample.pdf'; 
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
@readfile($file); 

Thanks to @Fred, I was able to piece together a working solution. This does what I've been trying to do:

if (isset($_POST["work"]) && !empty($_POST["work"])) 
 { 
   $result = mysql_query("SELECT file FROM ce WHERE userid=12", $c) or die("six");
   $document1=mysql_result($result, 0, 'file'); 
   header('Content-type: application/pdf');
   echo $document1;
 }

 echo '
        <form action="fetchdoc.php" method="post">
           <input type="hidden" name="work" value="1">    
           <input type="image" id="work" src="images/papers.png">
        </form>'; 
3

There are 3 best solutions below

1
On

Your going to have to create the pdf file and then use header to read that file. If you don't plan on keep the files, you can load them to a temp directory and then delete them when your done. If you echo the blob data from your database, its like opening a .pdf file with notepad.

0
On
0
On

Thanks to @Fred, I was able to piece together a working solution. This does what I've been trying to do:

if (isset($_POST["work"]) && !empty($_POST["work"])) { 
$result = mysql_query("SELECT file FROM ce WHERE userid=12", $c) or die("six");
$document1=mysql_result($result, 0, 'file'); 
header('Content-type: application/pdf');
echo $document1;}
echo '<form action="fetchdoc.php" method="post"><input type="hidden" name="work" value="1">    
<input type="image" id="work" src="images/papers.png"></form>';