Skip to content
Advertisement

How do I download a pdf blob file from database?

I’m trying to download a pdf file from the database stored as a blob datatype using the code blow, right now I’m only able to view the file as .php and not .pdf.

    if(isset($_POST['submit'])){
        $docno = $_POST['docno'];
        $admno = $_POST['admno'];
        $sql = "SELECT * FROM bonafide_cert WHERE DocumentNumber=:docno AND AdmssnNo=:admno";
        $query = $dbh->prepare($sql);
        $query->bindParam(':admno',$admno,PDO::PARAM_STR);
        $query->bindParam(':docno',$docno,PDO::PARAM_STR);
        $query->execute();  
        $results=$query->fetchAll(PDO::FETCH_OBJ);
        if($query->rowCount() > 0)
        {
            foreach($results as $result)
            {
                 header('Content-Type:'.$result->mime);
                 echo $result->pdf_file;
            }
        }
    }

The $result->mime contains the data-type of the file as application/pdf. The $result->pdf_file contains the PDF file itself as BLOB.

On execution of the php code, I am able to see my pdf file but the file is in .php extension, the browser is displaying the file in it’s PDF Viewer but still when I try to download it tries to save the file as .php. How do I make the file download as .pdf – right now I have to manually save as PDF each time.

Advertisement

Answer

Try adding this header line of code between your header and echo statement :

header('Content-Type:'.$result->mime);
header("Content-Disposition: inline; filename=filename.pdf");
echo $result->pdf_file;

You can set Content-Disposition: to attachment if you want it to download the file instead.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement