php force download file not working - php

I am trying to make make a visitor download text file when visiting a certain page. This is the page:
<?php
$file_url = 'text.txt';
header("Content-Disposition: attachment; filename=\"" . basename($file_url) . "\"");
header("Content-Type: application/force-download");
header("Content-Length: " . filesize($file_url));
header("Connection: close");
readfile($file_url)
?>
However, the file just shows up in the browser, in stead of asking for downloading. What am i doing wrong?

You might be missing some header properties.
<?php
$file_url = 'text.txt';
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename='.basename($file_url));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_url));
readfile($file_url);
exit;
?>

Related

PHP Force download not working for ZIP file

I am trying to download a zip file using headers. But it returns some special character's.
I tried the below code.
$filepath='http://localhost/mb/inc/tmp/liberty/xml_invoice.zip'
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="test.zip');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
ob_clean();
flush();
readfile($filepath);
exit();
when i run this code i am getting output like some special characters.like below
�Q�s�+k�X�ߡB�R�EE����m��#;Ok����A���R�2vZ�j�F�Mo� C�
If you want to deliver a ZIP file then you need to use also the correct MIME content type!
$filename = "xml_invoice.zip"
$file = "C:\wamp64\www\mb\inc\tmp\liberty\{$filename}";
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename={$filename}");
header("Content-length: " . filesize($file));
header("Pragma: no-cache");
header("Expires: 0");
readfile($file);
try this: give path to your zip file.
$filepath = "/path/to/some_file.zip";
$file_name = basename($filepath);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Length: " . filesize($filepath));
readfile($filepath);
exit;

PHP - Forcing download a file not working

code.php
$code = $_GET["code"];
$file = 'code/'.$code.'.html';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
Generated URL to download the file:
http://www.example.com/code.php?code=yoursite.com_nbsp63ibrf
Well, I want to forcing download the html file, above code not working and it just preview the file at browser!
file_exists() returns false. Change your path with document root:
$code = $_GET["code"];
$file = $_SERVER['DOCUMENT_ROOT'] . '/code/' . $code . '.html'; // set your path from document root.
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
Try changing the content type to match the file type and setting the transfer encoding to binary:
header('Content-Transfer-Encoding: binary');
header('Content-Type: text/html');
Try this
$code = $_GET["code"];
$file = $_SERVER['DOCUMENT_ROOT'] . '/code/' . $code . '.html'; // set your path from document root.
if (file_exists($file)) {
header("Content-Type: text/html");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
unfortunately it was a encoding issue. I changed code.php encoding from UTF-8 to UTF-8 Without BOM then problem solved. Thanks for all answers and helps. I forgot that PHP header only works with UTF-8 Without BOM.
This is actually not possible.
The browser can always decide on its own, if the file should be downloaded or not.
The furthest you can go is sending the content-disposition header.

Pdf damaged on download

I've got a web from that has two buttons for submitting, one sends an email with pdf attached, this works perfectly.
The second button is to download the pdf, this is the problem. I am saving the pdf in a temp file before download but after it is downloaded the file doesn't open and it is corrupt. The pdf is about 30KB. I have tried solutions to similar questions but always the same result, the pdf won't open.
This didn't work
$fileName = "file.pdf";
$file_name = ("temp/file.pdf");
file_put_contents($file_name, $pdf_content);
$filepath=$file_name; //file location
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
This didn't work
$path = $_SERVER['DOCUMENT_ROOT']."/temp/"; // change the path to fit your websites document structure
$fullPath = $path.$fileName;
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-disposition: attachment;
filename='.basename($fullPath));
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. filesize($fullPath));
readfile($fullPath);
exit;
This didn't work
set_time_limit(0); // disable timeout
$file = $root_path.'/full-tile-book.pdf';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="NewName.pdf"');
header('Content-Length: ' . filesize($file));
$f = fopen($file, 'rb');
fpassthru($f);
fclose($f);
exit;
This didn't work
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Type: application/pdf');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($filepath)) . ' GMT');
header('Content-disposition: attachment; filename=file.pdf');
header("Content-Transfer-Encoding: binary");
header('Content-Length: ' . filesize($filepath)); // provide file size
header('Connection: close');
readfile($filepath);
exit();
The file is always in the temp folder on the server and that works fine so somewhere in the download the file is getting corrupted.
I don't care how the download is done, pdf or oclet-stream or any other way.
I removed the : Content-Type header and it works for me.
Regards

How do I properly send a PDF file through PHP?

I am trying to send a PDF file. Here is the code that is executing:
$file_path = '/path/to/file/filename.pdf'
$file_name = 'filename.pdf'
header("X-Sendfile: $file_path");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename='$filename'");
readfile($file_path):
whenever I download the file directly, it is fine. however when I try to download the file via this script, a file downloads that cannot be opened. my pdf reader tells me it cannot open a file of type 'text/plain'. I also tried setting the Content-type to application/pdf , but I get the same errors. What am I doing wrong here?
Have you tried this?
$file = '/path/to/file/filename.pdf';
header('Content-Disposition: attachment; filename="'. basename($file) . '"');
header('Content-Length: ' . filesize($file));
readfile($file);
Using readfile() also eliminates any memory issues you might encounter.
try the code below.
header("Content-Type: application/octet-stream");
$file = "filename.pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp)
If the above one does not help you try the below
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=' . urlencode(basename($file)));
// header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
Don't for get to set the file path $file_path as required.

Force file download with php using header()

I want the user to be able to download some files I have on my server, but when I try to use any of the many examples of this around the internet nothing seems to work for me. I've tried code like this:
<?php
$size = filesize("Image.png");
header('Content-Description: File Transfer');
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename="Image.png"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);
readfile("Image.png");
I've even tried to use the most basic example I could find, like this:
<?php
header('Content-type: image/png');
header('Content-Disposition: attachment; filename="Image.png"');
readfile('Image.png');
When I've tested this I have removed all the other code I have and used an empty file with just this code to remove any faults created by external sources.
When I look in the console the file gets sent with the right headers i.e
'Content-Disposition: attachment; filename="Image.png"'
But the save dialog isn't displayed.
I've also tried with inline instead of attachment in the content disposition header but that didn't make a difference either, I've tested this in Firefox 8.0.1 Chrome 15.0.874.121 and Safari 5.1.1.
I’m pretty sure you don’t add the mime type as a JPEG on file downloads:
header('Content-Type: image/png');
These headers have never failed me:
$quoted = sprintf('"%s"', addcslashes(basename($file), '"\\'));
$size = filesize($file);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $quoted);
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: ' . $size);
This worked for me like a charm for downloading PNG and PDF.
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file_url)); //Absolute URL
ob_clean();
flush();
readfile($file_url); //Absolute URL
exit();
Based on Farhan Sahibole's answer:
header('Content-Disposition: attachment; filename=Image.png');
header('Content-Type: application/octet-stream'); // Downloading on Android might fail without this
ob_clean();
readfile($file);
This is all I needed for this to work. I stripped off anything that isn't required for this to work.
Key is to use ob_clean();
The problem was that I used ajax to post the message to the server, when I used a direct link to download the file everything worked fine.
I used this other Stackoverflow Q&A material instead, it worked great for me:
Ajax File Download using Jquery, PHP
its work for me
$attachment_location = "filePath";
if (file_exists($attachment_location)) {
header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
header("Cache-Control: public"); // needed for internet explorer
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Length:".filesize($attachment_location));
header("Content-Disposition: attachment; filename=filePath");
readfile($attachment_location);
die();
} else {
die("Error: File not found.");
}
the htaccess solution
<filesmatch "\.(?i:doc|odf|pdf|cer|txt)$">
Header set Content-Disposition attachment
</FilesMatch>
you can read this page:
https://www.techmesto.com/force-files-to-download-using-htaccess/
Here is a snippet from me in testing... obviously passing via get to the script may not be the best... should post or just send an id and grab guid from db... anyhow.. this worked. I take the URL and convert it to a path.
// Initialize a file URL to the variable
$file = $_GET['url'];
$file = str_replace(Polepluginforrvms_Plugin::$install_url, $DOC_ROOT.'/pole-permitter/', $file );
$quoted = sprintf('"%s"', addcslashes(basename($file), '"\\'));
$size = filesize($file);
header( "Content-type: application/octet-stream" );
header( "Content-Disposition: attachment; filename={$quoted}" );
header( "Content-length: " . $size );
header( "Pragma: no-cache" );
header( "Expires: 0" );
readfile( "{$file}" );

Categories