Write to a file in PHP and then download it - php

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.

Related

PHP force download corrupt PDF file

I have gone through all articles on Stack Overflow and can't fix my issue. I am using following code:
$file = $_GET['url'];
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
The above mention code is downloading the file from the directly above the root and Yes it is downloading a PDF file but the file is only of 1KB size and not the original size. The $_GET['url'] is receiving ../dir/dir/filename.pdf in it. the filename is space in it as well. For security reason I cannot share the file name.
Please let me know where am I going wrong.
Please make sure you are using the web server path to access the file - for instance your path could be: /home/yourusername/public/sitename/downloads/<filename>, you should check first - to help you can run this at the top of your PHP script to find out the full path for the current script:
echo '<pre>FILE PATH: '.print_r(__FILE__, true).'</pre>';
die();
Only send the filename with the url using urlencode() and on the receiving PHP script use urldecode() to handle any character encoding issues.
See here: http://php.net/manual/en/function.urlencode.php
and here: http://php.net/manual/en/function.urldecode.php
So where you create your url:
Download File
And in your php script:
$file_base_path = '/home/yourusername/public/sitename/downloads/';
$file = urldecode($_GET['url']);
$file = $file_base_path . $file;
$file = $_GET['url'];
if (file_exists($file))
{
if (FALSE!== ($handler = fopen($file, 'r')))
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: chunked'); //changed to chunked
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
//header('Content-Length: ' . filesize($file)); //Remove
//Send the content in chunks
while(false !== ($chunk = fread($handler,4096)))
{
echo $chunk;
}
}
exit;
}
echo "<h1>Content error</h1><p>The file does not exist!</p>";
I hope this helps you!

How to Choose the location to save the download files when forcing file download in Codeigniter?

Now, the CSV file is exported in reports folder. Instead i want the browser to ask where to export the file. so that i can export the file in desired location of client machine and avoid storing those files in server (i.e)reports folder.
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$selProducts= $this->db->query("SELECT * FROM tablename");
$data= $this->dbutil->csv_from_result($selProducts);
$randomidgenerated = "reports/".date('Y-m-d').".csv";
if(file_exists(FCPATH.$randomidgenerated)){
$randomidgenerated = "reports/".date('Y-m-d')."_".random_string('alnum', 3).".csv";
}
if ( ! write_file($randomidgenerated, $data))
{
echo 'Unable to write the file';
}
$data = file_get_contents($randomidgenerated);
force_download($randomidgenerated, $data, TRUE);
from what i can see you are just creating the contents of the file to be downloaded dynamically... What you have to do now is force the browser to download the file to the clients chosen part then probably delete the temporary file afterwards if you dont want to store it on the server... Add the code below just after you have created the file or sure of its existence... something like
$file = FCPATH.$randomidgenerated;
if(file_exists($file)){
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.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;
}
That should do it.

Simple PHP script for XZ file download

I'm trying to setup a backup system that will perform a backup, compress the file and make it downloadable from a browser. The file downloads properly but when I try to uncompress it I get:
unxz: backup_2015-08-12.txz: File format not recognized
There is a backup script that will output
/tmp/agribackup.txz
The PHP script is as follows:
<?php
// Create the agribackup.txz file
$e = shell_exec("/usr/local/bin/agribackup.sh");
$file = '/tmp/agribackup.txz';
if(file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/xz');
header('Content-Disposition: attachment; filename=backup_'.date("Y-m-d") . '.txz');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>
I think you are using the wrong Content-Type. Refering to 'http://tukaani.org/xz/xz-file-format.txt', the correct MIME-type is 'application/x-xz'.

PDF document error using Zend_Pdf

In magento1.7, I have tried something like below in my custom controller.
public function getPDF()
{
$imagePath=C:\Users\.........;
$image = Zend_Pdf_Image::imageWithPath($imagePath);
$page->drawImage($image, 40,764,240, 820);
.
.
.
$pdf->pages[] = $page;
$pdf->save("mydoc.pdf");
}
There's no error in it. It generates PDF with image but the PDF document is saved in magento folder instead in My downloads folder. After doing some research, I found some following chunk of lines and added them after $pdf->pages[] = $page;.
$pdfString = $pdf->render();
header("Content-Disposition: attachment; filename=myfile.pdf");
header("Content-type: application/x-pdf");
echo $pdfString;
Now it generates PDF in My Downloads folder. When I try to open it. It throws error saying : Adobe reader couldn't open myfile.pdf because it's not either a supported file type or because the file has been damaged............ Do this happens,when we try to open PDF document generated on localhost or there's some other reason. Please let me know, why this error occurs and also provide me a solution to resolve it.
your problem is probably due to calling both save() and render() together.
save() actually calls render(), the issue could be due to trying to render the PDF twice.
This is also a waste of resources, if you need to save the file it's probably best to just save the file first, and then serve this file directly to the user.
You can do this in plain old PHP (using passthru or readfile), although there's ways to do this inside Zendframework which are better you can look into :)
// .. create PDF here..
$pdf->save("mydoc.pdf");
$file = 'mydoc.pdf';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
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;
}
?>
if your code is inside a Magento Controller:
$this->getResponse()
->setHttpResponseCode(200)
->setHeader('Pragma', 'public', true)
->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true)
->setHeader('Content-type', $contentType, true)
->setHeader('Content-Length', filesize($file))
->setHeader('Content-Disposition', 'attachment; filename="'.$fileName.'"')
->setHeader('Last-Modified', date('r'));
$this->getResponse()->clearBody();
$this->getResponse()->sendHeaders();
$ioAdapter = new Varien_Io_File();
if (!$ioAdapter->fileExists($file)) {
Mage::throwException(Mage::helper('core')->__('File not found'));
}
$ioAdapter->open(array('path' => $ioAdapter->dirname($file)));
$ioAdapter->streamOpen($file, 'r');
while ($buffer = $ioAdapter->streamRead()) {
print $buffer;
}
$ioAdapter->streamClose();
exit(0);

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