Trouble forcing ZIP download from PHP web app - php

This php file is supposed to:
receive a piece of information from a form on a different page
use this information to create an array of file paths to add to a zip file
create a dynamically named zip file using a class that's included.
force the download of the newly created zip file
numbers 1-3 are working flawlessly.
The page even forces the download of a zip file that is correctly named and is the right size, but when I try to open it, it says the file is invalid. I've seen similar problems in searches, but I have yet to find a solution.
If i enter the direct URL for the newly created zip into the browser, the file downloads and opens perfectly. As a matter of fact, my temporary fix was creating a dynamic direct link to the files :/
I should probably mention that this is hosted on the go daddy economy plan.
<?php
error_reporting(0);
include "gavScripts/connect_to_mysql.php";
require_once 'Zipper.php';
// prepare the file paths to add to the zip file and find the job/client name (for naming the zip folder)
if(isset($_POST['jobName']))
{
$clientID = $_POST['jobName'];
$clientSQL = mysql_query("SELECT clientName FROM job_client WHERE clientID = $clientID");
while($clientRow = mysql_fetch_array($clientSQL))
{
$clientName = $clientRow['clientName'];
}
$zipSQL = mysql_query("SELECT filePath FROM job_expense WHERE clientID = $clientID");
While($zipRow = mysql_fetch_array($zipSQL))
{
$filePaths[] = $zipRow['filePath'];
}
}
//create the zip folder and store the requested files
$zipper = new Zipper();
$zipper->add($filePaths);
$zipper->store('invoices/' . $clientName . '_Invoices.zip');
//download the zip
$fileDownload = 'invoices/' . $clientName . '_Invoices.zip';
$fileName = basename($fileDownload);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=" . $fileName . "");
header("Content-Length: " . filesize($fileDownload));
readfile($fileDownload);
?>

You may have trailing whitespace at the end of your script which is breaking your zip file. Is there a \r or \n (or both) after the closing ?>? Try removing the closing ?> which is optional anyway.

Try the following:
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime($fileName)).' GMT');
header('Cache-Control: private',false);
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($fileName).'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($fileName));
header('Connection: close');
readfile($fileName);
exit();
Might help.

Related

Write to a file in PHP and then download it

I am working on a project where I get a file stream and write this file to the servers local disk.
I then want PHP to download it but instead it just dumps out the data of the file to the page.
Below is how I am writing the file and trying to tell PHP to download it
$settingsManager = new SettingsManager();
$this->tempWriteLocation = $settingsManager->getSpecificSetting("hddFileWriterLocation");
$downloadUrl = $settingsManager->getSpecificSetting("tempFileUrlDownload") . "/$this->tempFileName";
if (!$this->checkIfDirectoryExists())
{
throw new Exception("Failed to create temp write directory: $this->tempWriteLocation");
}
$filePathAndName = "$this->tempWriteLocation\\$this->tempFileName";
$fh = fopen($filePathAndName, "w");
if (!$fh)
{
throw new Exception("Failed to open file handle for: $filePathAndName. " . error_get_last());
}
fwrite($fh, $this->fileData);
fclose($fh);
//return $downloadUrl;
header('Content-Description: File Transfer');
header('Content-Type: audio/wav');
header('Content-Disposition: attachment; filename='.basename($filePathAndName));
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($filePathAndName));
ob_clean();
flush();
readfile($filePathAndName);
When the above code being run, I get the following output (only a snippet)
RIFF\tWAVELIST2INFOISFT%Aculab Media System Server V2.3.4b11fmt
##fact�sdata�sUU������UUUUUU�UUU��U���UU��UUU�UUUU���UU���UU�����UU
Just so you know the diamonds are actual output I get back, not anything wrong with Stack Overflow displaying something properly.
I've tried setting the content-type to be force-download but doesn't make any difference.
Try this header:
header('Content-type: audio/x-wav', true);
header('Content-Disposition: attachment;filename=wav-filename.wav');
and see if this works. From what I see you have you code formation setup correctly. Fixing the headers should download the file automatically.

correct PHP headers for pdf file download

I'm really struggling to get my application to open a pdf when the user clicks on a link.
So far the anchor tag redirects to a page which sends headers that are:
$filename='./pdf/jobs/pdffile.pdf;
$url_download = BASE_URL . RELATIVE_PATH . $filename;
header("Content-type:application/pdf");
header("Content-Disposition:inline;filename='$filename");
readfile("downloaded.pdf");
this doesn't seem to work, has anybody successfully sorted this problem in the past?
Example 2 on w3schools shows what you are trying to achieve.
<?php
header("Content-type:application/pdf");
// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename=\"downloaded.pdf\"");
// The PDF source is in original.pdf
readfile("original.pdf");
?>
Also remember that,
It is important to notice that header() must be called before any
actual output is sent (In PHP 4 and later, you can use output
buffering to solve this problem)
$name = 'file.pdf';
//file_get_contents is standard function
$content = file_get_contents($name);
header('Content-Type: application/pdf');
header('Content-Length: '.strlen( $content ));
header('Content-disposition: inline; filename="' . $name . '"');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
echo $content;
There are some things to be considered in your code.
First, write those headers correctly. You will never see any server sending Content-type:application/pdf, the header is Content-Type: application/pdf, spaced, with capitalized first letters etc.
The file name in Content-Disposition is the file name only, not the full path to it, and altrough I don't know if its mandatory or not, this name comes wrapped in " not '. Also, your last ' is missing.
Content-Disposition: inline implies the file should be displayed, not downloaded. Use attachment instead.
In addition, make the file extension in upper case to make it compatible with some mobile devices. (Update: Pretty sure only Blackberries had this problem, but the world moved on from those so this may be no longer a concern)
All that being said, your code should look more like this:
<?php
$filename = './pdf/jobs/pdffile.pdf';
$fileinfo = pathinfo($filename);
$sendname = $fileinfo['filename'] . '.' . strtoupper($fileinfo['extension']);
header('Content-Type: application/pdf');
header("Content-Disposition: attachment; filename=\"$sendname\"");
header('Content-Length: ' . filesize($filename));
readfile($filename);
Technically Content-Length is optional but it is important if you want the user to be able to keep track of the download progress, and detect if the download was interrupted before the end. When using it you have to make sure you won't be send anything along with the file data. Make sure there is absolutely nothing before <?php or after ?>, not even an empty line.
I had the same problem recently and this helped me:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="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("PATH/TO/FILE"));
ob_clean();
flush();
readfile(PATH/TO/FILE);
exit();
I found this answer here
Can you try this, readfile need the full file path.
$filename='/pdf/jobs/pdffile.pdf';
$url_download = BASE_URL . RELATIVE_PATH . $filename;
//header("Content-type:application/pdf");
header("Content-type: application/octet-stream");
header("Content-Disposition:inline;filename='".basename($filename)."'");
header('Content-Length: ' . filesize($filename));
header("Cache-control: private"); //use this to open files directly
readfile($filename);
You need to define the size of file...
header('Content-Length: ' . filesize($file));
And this line is wrong:
header("Content-Disposition:inline;filename='$filename");
You messed up quotas.
header("Content-type:application/pdf");
// It will be called downloaded.pdf thats mean define file name would be show
header("Content-Disposition:attachment;filename= $fileName ");
// The PDF source is in original.pdf
readfile($file_url);

Codeigniter Force download files

By going through the Codeigniter documentation, I am using the following code to force download files from my server.
function download($file_id){
$file = $this->uploadmodel->getById($file_id); //getting all the file details
//for $file_id (all details are stored in DB)
$data = file_get_contents($file->full_path); // Read the file's contents
$name = $file->file_name;;
force_download($name, $data);
}
The code is working file for images, but when it comes with the case of PDF files, it is not working. I have not tested it for all file extensions, but since it is not working for PDF, it might not work for other various file types.
Any solution?
I've had similar problems. I think the problem resides in certain mime's and headers sent to the browser(s). I've end up using the code I found here http://taggedzi.com/articles/display/forcing-downloads-through-codeigniter. Use the function below instead of force_download. It has worked for me so far.
function _push_file($path, $name)
{
// make sure it's a file before doing anything!
if(is_file($path))
{
// required for IE
if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); }
// get the file mime type using the file extension
$this->load->helper('file');
$mime = get_mime_by_extension($path);
// Build the headers to push out the file properly.
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($path)).' GMT');
header('Cache-Control: private',false);
header('Content-Type: '.$mime); // Add the mime type from Code igniter.
header('Content-Disposition: attachment; filename="'.basename($name).'"'); // Add the file name
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($path)); // provide file size
header('Connection: close');
readfile($path); // push it out
exit();
}
}
Hope it helps.
It is working for .pdfs also.
Check the path to the file - that might be the problem.
I, too, had that problem, but when I corrected the path to the file, it worked perfectly.
The following is how I wrote the code:
if($src == "xyyx")
{
$pth = file_get_contents(base_url()."path/to/the/file.pdf");
$nme = "sample_file.pdf";
force_download($nme, $pth);
}
Try this, I think its best practice for that problem.
function download($file_id)
{
$this->load->helper('file'); // Load file helper
$file = $this->uploadmodel->getById($file_id); //Get file by id
$data = read_file($file->full_path); // Use file helper to read the file's
$name = $file->file_name;;
force_download($name, $data);
}

File download from server using mysql and PHP

I have created a PHP page that allows users to download a file when they click the this link:
Download File
I have also created the download page that the link directs to:
<?php
if(isset($_GET['file'])) {
$fileID = $_GET['pubid'];
$filename= ($_GET['file']);
$path = "admin/pubfiles/";
$fullPath = $path . $filename;
mysql_select_db($database_connDioceseofife, $connDioceseofife);
$sql = "SELECT file FROM publications WHERE pubID = $fileID";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if($filename == NULL) {
die('No file exists or the name is invalid!');
}
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=\"$filename\"");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
readfile($fullPath);
}
?>
Now my problem is, when the download popup window come up, it reads that the file is of 0 bytes. And when downloaded, it can't open. i get the message that it is not a supported file type or its been damaged or corrupted.
Please any help would be much appreciated.
You're not doing anything with the query result in $row.
Use $row['file'] to get the actual file itself.
Thank you all for assisting me. I have been able to solve the problem after further reading. I have updated the initial script i wrote. what is above is now the working script.
What i did was to include $fullpath = $path . $filename then changed the header("Content-Disposition: attachment; filename=\"$filename\""); and then the readfile function from readfile($path) to readfile($fullpath).
Thanks again #nlsbshtr and everybody else for your help.

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