in PHP How to download the file from its file path? - php

I am new to PHP and trying my hands into it. I am creating a file and writing back to it. Creating a file in some path and writing to it, works fine for me. But when i try to download the same file from the same path, its not getting downloaded instead I'm getting empty file.
header('Content-type: text/xml');
header("Content-Disposition: attachment; filename=".'check.xml');
header("Content-Length: " . filesize('./download/'.$_SESSION['user_name'].'/check.xml'));
readfile('download/'.$_SESSION['user_name'].'/check.xml');
exit;
Hi, Thanks for everyone. But I saw very unusual thing. When i downloaded the file, I didn't got the full file.
Why this case

Try removing ./ from the start of the filepath, like follows:
header('Content-type: text/xml');
header("Content-Disposition: attachment; filename=".'check.xml');
header("Content-Length: " . filesize('download/'.$_SESSION['user_name'].'/check.xml'));
readfile('download/'.$_SESSION['user_name'].'/check.xml');
exit;
With Linux file systems, ./ means the root, so that's the equivalent of / and ../ means the directory above the current directory. It's best to use absolute file paths, but simply removing the ./ should suffice.

You will also need to flush the write buffers of PHP using flush()
Here is a good working function to download a file
Here is a version adapted from that page:
public static function downloadFile($fileName) {
$filePath = $fileName;
$size = filesize($filePath);
// Taken from http://w-shadow.com/blog/2007/08/12/how-to-force-file-download-with-php/
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Content-Transfer-Encoding: binary");
header("Accept-Ranges: bytes");
// The three lines below basically make the download non-cacheable
header("Cache-control: private");
header("Pragma: private");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Content-Length: " . $size);
if ($file = fopen($filePath, "r")) {
$buffer = fread($file, $size); // this only works for small files!
print $buffer;
flush();
fclose($file);
}
}

Related

readfile() function read the zip file instead of Downloading it (Zend)

I have to trigger a download of a zip file ( The Zip file is inside my data folder).
For this i am using the code,
$file = 'D:\php7\htdocs\Project\trunk\api\data\file.zip';
header('Content-Description: File Transfer');
header('Content-type: application/zip');
header('Content-disposition: attachment; filename=' . basename($file) );
readfile($file);`
This is working in core php as i expected. But when i am using the same code in the Zend prints a content like below,
PKYsVJ)~�� study.xlsPKYsVJs�����+
tutorial-point-Export.xlsPKYsVJn��� 8��Zabc.xlsP
In between the content i can see the name of all files in the zip. But it is not getting downloaded.
After i realised that this is not working i started searching about it and Found some solution from stack over flow
Try 1: Adding different header element and ob functions in every random lines
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: ' . $file_size);
ob_start();
ob_clean();
flush();
All these are tried from different stack overflow Question and answers and have the same result
Try 2:PHP is reading file instead of downloading . This question do not have any accepted answer (He was asking about the core php but i have the same issue with zend only) . I tried all of this but it was not working.
Try 3:Changing the .htaccess . After that i thought it was a problem with my .htaccess and found this answer for changing the .htaccess file.
<FilesMatch "\.(?i:zip)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
This also given me the same result.
Try 4:Using download functions in Zend . I have tried the all the zend functions in the answer of this question. But given me an empty output even the file was not read.
Try 5: Remove all the unwanted spaces before and after the php tag as per the answer
Is there any other way to trigger a download in ZF2 framework?
EDIT
Below is my exact function. This is GET(API) function,
public function getList(){
try{
//here i am getting the zip file name.
$exportFile = $this->getRequest()->getQuery('exportid','');
$file = 'D:\php7\htdocs\Project\trunk\api\data\\' . $exportFile . '.zip';
header('Content-Description: File Transfer');
header('Content-type: application/zip');
header('Content-disposition: attachment; filename=' . basename($file) );
readfile($file);
return new JsonModel(["status"=>"Success"]);
} catch(\Exception $e){
return new JsonModel(["status"=>"Failed"]);
}
}
There are two problems here:
your browser trying to open the file, instead of downloading it.
also, it is not opening the file correctly.
Both point to a Content-Type error. Verify that the Content-Type being received by the browser is correct (instead of being rewritten as, say, text/html).
If it is, change it to application/x-download. This might not work in Internet Explorer, which performs some aggressive Content-Type sniffing. You might try adding a nosniff directive.
Additionally, after a readfile (and you might be forced to return the file's contents instead of readfile()'ing - i.e., return file_get_contents($filename);), you should stop all output with return null;. ZIP file directory is at the very end, so if you attach a JSON message there, you risk the browser neither downloading the file, nor displaying it correctly.
As a last resort, you can go nuclear and do everything yourself. Extremely non-elegant, and all frameworks ought to provide an alternative, but just in case...
// Stop *all* buffering
while (ob_get_level()) {
ob_end_clean();
}
// Set headers using PHP functions instead of Response
header('Content-Type: application/x-download');
header('X-Content-Type-Options: nosniff');
header('Content-Length: ' . filesize($filename));
header('Content-Disposition: attachment; filename="whatever.zip"');
die(readfile($filename));
It's possible that some creative use of atexit handlers or destructor hooks might mess up even this last option, but I feel it's unlikely.
Based on this SO answer, you can try the following modification to your function.
public function getList(){
try{
//here i am getting the zip file name.
$exportFile = $this->getRequest()->getQuery('exportid','');
$file = 'D:\php7\htdocs\Project\trunk\api\data\\' . $exportFile . '.zip';
if (file_exists($file)) {
$response = new \Zend\Http\Response\Stream();
$response->setStream(fopen($file, 'r'));
$response->setStatusCode(200);
$response->setStreamName(basename($file));
$headers = new \Zend\Http\Headers();
$headers->addHeaders(array(
'Content-Description' => 'File Transfer',
'Content-Disposition' => 'attachment; filename="' . basename($file) .'"',
'Content-Type' => 'application/zip',
'Content-Length' => filesize($file)
));
$response->setHeaders($headers);
return $response;
//return new JsonModel(["status"=>"Success"]);
} else {
return new JsonModel(["status"=>"Failed. No such file in \"".$file."\""]);
}
} catch(\Exception $e){
return new JsonModel(["status"=>"Failed"]);
}
}
This worked for me!
ob_clean(); // Clear any previously written headers in the output buffer
$filepath = "some_file.zip";
$content_type = 'application/octet_stream';
$filetype = filetype($filepath);
$filename =$filepath;
if($filetype=='application/zip')
{
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
$fp = #fopen($filepath, 'rb');
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
{
header('Content-Type: '.$content_type);
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
header("Content-Length: ".filesize(trim($filepath)));
}
else
{
header('Content-Type: '.$content_type);
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".filesize(trim($filepath)));
}
fpassthru($fp);
fclose($fp);
}
If you correct the capitalisation of the headers does it work? ie use Content-Disposition and Content-Type over Content-disposition and Content-type respectively?
Regardless, as standard debugging technique I would suggest using your browser dev tools to inspect the requests that are being made (inc headers) and comparing that to what ends up in your serverside code, and what is in the server side response and what ends up in the client. I would also validate this using a private-session (Incognito mode in Chrome etc) or a fresh profile / VM install just to eliminate anything else.
Also, why not use xsendfile and delegate the responsibility of sending the file to the web server so you aren't incurring the responsibility in your PHP code? You can do this with appropriate server configuration (sometimes through .htaccess, but in this day and age surely you have complete control anyway) and then simply setting the X-Sendfile header as per the example on the above link:
header("X-Sendfile: $path_to_somefile");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$somefile\"");
Because you are return JsonModel so your output will be a json with your message instead of buffering for downloading.
Edit: I notice that you was missing Content-Transfer-Encoding: Binary, tested on my os x - php5.6 env.
You should try this
public function getList(){
try{
//here i am getting the zip file name.
$exportFile = $this->getRequest()->getQuery('exportid','');
$file = 'D:\php7\htdocs\Project\trunk\api\data\\' . $exportFile . '.zip';
header('Content-Description: File Transfer');
header('Content-type: application/zip');
header('Content-disposition: attachment; filename=' . basename($file));
header("Content-Transfer-Encoding: Binary");
header("Content-length: " . filesize($file));
header("Pragma: no-cache");
header("Expires: 0");
readfile("$file");
} catch(\Exception $e){
return new JsonModel(["status"=>"Failed"]);
}
}
Just remove your JSonModel on response.
You can try this for downloading the file instead of readfile();
Server side -
file_put_contents("file.zip", fopen("http://someurl/file.zip", 'r'));
Client side -
<button>download file</button>
download file

Downloading code is not working in wordpress [duplicate]

This question already has answers here:
Forcing to download a file using PHP
(10 answers)
Closed 9 years ago.
When I am downloading an image it's displaying these characters on screen.
�M\cIDATx��\i��v�U�ݳ��x���6`8�Y�&#��#D �����HDʟ'�~�z;a���D,�c������ƌ���ٺ�*�w�=շjz^z�ـ���UwWWݺ�;�|g��&H���o�Gy�𼖖��~s��K۲e�y�7�ѣG�̙3ͤI������3�O=�T���n�z�)�k�.�p�B��NJ��6m���؄a(�ٳgOt��i���|����hhh((�˦����{����3��sO�C�:�_�k�������s�)�|X�V��_C�6���2o~G���3����y۶m��o4�\s�) r�ܹse.|-[�,�`~/N� GQdU(h!Z� |E���J��h�&�u�sާ�ES�T���æ��ׯh�o�>���ˡ�ˠ�-��-m�{ �\p�#Mo؅u�֙���{�qN;,�ŋ�cߏ䦦&3u�T���)��MS�yrP���B|o���Ԏ�l1�C&L8�����j�j/_4ϯ���4��o�o��w�>|8�5���M�P�;f���͆ Ҿ&N�hJM%C�,Z�� Z=�9螞�=~��4�7H�������#���-"0�jWW�1���{[[[�:;'�Θ1�0�+�^h�h�>��#�Aw�;�� ��Ba�J%�ޓ���;�����с� ���4�2�<xͩt�8��="" p�ٴi�����="" 4g�q8��:��u�9q:v�i��x(���r�b��m��n��f�ml���="" ���)��n�="" ="" -��="" ���o����+�itj�_⧟~"Ȣ="" Ԯj��`�!�x��sn��n�g��'�j��cmv��o="" !�����?������޷r���p��(��)�,Ԭ^�z�0k֬���ŀh�`�5�'��1�����&\��+�2�o="" �v��4�="" �ac="" ��="" 4�f+�e�="" �ӭ�w����j���q�#�)��t̟??��x4�7e���oh�6o޼���r&�lh�z�n��l�8��pn���kἎbhj�e�-�|!�*���ɪ��z="">�E��Ŵ��;���Ʃ�0����j\�]o^�X�A�qο�8cVh�Q�M�x��F](L3�#'f�T�*4�IxZ,K8��͜ ! ���S��MJ�h� 5��2��p�!��wۇ�n� �M�/Z�c�=&Q��_h&�8� �X8��.��鑪&uRL���b�j�~Wg���A �d#MUG(�+�B_r�$�h�w ���i 2���ʠ>�QƸ�v�e�n�~|�fm�1� D��6K�w{����z��7T0�����}���ĩ#��Q�8K�Q�"�8�^2��d�N�+l�$j3�j����h'�x�V.��qmA�����P�?[� ^bIFE�Q����#�{i���o��� �:�<&��Y���Ѳ%�L�U��܍�����ź�ZB�\���*N��X� G!*=w�J#-���k5� m��\ 7�8O~��,��=�݄}Jp�?�P�L)�P��j4F�����"Ds:��I�o���^{M����*4H#�
And I used this code for downloading
$fn = $path.'/'.$file_name;
$mm_type="application/octet-stream";
header("Cache-Control: public, must-revalidate");
header("Pragma: hack");
header("Content-Type: " . $mm_type);
header("Content-Length: " .(string)(filesize($fn)) );
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header("Content-Transfer-Encoding: binary\n");
readfile($fn);
I have tried with your code and found no problem. After read your comment and try with your file thetexturemill.com/wp-content/uploads/2013/07/dell.png I have this code working:
# my demo value in my local machine
$path = dirname(__FILE__) . "/demo";
$file_name = "Capture.PNG";
#$fn = realpath($path.'/'.$file_name);
$fn = "http://thetexturemill.com/wp-content/uploads/2013/07/dell.png";
//var_dump(readfile($fn));
$mm_type="application/octet-stream";
#$mm_type=mime_content_type($fn);
#echo $mm_type; die();
ob_get_flush();
header("Cache-Control: public, must-revalidate");
header("Pragma: hack");
header("Content-Type: " . $mm_type);
#header("Content-Length: " .(string)(filesize($fn)) );
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header("Content-Transfer-Encoding: binary\n");
readfile($fn);
flush();
die();
What problems I found are:
If you use an image from remote host, make sure you can get it (the allow_url_fopen INI option is ON and the returned value from readfile is greater than zero) and do not use filesize as well as mime_content_type functions.
I don't know whether thetexturemill.com is your domain name or folder name. Supposed that it is a domain name, remember to add the protocal prefix (http:// as in example)
Do not output anything before the header function calls or your downloaded file will not be open properly.
Ah, for local file, your original code work without errors on my machine.
The content type is wrong
application/octet-stream
Ocet-stream is used for executable files which images are not for sure.
A proper type for a image for jpg image is for example:
image/jpeg
You can use mime_content_type() to get proper content type of file
Returns the MIME content type for a file as determined by using information from the magic.mime file.
Try this code
$fn = $path.'/'.$file_name;
$mime = mime_content_type($fn);
header('Content-Type:'.$mime);
header('Content-Length: ' . filesize($fn));
readfile($fn);
Try this,
<?php
$fn = $path.'/'.$file_name;
$mm_type="application/octet-stream";
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Length: " .(string)(filesize($fn)) );
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Disposition: attachment; filename="'.$fn.'"');
header("Content-Transfer-Encoding: binary\n");
ob_clean();
flush();
readfile($fn);
exit;
?>
Read this http://php.net/manual/en/function.readfile.php

try to download file and getting invalid file in response in core php

I download a file but it gives invalid file in return.
Here's my download_content.php
<?php
$filename = $_GET["filename"];
$buffer = file_get_contents($filename);
/* Force download dialog... */
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
/* Don't allow caching... */
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
/* Set data type, size and filename */
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . strlen($buffer));
header("Content-Disposition: attachment; filename=$filename");
/* Send our file... */
echo $buffer;
?>
download file link:
Download
$r['file'] contains the file name to be downloaded.
The complete path of the folder which contain the file is:
localhost/ja/gallery/downloads/poster/large/'.$r['file'].'
ja is the root folder in htdocs.
I don't know what the actual problem is, can anyone help me out please?
<?php
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
// print your data here. note the following:
// - cells/columns are separated by tabs ("\t")
// - rows are separated by newlines ("\n")
// for example:
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";
?>
As said in the other question, this way looks better:
$filename = $_GET["filename"];
// Validate the filename (You so don't want people to be able to download
// EVERYTHING from your site...)
// For example let's say that you hold all your files in a "download" directory
// in your website root, with an .htaccess to deny direct download of files.
// Then:
$filename = './download' . ($basename = basename($filename));
if (!file_exists($filename))
{
header('HTTP/1.0 404 Not Found');
die();
}
// A check of filemtime and IMS/304 management would be good here
// Google 'If-Modified-Since', 'If-None-Match', 'ETag' with 'PHP'
// Be sure to disable buffer management if needed
while (ob_get_level()) {
ob_end_clean();
}
Header('Content-Type: application/download');
Header("Content-Disposition: attachment; filename=\"{$basename}\"");
header('Content-Transfer-Encoding: binary'); // Not really needed
Header('Content-Length: ' . filesize($filename));
Header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
readfile($filename);
That said, what does "invalid file" mean? Bad length? Zero length? Bad file name? Wrong MIME type? Wrong file contents? The meaning may be clear to you with everything under your eyes, but from our end it's far from obvious.
UPDATE: apparently the file is not found, which means that the filename= parameter to the PHP script is wrong (refers a file that's not there). Modified the code above to allow a directory to contain all files, and downloading from there.
Your $filename variable contains whole path as below
header("Content-Disposition: attachment; filename=$filename");
Do like this
$newfilename = explode("/",$filename);
$newfilename = $newfilename[count($newfilename)-1];
$fsize = filesize($filename);
Then pass new variable into header
header("Content-Disposition: attachment; filename=".$newfilename);
header("Content-length: $fsize");
//newline added as below
ob_clean();
flush();
readfile($filename);

Download Image link using php

I downloaded this code to use as a download button.
<?
$filename = $_GET["filename"];
$buffer = file_get_contents($filename);
/* Force download dialog... */
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
/* Don't allow caching... */
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
/* Set data type, size and filename */
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . strlen($buffer));
header("Content-Disposition: attachment; filename=$filename");
/* Send our file... */
echo $buffer;
?>
The thing is, the name of the file ends up with the whole path in the file name, for example, this code:
<a href="download.php?filename=images/something.jpg">
Ends up with an image named "images_something.jpg"
I'd like to remove the "images_" from the final file name, so far I haven't had any luck.
Thanks for the help!
If you need the file name part without folder name, you have to use basename($filename)
http://php.net/manual/en/function.basename.php
basename()
$filename = basename($path);
p.s
Setting Content-Type several times may not be the best way to force a download. Also, I hope you're sanitizing that $filename argument before you use a file_get_contents.
p.p.s
Use readfile, don't cache it in the memory.
$filename = basename($filename);
header("Content-Disposition: attachment; filename=$filename");
Set your filename to only be the basename?
Don't do it at the top unless you change the variables though so your pathing to it still works.

Serve file to user over http via php

If I goto http://site.com/uploads/file.pdf I can retrieve a file.
However, if I have a script such as:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);
//require global definitions
require_once("includes/globals.php");
//validate the user before continuing
isValidUser();
$subTitle = "Attachment";
$attachmentPath = "/var/www/html/DEVELOPMENT/serviceNow/selfService/uploads/";
if(isset($_GET['id']) and !empty($_GET['id'])){
//first lookup attachment meta information
$a = new Attachment();
$attachment = $a->get($_GET['id']);
//filename will be original file name with user name.n prepended
$fileName = $attachmentPath.$_SESSION['nameN'].'-'.$attachment->file_name;
//instantiate new attachmentDownload and query for attachment chunks
$a = new AttachmentDownload();
$chunks= $a->getRecords(array('sys_attachment'=>$_GET['id'], '__order_by'=>'position'));
$fh = fopen($fileName.'.gz','w');
// read and base64 encode file contents
foreach($chunks as $chunk){
fwrite($fh, base64_decode($chunk->data));
}
fclose($fh);
//open up filename for writing
$fh = fopen($fileName,'w');
//open up filename.gz for extraction
$zd = gzopen($fileName.'.gz', "r");
//iterate over file and write contents
while (!feof($zd)) {
fwrite($fh, gzread($zd, 60*57));
}
fclose($fh);
gzclose($zd);
unlink($fileName.'.gz');
$info = pathinfo($fileName);
header('Content-Description: File Transfer');
header('Content-Type: '.Mimetypes::get($info['extension']));
header('Content-Disposition: attachment; filename=' . basename($fileName));
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($fileName));
ob_clean();
flush();
readfile($fileName);
exit();
}else{
header("location: ".$links['status']."?".urlencode("item=incident&action=view&status=-1&place=".$links['home']));
}
?>
This results in sending me the file, but when I open it I receive an error saying:
"File type plain text document (text/plain) is not supported"
First off, I'd start by checking the HTTP headers. You can do this in Firefox easily using the "Live HTTP headers" extension; not sure about equivalents in other browsers offhand. This will let you verify if the header is actually getting set to "application/pdf" and whether your other headers are getting set as well.
If none of the headers are getting set, you might be inadvertently sending output before the calls to header(). Is there any whitespace before the <?php tag?
Are you sure application/pdf is the header your browser is actually seeing?
You can check that out with various HTTP dev tools, for instance HTTP Client for the Mac or Firebug for Firefox.
I use this one and it works.
if(file_exists($file_serverfullpath))
{
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
//sending download file
header("Content-Type: application/octet-stream"); //application/octet-stream is more generic it works because in now days browsers are able to detect file anyway
header("Content-Disposition: attachment; filename=\"" . basename($file_serverfullpath) . "\""); //ok
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($file_serverfullpath)); //ok
readfile($file_serverfullpath);
}
Try prepending "error_reporting(0);". I found this in the comments at http://php.net/readfile (where you took this example from).
Another thing that could be a problem is your file size. There have been issues reported in the past about PHP5 (we're talking 2005 here, so i hope this is fixed by now) having trouble reading files >2MB. If your file size exceeds this you may want to verify that it reads the whole file.

Categories