PDF file download error PHP - php

I have used below code for downloading my pdf file in PHP.
my problem is when i download file it display error File type HTML document (text/html) is not supported. if i download direct from server it can be open. Please solve my issue.
$path = "";
if (is_readable ($Path)) {
$fsize = filesize($Path);
$path_parts = pathinfo($Path);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf"); // add here more headers for diff. extensions
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
break;
default:
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
readfile($Path);
} else {
die("Invalid request");
}

Your code seems correct apart from one mistake.
PHP variables are case sensitive.
Correct your $path variable to $Path.
And also cross check the directory and file permission.

Related

PHP: Download file from Server

I have tried all sorts of codes I've found but nothing has worked for me...
When I use readfile() or fopen() or something like this:
function makeDownload($file, $dir, $type) {
header("Content-Type: $type");
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($dir.$file);
}
... A download is started but the file is always empty...
here's the last code I've tried:
$filename = "gandalf.jpg";
// define error message
$err = '<p style="color:#990000">Sorry, the file you are requesting is unavailable.</p>';
if (!$filename) {
// if variable $filename is NULL or false display the message
echo " filename NULL";
echo $err;
} else {
// define the path to your download folder plus assign the file name
$path = 'upload/'.$filename;
// check that file exists and is readable
if (file_exists($path) && is_readable($path)) {
echo "file exists";
// get the file size and send the http headers
$size = filesize($path);
header('Content-Type: image/png');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
// open the file in binary read-only mode
// display the error message if file can't be opened
//readfile($path.$filename);
$file = # fopen($path, 'rb');
if ($file) {
// stream the file and exit the script when complete
fpassthru($file);
exit;
} else {
echo $err;
}
} else {
echo $err;
}
}
This is the source of my code: Source code
I hope you can help me :)
I use google chrome
I need your help for this little project: Link to Project
When you click on a file in the drop down appears "herunterladen" (download in german) here is where I want to start the php download code
I just need the most basic download function for PHP... why is there an upload example on w3schools but NOT a download example? oO
$fileSource= $_GET['fileSource']; //If you are passing the filename as a URL parameter
$fileSource= "sample.pdf" //If the filename is fixed in the current folder
if($fileSource) {
$filesize = filesize($fileSource);
$path_parts = pathinfo($fileSource);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-Disposition: attachment;
filename=\"".$path_parts["basename"]."\""); // use 'attachment' to
force a download
header("Content-type: application/pdf"); // add here more headers
for diff. extensions
break;
default:
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
if($filesize) {
header("Content-length: $filesize");
}
readfile($fileSource);
exit;
}

Need to refresh the page to see the download

I'm trying to download a simple text file from my server to the client in php. Unfortunately, when i try to download, a new white page appear and the download isn't ask to the user. But, if i refresh the page, the download is now ask and the user can accept to download the file like usual. Do anyone know why?
P.S. If anyone knows about how not opening another blank page to show the download and just show it on the page i clicked the link, any information would be appreciated.
Here is the code :
HTML
Download file
PHP
<?php
ignore_user_abort(true);
set_time_limit(0); // disable the time limit for this script
$path = "toDownload/"; // change the path to fit your websites document structure
$dl_file = $_GET['download_file']; // simple file name validation
$fullPath = $path.$dl_file;
if ($fd = fopen ($fullPath, "r"))
{
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext)
{
case "txt":
header("Content-type: application/txt");
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: public"); //use this to open files directly
while(!feof($fd))
{
$buffer = fread($fd, 2097152); // 2097152 Octet = 2Mo
echo $buffer;
}
}
fclose ($fd);
exit;
?>

(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

File download script not working after changing from WAMP server to LAMP server.

I moved my application from a WAMP server (PHP version <= 5.2, Windows XP) to a LAMP server (PHP > 5.3, Ubuntu 12.04 LTS), and the problem that I have now is that my download function outputs the file on the screen and it's not forcing the browser to perform a download.
Anyone can point me in the right direction?
Here's the code:
function download()
{
$fullPath = $_POST['fisier'];
if($fullPath=="NULL")
{
echo "Wrong path!";
}
else
{
$fd = fopen ($fullPath, "r");
if ($fd) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
break;
case "tiff":
header("Content-type: image/tiff");
break;
case "tif":
header("Content-type: image/tiff" );
break;
default:
header("Content-type: application/force-download");
break;
}
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="'.$path_parts["basename"].'"');
header("Content-length: ".$fsize);
header("Cache-control: private"); //use this to open files directly
ob_clean();
flush();
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
}
}
You can use the Content-Disposition header as per the PHP docs:
If you want the user to be prompted to save the data you are sending,
such as a generated PDF file, you can use the ยป Content-Disposition
header to supply a recommended filename and force the browser to
display the save dialog.
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
try using header("Content-type: application/octet-stream"); instead of header("Content-type: application/force-download");
The recommended action for an implementation that receives an
"application/octet-stream" entity is to simply offer to put the data
in a file
From here. Looks like your application/force-download is non standard.

Php code to download pdf file from server not working

I have written a code to download pdf file from server, but the code is not working and I cant even see the errors
This is the code which I am using.
// place this code inside a php file and call it f.e. "download.php"
$path = $_SERVER['DOCUMENT_ROOT']."/product_images/"; // change the path to fit your websites document structure
fullPath = $path.$_REQUEST['download_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"); // add here more headers for diff. extensions
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
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;
// example: place this kind of link into the document where the file download is offered:
// Download here
?>
I am fetching the file from database and this is my download link which I am using on my site
<div style="padding-left:320px; padding-top:5px;"><a href="<?php echo URL ?>download.php?download_file=<?php echo $prod_details['specification_pdf']?>">
<img src="<?php echo URL ?>images/download_pdf.png" /></a></div>
</div>
Can anyone please help me in resolving this problem
As say #lasar missing $ in line 2 could be the problem.
I adapt (and test) your code to be more secure (see basename) and direct (see readfile):
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/product_images/"; // change the path to fit your websites document structure
$fullPath = $path.basename($_REQUEST['download_file']);
if (is_readable ($fullPath)) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf"); // add here more headers for diff. extensions
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
readfile($fullPath);
exit;
} else {
die("Invalid request");
}
// example: place this kind of link into the document where the file download is offered:
// Download here
ADD
see readfile manual page for a good explanation of headers to
download files
REMEMBER due it's nature PHP is well know to damage binary file download, remeber to keep <?php always in 1st line and avoid close tag ?> in PHP-only files

Categories