PHP - simple download script - php

I'm making a simple download script, where my users can download their own images etc.
But I'm having some weird problem.
When I've downloaded the file, it's having the contents from my index.php file no matter what filetype I've downloaded.. My code is like so:
$fullPath = $r['snptFilepath'] . $r['snptFilename'];
if (file_exists($fullPath)) {
#echo $fullPath;
// setting headers
header('Content-Description: File Transfer');
header('Cache-Control: public'); # needed for IE
header('Content-Type: '.$r['snptFiletype'].'');
header('Content-Disposition: attachment; filename='. $filename . '.' . $r['snptExtension']);
header('Content-Length: '.$r['snptSize'].'');
readfile($fullPath)or die('error!');
} else {
die('File does not exist');
}
$r is the result from my database, where I've stored size, type, path etc. when the file is uploaded.
UPDATE
When I'm uploading and downloading *.pdf files it's working with success. But when I'm trying to download *.zip and text/rtf, text/plain it's acting weird.
By weird I mean: It downloads the full index.php file, with the downloaded file contents inside of it.
ANSWER
I copied this from http://php.net/manual/en/function.readfile.php and it's working now. It seems that : ob_clean(); did the trick! Thanks for the help everyone.
#setting headers
header('Content-Description: File Transfer');
header('Content-Type: '.$type);
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;

Try this function , or implement these headers to your code
function force_download($filename) {
$filedata = #file_get_contents($filename);
// SUCCESS
if ($filedata)
{
// GET A NAME FOR THE FILE
$basename = basename($filename);
// THESE HEADERS ARE USED ON ALL BROWSERS
header("Content-Type: application-x/force-download");
header("Content-Disposition: attachment; filename=$basename");
header("Content-length: " . (string)(strlen($filedata)));
header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
// THIS HEADER MUST BE OMITTED FOR IE 6+
if (FALSE === strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE '))
{
header("Cache-Control: no-cache, must-revalidate");
}
// THIS IS THE LAST HEADER
header("Pragma: no-cache");
// FLUSH THE HEADERS TO THE BROWSER
flush();
// CAPTURE THE FILE IN THE OUTPUT BUFFERS - WILL BE FLUSHED AT SCRIPT END
ob_start();
echo $filedata;
}
// FAILURE
else
{
die("ERROR: UNABLE TO OPEN $filename");
}
}

I copied this from http://php.net/manual/en/function.readfile.php and it works now. ob_clean(); did the trick..
#setting headers
header('Content-Description: File Transfer');
header('Cache-Control: public');
header('Content-Type: '.$type);
header("Content-Transfer-Encoding: binary");
header('Content-Disposition: attachment; filename='. basename($file));
header('Content-Length: '.filesize($file));
ob_clean(); #THIS!
flush();
readfile($file);

Related

php file_put_contents save in local client real path [duplicate]

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}" );

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.

What is the correct syntax for defining filename with variables?

Regarding downloading files and defining the headers, I am having trouble assigning a dynamic filename to my files. When using the code below :
header("Content-Disposition: attachment; filename=test.csv");
A test.csv file is generated for download. However if I use this:
header('Content-Disposition: attachment; filename=' . $filename . '.csv');
It generates a .php file instead. Using this method also doesn't pass the Content-Disposition or filename to the header.
Full code:
session_start();
$file =$_SESSION['csvf'];
$filename = $file."_".date("Y-m-d_H-i",time());
header ( "Content-type: text/csv" );
header("Content-Disposition: attachment; filename=test.csv");
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
print($file);
exit ();
What is the correct syntax?
EDIT
Working Code after suggestions
session_start ();
$file = $_SESSION ['csvf'];
$filename =date ( "Y-m-d_H-i", time () );
header ( "Content-type: text/csv" );
header ( "Content-Disposition: attachment; filename=".$filename );
header ( 'Expires: 0' );
header ( 'Cache-Control: must-revalidate' );
header ( 'Pragma: public' );
header ( 'Content-Length: ' . filesize ( $file ) );
print ($file) ;
exit ();
I don't see the path to example.csv specified on your code, you need to give the full path to $file, i.e.:
$mySession = $_SESSION['csvf'];
//since $_SESSION['csvf'] contains the actual data you cannot use it for filename
$filename = date("Y-m-d_H-i",time()).".csv";
//write $mySession contents to file. Make sure this folder is writable
file_put_contents("/home/site/csvfolder/$filename", $mySession);
$file = "/home/site/csvfolder/$filename";
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename='.$filename);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
Please Use Like as follows,I am using this for me.
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=".$fileName);
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
In place of application/vnd.ms-excel use your file format.It is for Microsoft Excel.
Try with this:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=test.csv');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
You can see more about download files with PHP here:
http://php.net/manual/en/function.readfile.php
Try With Below code , it's work for me
$file =$_SESSION['csvf'];
$filename = $file."_".date("Y-m-d_H-i",time()).".csv";
header ( "Content-type: text/csv" );
header("Content-Disposition: attachment; filename=".$filename);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
print($file);
exit ();
Below is a snippet for a .zip file with some descriptions on some information that header requires, perhaps a good practice is to get the information and some validations before writing headers.
Another shorter example is also included,
// defines filename, type, path, size and a reference to file (handler)
// to set as values for file header
$filename = $survey_id . '.zip';
// define path to the file to be get file size on the next line
$filepath = [path to file]. '/' . $filename;
// used by 'Content-length'
$filesize = filesize($filepath);
// using fopen to get a file handler, 'r' for read, 'b' for binary (zip file)
$file_pointer = fopen($filepath, 'rb');
// check if file exists
if(is_file($filepath))
{
// valid file?
if($filesize && $file_pointer)
{
// some required header information to describe file, see [docs][1]
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: zip file");
header("Content-Type: application/zip");
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=" . $filename);
header("Content-Transfer-Encoding: binary");
header("Content-length: " . $filesize);
fpassthru($file_pointer);
// close
fclose($file_pointer);
}
}
Also, checkout readfile(), a shorter snippet below
<?php
$file = 'monkey.gif';
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;
}
?>
Hope this helps!
Just escape your php properly like so:
header('Content-Disposition: attachment; filename=' . time() . '.export.csv');
This example will put a UNIX timestamp prepended to the file name. Of course you could get crazy with programmatically using variables or inbuilt php functions, but this is just the example.
Here is more of an example. This file name will be produced when running this php code.
2019-05-18-contacts-main-export-by-Garrick.csv
header('Content-Disposition: attachment; filename=' . date("Y-m-d") . '-contacts-main-export-by-' . $uidName . '.csv');

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

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