PHP Header download PDF - php

I've made a page where you can go and write text in a "textarea" and then when you click download you download that file as a .txt file. I've done the same thing to some other extensions and that is working fine. But it won't work with .PDF, nothing I read works. Here is the snippet I use for the .PDF downloading:
<?php
if($fileFormat == ".pdf"){
$content = $_POST['text'];
$name = stripslashes($_POST['name']);
$nameAndExt = $name.".pdf";
print strip_tags($content);
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="'.$nameAndExt.'"');
header('Content-Transfer-Encoding: binary ');
}
?>
I'm grateful for any answear, thanks!

// hold the filename for use elsewhere so you don't have to append .pdf every time
$filename = "$id.pdf";
// create the file
$pdf->output( $filename );
// set up the headers
header("Content-Description: File Transfer");
header("Content-disposition: attachment; filename={$filename}");
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
header('Content-Length: ' . filesize($file));
// push the buffer to the client and exit
ob_clean();
flush();
// read the file and push to the output stream
readfile( $filename );
// remove the file from the filesystem
unlink( $filename );
exit();

I would recommend a class like TCPDF, see http://www.tcpdf.org/. I used it couple of times and it's quite nice (open source).

Related

why does an empty pdf file created in the same folder when i click download every time?

i was trying to force download pdf files on my website. The file was downloaded successfully but an empty file is created in the same folder with a random name when download is clicked. i'm having multiple null files in the folder.
download.php :
<?php
$file = $_GET['file'];
header('Content-type: application/pdf');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="'.$file.'"');
?>
Assuming you store your pdf in database.
//you need to decode
$decoded = base64_decode($downloaded->pdf);
//name of pdf
$filename =date('Ymdhis').'.pdf';
$size=strlen($decoded);
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.($filename).'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header('Content-Length:'.$size);
echo($decoded);
exit;
Please note, if you send some headers before it will not working.
Make sure you create properly your pdf file.
$decoded = base64_decode($downloaded->pdf);
$filename =date('Ymdhis').'.pdf';
//if file doesn't exists
if(!file_exists($filename)){
//we create file in the location
$fp=fopen($_SERVER['DOCUMENT_ROOT'].'/tmp/'.$dir_name.''.$filename,'a+');
//We write in
fwrite($fp, $decoded);
}

Download RAR file from a link (server)

I'm trying to download a .rar file from a cloud (for sake of simplicity I'm using my google drive storage), the file is downloading perfectly, but once i want to open the .rar file , it says that "the archive is either unknown format or damaged" , tried all methods even cURL ,but it didnt want to work,
Im just wondering what I'm missing in my code, thank you
<?php
$filename = 'stu.rar';
if ( file_put_contents( $filename,file_get_contents("mygoogleDriveLink/search?q=stu.rar"))) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
//header('Content-Length: '.filesize($filename));
readfile($filename);
//print_r("this is ".$id);
exit();
}
else{
echo "err";
}
You may use file_put_contents to save the file to the server first, before you stream it to your browser.
if you do not need to stream to user's web browser, then you may remove the codes from start streaming to end streaming.
Please try the following:
<?php
// Initialize a file URL to the variable
$url = 'http://www.xxxxxxxxxxx.com/xxxxx.rar';
// Use basename() function to return the base name of file
$file_name = basename($url);
// Use file_get_contents() function to get the file
// from url and use file_put_contents() function to
// save the file by using base name
if(file_put_contents( $file_name,file_get_contents($url))) {
// File successfully saved in the server
// start streaming . The following is to stream and save to browser
$file_name = $file_name;
$file_url = $file_name;
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$file_name."\"");
readfile($file_url);
exit;
/// end streaming
}
else {
echo "File downloading failed.";
}
?>

(PHP) Problem with filename after downloading it

While writing a PHP-Script, im stuck at an issue i cant resolve.
The PHP-Script consist in letting a user download a .mp4 file. The download works without any issues but the file downloaded can not be played.
Heres the code:
<?php
$filepath = "/www/servermedia/technounion.mp4";
$filename = basename($filepath);
header("Content-type: video/mp4");
header("Content-Disposition: attachment; filename=.$filename");
readfile($filename);
exit;
?>
After the .mp4 file gets downloaded, it cannot be played.
It looks like this:
The error message means that Windows Media Player cannot play back the file because probably the player doesnt support the codec. I already tried with VLC but it does not work either.
EDIT:
Comparing both file sizes, the downloaded file is only a couple bytes large instead of the 3,73 MB of the file on the server
Your code is not well-formed, you miss to escape double-quotes by adding single-quotes as I done here, please test my answer.
<?php
$filepath = "/www/servermedia/technounion.mp4";
$filename = basename($filepath);
header('Content-Type: video/mp4');
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($filename);
exit;
?>
But I suggest a more complex way:
<?php
$filepath = $_SERVER['DOCUMENT_ROOT'] . "/www/servermedia/technounion.mp4";
$filename = basename($filepath);
header('Content-Type: video/mp4');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . sprintf("%u", filesize($filepath)));
set_time_limit(0);
$fh = fopen($filepath, "rb");
while (!feof($fh)) {
echo fgets($fh);
ob_flush();
flush();
}
fclose($fh);
exit;
?>
$_SERVER['DOCUMENT_ROOT'] is useful to get the full path from the server
set_time_limit(0) is useful to avoid any timeout during download
fgets() is useful for reading large files
ob_flush() and flush() assure that there is not other output in the buffer
I hope this helps.
Is the downloaded file the exact same filesize?
Does the content type exist in your webserver?
header("Content-Type: video/mp4"); Note capital 'T' for type.
This maybe worth testing with to see you can serve the file content inline:
http://www.phpmind.com/blog/2016/10/how-to-use-php-to-output-an-mp4-video/

open a pdf inline in the browser. File link has no extension

I have a pdf generated invoice witch i like to display inline in the browser:
link is for example: guest/view/invoice/vqhH8sujcOrpg0t2nF4WQExDLKXmYTNe
No extension.
the below code gets a failed to load PDF document when i change it to attachment it works but give a download while i like to display it inline.
$file = site_url('guest/view/generate_invoice_pdf/' . $invoice_url_key);
$filename = 'factuur.pdf';
header("Content-type: application/pdf");
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
echo $file;
Sorry i though i did a thorough search but i din't solution is this:
Orginal from: Chrome has "Failed to load PDF document" error message on inline PDFs
I've been wrestling with this same issue. This is as close as I got to consistent results across browsers. I think that the reason you could be having problems is if some PDF's are too large for readfile() to handle correctly. Try this:
$fp = fopen($file, "r") ;
header("Cache-Control: maxage=1");
header("Pragma: public");
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=".$myFileName."");
header("Content-Description: PHP Generated Data");
header("Content-Transfer-Encoding: binary");
header('Content-Length:' . filesize($file));
ob_clean();
flush();
while (!feof($fp)) {
$buff = fread($fp, 1024);
print $buff;
}
exit;````

How to Automatically Start a Download in PHP?

What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited?
I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software?
Send the following headers before outputting the file:
header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");
#grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)
Here is an example of sending back a pdf.
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
readfile($filename);
#Swish I didn't find application/force-download content type to do anything different (tested in IE and Firefox). Is there a reason for not sending back the actual MIME type?
Also in the PHP manual Hayley Watson posted:
If you wish to force a file to be downloaded and saved, instead of being rendered, remember that there is no such MIME type as "application/force-download". The correct type to use in this situation is "application/octet-stream", and using anything else is merely relying on the fact that clients are supposed to ignore unrecognised MIME types and use "application/octet-stream" instead (reference: Sections 4.1.4 and 4.5.1 of RFC 2046).
Also according IANA there is no registered application/force-download type.
A clean example.
<?php
header('Content-Type: application/download');
header('Content-Disposition: attachment; filename="example.txt"');
header("Content-Length: " . filesize("example.txt"));
$fp = fopen("example.txt", "r");
fpassthru($fp);
fclose($fp);
?>
None of above worked for me!
Working on 2021 for WordPress and PHP:
<?php
$file = ABSPATH . 'pdf.pdf'; // Where ABSPATH is the absolute server path, not url
//echo $file; //Be sure you are echoing the absolute path and file name
$filename = 'Custom file name for the.pdf'; /* Note: Always use .pdf at the end. */
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: https://qastack.mx/programming/4679756/show-a-pdf-files-in-users-browser-via-php-perl
my code works for txt,doc,docx,pdf,ppt,pptx,jpg,png,zip extensions and I think its better to use the actual MIME types explicitly.
$file_name = "a.txt";
// extracting the extension:
$ext = substr($file_name, strpos($file_name,'.')+1);
header('Content-disposition: attachment; filename='.$file_name);
if(strtolower($ext) == "txt")
{
header('Content-type: text/plain'); // works for txt only
}
else
{
header('Content-type: application/'.$ext); // works for all extensions except txt
}
readfile($decrypted_file_path);

Categories