1

I am working in a project where I store files in Mysql database.

I stored the files as long blob in my database and I want to make them readable in my site web based on PHP. I tried to view PDF files and it works but if I try to download Excel File, it gives me file.php and some numbers.

//PHP

$dbh= new PDO("mysql:host=localhost;dbname=smi","root","");
$id=isset($_GET['id_fichier'])? $_GET['id_fichier']:"";
$stat=$dbh->prepare("select * from fichier where id_fichier=?");
$stat->bindparam(1,$id);
$stat->execute();
$row=$stat->fetch();
$file = $row['fichier'];
$type=$row['type'];
header('Content-Type:'.$type);
echo($file);

I expect the excel file but I get something like this.

3c21 444f 4354 5950 4520 6874 6d6c 3e0d
0a3c 6874 6d6c 2064 6972 3d22 6c74 7222
206c 616e 673d 2265 6e22 3e0d 0a3c 6865
6164 3e0d 0a3c 7469 746c 653e 534d 4920
4165 726f 706f 7274 2046 6573 2053 6169
7373 3c2f 7469 746c 653e 0d0a 0d0a 3c2f
Masoud Rahimi
  • 5,785
  • 15
  • 39
  • 67
Saad
  • 23
  • 7
  • What is your encoding? Could you try to add charset to your DSN and see if it helps? – Dharman Jun 11 '19 at 22:14
  • you missing a numbe r of headers https://stackoverflow.com/questions/7263923/how-to-force-file-download-with-php –  Jun 11 '19 at 22:26
  • @tim I add the missing headers the file download but not open because form or extension are not valid – Saad Jun 11 '19 at 22:36
  • what does " form or extension are not valid " mean? –  Jun 11 '19 at 22:41
  • @tim when I tried to open the excel file it gives me that like the file is damaged – Saad Jun 11 '19 at 23:07

1 Answers1

-1

Make sure you have added it correctly into your database and that the type of the column fichier is set to BLOB and not anything else.

Here's a clean code to insert it into your database:

$dbh = new PDO('mysql:host=localhost;dbname=smi', 'root', '');

$file = 'XYZ.xls';
$blob = fopen($file, 'rb');
$mime = 'application/vnd.ms-excel';

$sql  = "INSERT INTO `fichier` (fichier, type) VALUES (:fichier, :type)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':fichier', $blob, PDO::PARAM_LOB);
$stmt->bindParam(':type', $mime);
$stmt->execute();

And then select it back:

if(isset($_GET['id_fichier'])){
   $id   = $_GET['id_fichier'];  
   $stmt = $dbh->prepare("SELECT * from `fichier` where `id_fichier` = :id");
   $stmt->bindColumn(':id', $id);
   $stmt->execute();

   $data = $stat->fetch();
   $file = $data['fichier'];
   $type = $data['type'];
   header('Content-Type:'.$type);
   echo($file);
}
RyadPasha
  • 333
  • 3
  • 9
  • Thanks for your answer but I dont have any problem with PDF file, I have problem with Microsoft file. – Saad Jun 11 '19 at 22:48
  • Yes, it's an excel file, whatever the file type is .. these steps should be followed for any type of file – RyadPasha Jun 11 '19 at 22:53