Not able to download a file in php. Filename passed through url - php

I am just a beginner with PHP. I am trying to download an image file when a url is clicked.
When I hardcode the filename it works, however when I try to download different image files based on the url clicked, it does not work. The code might explain it in a better way.
Code when a url is clicked
Download brochure
download.php
<?php
$var=$_GET['var'];
$filename=$var;
$filename = './img/Photo6.jpg'; // this works
//$filename = $var; // this does not work
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false); // required for certain browsers
header('Content-Type: image/jpeg');
header('Content-Disposition: attachment; filename="'. basename($filename) . '";');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;
?>
Kindly help.
Thanks.

when you use:
$_GET['var'];
You are expecting a url construct with an ? inside it:
./download.php?var=./img/Photo6.jpg
in your sample: var=./img/Photo6.jpg, tells to php the variable GET[var] will take the value ./img/Photo6.jpg
so, your different image files based on the url clicked, must have the
./download.php?var=XXX
structure to work. Be sure all your urls has that structure.

Related

PHP Download script not able to navigate to other page until Download finishes

I'm working on a video based website, I have to give the link to download video.
I used the below code and it is working fine.
if (file_exists($FileDownload)) {
$Basename = pathinfo($FileDownload, PATHINFO_BASENAME);
$mime = 'application/force-download';
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Type: ' . $mime);
header('Content-Disposition: attachment; filename="' . basename($Basename) . '"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
readfile("$FileDownload"); // push it out
exit();
}
$this->render(false);
it is forcefully downloading the file, It is written on my Controller action and i make the view render false.
Issue is when i click on download and file started downloading, i'm not able to navigate to other pages until the download finishes.
Thanks!
After lot's of efforts finally I got to know the answer.
CakePhp response file is the solution of my problem.
updated code
$FileDownload = base64_decode($FileDownload);
// Retrieve the file ready for download
$Basename = pathinfo($FileDownload, PATHINFO_BASENAME);
// Run any pre-download logic here.
// Send file as response
$this->response->file(
$FileDownload, array(
'download' => true,
'name' => $Basename
)
);
return $this->response;

Echo image through PHP

For an newsletter script I like to use an image to check if it is read or not. So we made an image like this in our script:
<img src="[url]/getEmailImage/test/">
When this url is triggered it registers that the mail is opened.
At the server side we use this meganism:
// register that the email is read
$this->modelOpslag->changeByToken($token,array('gelezen' => '1'));
// download image and show is
$image = base_url().'external/afbeeldingen/pixel.jpg';
$info = getimagesize($image);
header('Content-Type: '.$info['mime']);
echo file_get_contents($image);
exit;
When i remove the PHP header function is shows something like this:
����JFIF``��rExifMM*JR(1Z``paint.net 4.0.5��
etc...
With the header my browser gives the error: the image cannot be displayed, because is contains errors.
What did I do wrong?
-- EDIT --
I've got no solutions for this specific problem, but i found an alternative in case someone like to use this meganism for their newsletter witch works:
$file = './external/afbeeldingen/pixel.jpg';
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, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
If i understood your question correctly.. you are trying to echo the image, using echo we cannot display the image..
Why don't you use...
<img src="<?php echo file_get_contents($image); ?>" />
you need different headers for image download and for showing image dynamically. Also file encoding format of the php script can cause broken image data.

javascript - Default filename when saving from html2canvas or save as dialogue?

A friend of mine configured h2ml2canvas for me as I don't understand javascript. When saving using h2ml2canvas it generates a random filename e.g.
df0e604b2962492165eb8f2b31578171
Is there a way to specify a filename prefix? e.g. soccer then generate a random 3-4 digit number? Alternatively is there a way to open a save as dialogue instead of downloading an image on click? My download.php file.
<?php
$file = trim($_GET['path']);
// force user to download the image
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: image/png');
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);
unlink($file);
exit;
}
else {
echo "error not found";
}
?>
The filename in your case is actually generated (or not) by the PHP server-side, not the JavaScript you've quoted. When it returns the data to send back, it's including a Content-Disposition header, probably one that looks like this:
Content-Disposition: attachment
It's possible to suggest a filename to the browser by adding to that header:
Content-Disposition: attachment; filename=soccer123.xyz
In the PHP somewhere, you should find:
header("Content-Disposition", "attachment");
or similar. You can change it to:
header("Content-Disposition", "attachment; filename=soccer-" . rand(100,999) . ".xyz");
(Probably best to make the .xyz an appropriate extension for the type of image, e.g. .png or .jpg...)
Re your edit, you can replace:
header('Content-Disposition: attachment; filename='.basename($file));
with
header('Content-Disposition: attachment; filename=soccer-'.rand(100,999).'.xyz');
again you'll want a correct extension instead of .xyz.

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);

Trying to generate a php download link. Name of file will not set

Hello I am trying to generate a php powered download link for my program, I had copied and pasted some old code I had laying around which worked in the past, and it still seems to work okay except for 2 issues.
Issue 1: No matter what it always download the file as link.php not the filename
Issue 2:The filesize isn't sent to the browser(not really that concerned about this)
Mainly I need to know what I am doing wrong in setting the filename, here is my code below:
$file = $_GET['file'].'.exe';
if ($_GET['DL'] == "GO") {
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false); // required for certain browsers
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'. basename('MIRROR/'.$file) . '";');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize('MIRROR/'.$file));
ob_clean();
flush();
readfile('MIRROR/'.$file);
die();
}
Try taking out the trailing ;:
header('Content-Disposition: [..snip...] . basename($file) . '";');
^--- here

Categories