0

I have a dataform form where I upload pdf files into a blob type field, my problem is when i want to display it it always gives me the message: Failed to load PDF document. is follow my code:

     $code = mysqli_real_escape_string($conn , $_GET['doc']); 
 $q = mysqli_query($conn, ' SELECT document FROM saisie WHERE code = "'.$doc.'" ');  
 $r= mysqli_fetch_assoc($q);  
 $doc=$r['document'];

 header('Content-Type: application/pdf') ; 
 header('Content-Disposition: inline; filename="test.pdf"') ;
 header('Content-Transfer-Encoding: binary');
 header('Accept-Ranges: bytes');
 @readfile($doc) ;

1 Answers1

1

Here is a simple script which works fine for me:

<?php

$db = new PDO("mysql:host=localhost;dbname=test", "test","");

// Read the file and store as blob into DB
$filename = 'doc.pdf';
$fileContents = file_get_contents($filename);

$stmt = $db->prepare("insert into pdf_blob(filename, data) values (?, ?)");
$stmt->execute([$filename, $fileContents]);


// Read blob data from DB and output in browser
$stmt = $db->prepare("select filename, data from pdf_blob where filename = ? limit 1");
$stmt->execute([$filename]);
$result = $stmt->fetch();

header('Content-Type: application/pdf') ;
header('Content-Disposition: inline; filename="test.pdf"') ;
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');

echo $result['data'];

I read a PDF file from the file system with file_get_contents() and store the content into a MySQL BLOB column. After that I read the same data from the DB and simply use echo for the output. The header declaration is exactly the same as in your code.

Though I use PDO here instead of mysqli, it should probably not matter.

Here is my table definition:

CREATE TABLE `pdf_blob` (
    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `filename` VARCHAR(50) NOT NULL,
    `data` BLOB NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB;
Paul Spiegel
  • 30,925
  • 5
  • 44
  • 53