How to make images are send inline while any other file is send as an attachment?
I have a simple question. I was looking for function to download file. I have found one but I have small problem.
First, this is some codes of function:
header ('Content-type: ' . mime_content_type($file));
header ('Content-Disposition: attachment; filename="'.basename($file).'"');
header ('Expires: '.gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y"))).' GMT');
header ('Accept-Ranges: bytes');
header ('Cache-control: no-cache, must-revalidate');
header ('Pragma: private');
To test function I am using this:
$file = 'path/file.rar';
dowload_file($file);
It’s working fine and file is getting downloaded. But if I use the function for image, for example:
$file = 'path/image.jpg';
download_file($file);
Then the image is also getting downloaded. But I want it to be viewed and not downloaded.
If I delete this line:
header ('Content-Disposition: attachment; filename="'.basename($file).'"');
the image is showed immediately but the rar and zip files is stopped being downloade开发者_如何学编程d.
So how to make images being displayed without downloading but any other file being downloaded? I am testing on localhost, may be this is the problem?
If you have the Content-Disposition
header set to attachment
, it will force a download regardless of file type.
If you want your images to be handled differently, you'll have to include a conditional on the Content-Disposition
header, like:
if (!preg_match('@\.(gif|jpe?g|png)$@', basename($file)) {
// this is *not* an image, do C-D: attachment header
header ('Content-Disposition: attachment; filename="'.basename($file).'"');
} // otherwise do nothing
You have to put a conditional statement on the files that can be viewed in browser and that should be downloaded. For images and xml files you can provide condition not to use content dispostion as attachment. For others include it.
You can try switching based on file types. If you take the extension of the file:
$ext = pathinfo($file, PATHINFO_EXTENSION);
Then you can whitelist your images as so:
if($ext != 'gif' && $ext != 'jpg' && $ext != 'png' && $ext != 'jpeg')
{
header ('Content-Disposition: attachment; filename="'.basename($file).'"');
}
Or, alternatively whitelist your downloads:
if($ext == 'rar')
{
header ('Content-Disposition: attachment; filename="'.basename($file).'"');
}
I am testing on localhost, may be this is the problem?
Nope. Not localhost but logic is your problem.
If you want to display an image, you heed a function that displays an image, not downloads a file. That's different tasks.
In fact, to display an image the only header you have to send is proper content-type one.
精彩评论