I'm new to PHP. Here is my problem. I tried using readfile to download a pdf file and it works on localhost but on the online server well it prints the file contents with strange characters. I tried other codes but the same problem persists. I researched for several days and found nothing conclusive. So please help me. Here is everything I tried:
$chemin = dirname(__FILE__,3)."/resultats_examens/".$Open;
$fileName = basename($chemin);
$filePath = $chemin;
if(!empty($fileName) && file_exists($filePath)){
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $fileName . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
// Lire le fichier
@readfile($filePath); }
I tried everything too :
//Stocker le nom du fichier dans une variable
//for any file
$file = fopen($filePath, 'rb');
if ( $file !== false ) {
fpassthru($file);
fclose($file);
}
//for any file, if fpassthru() is disabled
$file = fopen($filePath, 'rb');
if ( $file !== false ) {
while ( !feof($file) ) {
echo fread($file, 4096);
}
fclose($file);
}
//for small files;
//this should not be used for large files, as it loads whole file into memory
$data = file_get_contents($filePath);
if ( $data !== false ) {
echo $data;
}
And here is what is displayed on the screen:
%PDF-1.7
4 0 obj
(Identity)
endobj
5 0 obj
(Adobe)
endobj
8 0 obj
<<
/Filter /FlateDecode
/Length 80044
/Type /Stream
>>
stream
x�� `T��?~�[f��o&��$3��L C$�$�
CodePudding user response:
It sounds like you've got a couple of problems. Here is my recipe for sending PDF files for download. I would try adding these to your code incrementally and see what solves the problem (don't just cargo-cult the whole thing).
<?php
$filePath = '/path/to/file.pdf';
$fileTime = filemtime($filePath);
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.basename($filePath).'"');
header('Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate('D, j M Y H:i:s T', $fileTime));
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));
ob_clean();
flush();
readfile($filePath);
CodePudding user response:
It is resolved. the problem is that I had used Ajax to pass variables to the download file. now i used window.location.href to pass the variables and open the download file. it works locally and on the server