downloading file in PHP - php

I'm trying to create a temporary download link for download files.
my code is:
$file_temp_adrs = "temp/".md5(microtime());
mkdir($file_temp_adrs);
$file_temp_adr = $file_temp_adrs."/".$fileinfo['org_filename'];
$file_org_adr = "files/".$fileinfo['filename'];
copy($file_org_adr , $file_temp_adr);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $file_temp_adr);
finfo_close($finfo);
$name = basename($file_temp_adr);
$size = filesize($file_temp_adr);
header("Content-Disposition: attachment; filename=\"".$name."\"");
header("Content-Type: $mime_type");
header("Content-Length: $size");
header("Connection: close");
When i click on download button, the browser saves a file with true name and extention but the file size is 0KB that is not usable.
where is wrong?

I think you do not actually deliver the file content and you should output the file content using readfile:
readfile($file_temp_adr);

Related

HTTP header file not downloaded completely

I am trying to download the file with http header but it will not download completly. The uploaded file size is 1 MB and the file download with my code 336 byte size only.
I am trying with below code
$attachment_location= "filename";
$filePath= "$siteURL/foldername/filename";
$file_content = file_get_contents($filePath);
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$attachment_location\"");
echo $file_content;
I have solved this issue by just changing the filepath remove the path with SiteURL and provide the path from folder. Check code below,
$attachment_location= "filename";
$filePath= "foldername/filename";
$file_content = file_get_contents($filePath);
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$attachment_location\"");
echo $file_content;

(PHP) Save file in folder to computer

I'm using PHP (PHPExcel) to handle all the excel files.
Currently I have saved a "New Template.xlsx" in a folder. And now I want the users to be able to download the "New Template.xlsx" at a click of a button.
How do i do that with php or phpexcel (i'm using Yii PHP framework as well)?
I'm not sure how to start, all I have now is
$filePath = Yii::app()->basePath . '\\vendors\\Excel Template\\New Template.xlsx';
Yii::import('application.vendors.PHPExcel', true);
$objPHPExcel = PHPExcel_IOFactory::load($filePath);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
Edit
Thanks to Miqi180's comments, I'm now able to download the excel file, however I am unable to open it because of invalid file extension/file format.
Here are my codes:
<?php
ignore_user_abort(true);
set_time_limit(0); // disable the time limit for this script
//$path = "/absolute_path_to_your_files/"; // change the path to fit your websites document structure
$path = Yii::app()->basePath . '\\vendors\\Excel Template\\';
//$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\].]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\].]|[\.]{2,})", '', 'NewTemplate.xlsx'); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$dl_file;
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "xlsx":
//header("Content-type: application/vnd.ms-excel");
header("Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
break;
// add more headers for other content types here
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
Stop Yii from sending its own headers and output
Send the appropriate headers for an xlsx file
Save the file to php://output
Look at some of the examples in the PHPExcel Examples folder like 01simple-download-xlsx.php
But unless you're changing the template between loading it and sending it to the user, there's no need to use PHPExcel for this
Basically, what you need to do is execute a php script which fires when another page is loaded, e.g. "download.php" and then send the file through the header commands in that script.
Complete working code example taken from here:
<?php
ignore_user_abort(true);
set_time_limit(0); // disable the time limit for this script
$path = "/absolute_path_to_your_files/"; // change the path to fit your websites document structure
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\].]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$dl_file;
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
break;
// add more headers for other content types here
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
However, you need to set the content-type correctly first (see this post).
from
header("Content-type: application/pdf");
to
header("Content-type: application/vnd.ms-excel");
or for For Excel2007 and above .xlsx files
header("Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
Edit:
According to this MSDN blog article, the correct Extension MIME type for Excel .xlsx files actually is:
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

PHP Header download PDF

I've made a page where you can go and write text in a "textarea" and then when you click download you download that file as a .txt file. I've done the same thing to some other extensions and that is working fine. But it won't work with .PDF, nothing I read works. Here is the snippet I use for the .PDF downloading:
<?php
if($fileFormat == ".pdf"){
$content = $_POST['text'];
$name = stripslashes($_POST['name']);
$nameAndExt = $name.".pdf";
print strip_tags($content);
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="'.$nameAndExt.'"');
header('Content-Transfer-Encoding: binary ');
}
?>
I'm grateful for any answear, thanks!
// hold the filename for use elsewhere so you don't have to append .pdf every time
$filename = "$id.pdf";
// create the file
$pdf->output( $filename );
// set up the headers
header("Content-Description: File Transfer");
header("Content-disposition: attachment; filename={$filename}");
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
header('Content-Length: ' . filesize($file));
// push the buffer to the client and exit
ob_clean();
flush();
// read the file and push to the output stream
readfile( $filename );
// remove the file from the filesystem
unlink( $filename );
exit();
I would recommend a class like TCPDF, see http://www.tcpdf.org/. I used it couple of times and it's quite nice (open source).

download image from another server url without saving in my server folder

I have problem in download image from url,
$url = 'http://example.com/image.php';
$img = '/my/folder/flower.gif';
file_put_contents($img, file_get_contents($url));
in this code file is saving in my server folder .but i needed without saving in my server it needs to be download to user.
set the correct header and echo it out instead of file_put_contents
$url = 'http://example.com/image.php';
header('Content-Disposition: attachment; filename:image.jpg');
echo file_get_contents($url);
Use application/octet-stream instead of image/jpg:
If [the Content-Disposition] header is used in a response with the application/octet-stream content-type, the implied suggestion is that the user agent should not display the response, but directly enter a `save response as...' dialog.
— RFC 2616 – 19.5.1 Content-Disposition
EDIT
function forceDownloadQR($url, $width = 150, $height = 150) {
$url = urlencode($url);
$image = 'http://chart.apis.google.com/chart?chs='.$width.'x'.$height.'&cht=qr&chl='.$url;
$file = file_get_contents($image);
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=qrcode.png");
header("Cache-Control: public");
header("Content-length: " . strlen($file)); // tells file size
header("Pragma: no-cache");
echo $file;
die;
}
forceDownloadQR('http://google.com');
if you want to download the file onto your webserver(and save it), just use copy()
copy($url, 'myfile.png');

Cannot download pdf using ipad

I am using the following function to download pdf file it is working fine when i download it from PC or laptop but when i click on download link using ipad it opens a page with lots of special chracters and I am unable to download the file.
My download function is
public function download() {
$download_path = $_SERVER['DOCUMENT_ROOT'] . "/import";
$filename = $_GET['file'];
$file = str_replace("..", "", $filename);
$file = "$download_path/$file";
if (!file_exists($file))
die("Sorry, the file doesn't seem to exist.");
$type = filetype($file);
header("Content-type: $type");
header("Content-Disposition: attachment;filename=$filename");
header('Pragma: no-cache');
header('Expires: 0');
readfile($file);
}
Any idea about this error ?
This is probably the issue:
$type = filetype($file);
header("Content-type: $type");
From the manual
Possible values are fifo, char, dir, block, link, file, socket and
unknown.
Which are not things you want to see in the header. You are probably looking for:
header('Content-type: application/pdf');
You probably want finfo_file() and not filetype().

Categories