Image file download problem - php

I am facing problem in downloading any image file from the server.
I am able to upload them successfully and can open them from the location where they are uploaded and stored.
When i download using my function the image files get downloaded fully, file size is also correct but when i open them i get an error No image preview !!!
$fileString=$fileDir.'/'.$fileName; // combine the path and file
// translate file name properly for Internet Explorer.
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
{
$instance_name = preg_replace('/\./', '%2e', $instance_name, substr_count($instance_name, '.') - 1);
}
// make sure the file exists before sending headers
if(!$fdl=#fopen($fileString,'r'))
{
die("Cannot Open File!");
}
else
{
header("Cache-Control: ");// leave blank to avoid IE errors
header("Pragma: ");// leave blank to avoid IE errors
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$instance_name."\"");
header("Content-length:".(string)(filesize($fileString)));
sleep(1);
fpassthru($fdl);
}
I am using IE as browser.
I am using this code snippet to download the file and not to show on the browser. The script executes and i get prompted on whether i want to open / save the file. When i save the file the size is also correct but the image doesn't show up. When i right click and see the summary of the file, it says the summary is unavailable.
Thanks in advance. Kindly help.

It's not clear from your code, are you using this PHP snippet to serve the image on a web page, such as:
<img src="my-php-script.php" alt="blah blah blah" />
If so, your content-type is incorrect. You would need to use an image MIME type, such as image/gif, image/jpeg, image/png or image/tiff, whichever is most appropriate.

This line: header("Content-type: application/octet-stream"); seems fishy to me. You might want to try giving the actual mime type and see if that helps

The problem is with the MIME type. Please have a look here:
http://www.daniweb.com/forums/thread122055.html
This is if you want to view images in the browser.
If you want to download them as binaries then leave your mime type.
Also please change file open mode from "r" to "rb"

Related

Creating simple button for .mp3 file download (no right-click, no media player)

I'm sure this is a simple task, but on my wordpress site I want to create a download button that forces an .mp3 download, without opening a player (when left clicked), or the user having to right-click 'save target as'. I just need a straight forward button, that when left-clicked causes a file to be downloaded (as well as being easily trackable by Google Analytics).
Is a .php script required for this? You'd think this would be a very common function, and easy to solve....but I have spent hours on this and have been unable to get anything to work.
*if it's not obvious my coding skills are nearly non-existent.
I really appreciate anybody's time who can help me figure this out. Thanks!
***EDIT
Just found this on another post, but no comments if it would work or not. It was for a .pdf file though...
<?php
if (isset($_GET['file'])) {
$file = $_GET['file'] ;
if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) {
header('Content-type: application/pdf');
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($file);
}
} else {
header("HTTP/1.0 404 Not Found");
echo "<h1>Error 404: File Not Found: <br /><em>$file</em></h1>";
}
?>
Save the above as download.php
Save this little snippet as a PHP file somewhere on your server and you can use it to make a file download in the browser, rather than display directly. If you want to serve files other than PDF, remove or edit line 5.
You can use it like so:
Add the following link to your HTML file.
Download the cool PDF.
Well, this is possible, but you need to write a script to do it. This is a pretty poor (security and basic coding wise) from http://youngdigitalgroup.com.au/tutorial-force-download-mp3-file-streaming/
file: downloadit.php
<?php
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file.";");
header ("Content-Length: ".filesize($file));
readfile($file);
exit;
?>
you would then place it into a publicly accessible folder and build your links as such:
http://www.yoursite.com/downloadit.php?file=/uploads/dir/file.mp3
what this does is tells the browser to treat the file as a stream of bytes, rather than a particular MIME type which the browser would ordinarily do based on the file extension.

How to force the proper file extension in the "save as" dialog? (.jpg instead of .php)

To password protect the website images, I access them through PHP.
Intead of using the url "meme_penguin.jpg" I use "image.php?file=penguin".
This works great for displaying it, except when the user try to "save as".
In chrome the "save as" dialogue will suggest the file type as PHP instead of JPG
In internet explorer it will suggest BMP
Obviously the user can just change the file type and rename the file. However this is not an elegant solution and will cause problems for sure.
How can we make it automatically "save as" with the proper extension, JPG? Is there an alternative way? - Many thanks!!
Found it! I was missing the third line of code.
You can use this to display a secure image in your page, or download it as jpg
Got the first two lines from another question in stackoverflow
//need this two lines to work properly on IE8
header("Pragma: ");
header("Cache-Control: ");
//was missing this line
header('Content-Disposition: attachment; filename="renamed.jpg"');
header("Content-Type: image/jpeg");
echo file_get_contents("images/somepic.jpg");
from php.net
Set the content-type header to proper value in response
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
14.17 Content-Type
header('Content-Type: image/jpeg');

Link to a PDF in html, the file has no extension, but I know it is pdf how to make it open appropriately

First post. I'm working on a project for a client where they have pdf files uploaded to a file structure (LAMP Stack) but the files have no extensions on them. Under the assumption that those files have to be PDF how would I get the browsers to understand that, and open them accordingly? Obviously with adding the file extensions this would suddenly work but I can't change the way their system works, it would result in too many changes and they are on a tight deadline. As for saving a temporary copy somewhere, I could do that, but I was hoping for a better solution. Is there a way to suggest to the browsers that they open a file a certain way?
Any thoughts guys/gals?
You just set the application type and file name in the headers, like so:
// This points to the file in question, note that it doesn't
// care whether it has an extension on the name or not.
$filePathOnDisk = '/path/to/your/pdffile';
// You can make this whatever you like, it doesn't have to
// be the same as the file name on the disk! This is the name of the file your end
// user will see when they are asked if they want to save. open, etc in the browser.
$fileName = 'file.pdf';
$data = file_get_contents($filePathOnDisk);
header("Content-type: application/pdf");
header("Content-disposition: attachment;filename=$fileName");
echo $data;
See PHP: stream remote pdf to client browser and Proper MIME media type for PDF files for reference as well.
Tested
You can use the following which will prompt the user to save the (PDF) file on their computer.
Notice the different file names.
One is the file that will be uploaded/prompted to the user download_example.pdf, while the other is the file without an extension as set in readfile('example');
<?php
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="download_example.pdf"');
readfile('example');
?>

'Save As' image with src from PHP

I'm currently displaying images and hiding the src code by having a php file output the image. But when I right click on the image displayed and go down to 'Save As' it prompts me to download the php file not the actual image (obviously because it points to that src).
What can I do to download the actual image instead of displayImage.php?
It doesn't prompt you to download the PHP file, it simply uses that as the file name, because that is the file name from which it got the image data. If you manually input a valid image file name and try to open what you saved, it should still be a valid image.
You may also be able to give it a sensible name by including the file name in a Content-Disposition: header from your PHP file, e.g.
$filename = 'image.jpg';
header('Content-Disposition: inline; filename="'.$filename.'"');
// Don't forget the Content-Type as well...
// Output image here
...however this relies on the browser handling this sensibly, which not all of them do :-(
You can send a filename in the header.
header("Content-Type: image/png");
header('Content-Disposition: inline; filename="some.png"');
Send the correct content type in the image generator script:
header('Content-type: image/jpg');
If you want to have the .jpg extension when a PHP script is outputting an image, you'll need to do a htaccess or httpd.conf rewrite, where you can rewrite a .jpg request, to your php image generator script.
See mod_rewrite http://httpd.apache.org/docs/current/mod/mod_rewrite.html

How to force a file to download in PHP

I have list of images and I want a "Download" link along with every image so that user can download the image.
so can someone guide me How to Provide Download link for any file in php?
EDIT
I want a download panel to be displayed on clicking the download link I dont want to navigate to image to be displayed on the browser
If you want to force a download, you can use something like the following:
<?php
// Fetch the file info.
$filePath = '/path/to/file/on/disk.jpg';
if(file_exists($filePath)) {
$fileName = basename($filePath);
$fileSize = filesize($filePath);
// Output headers.
header("Cache-Control: private");
header("Content-Type: application/stream");
header("Content-Length: ".$fileSize);
header("Content-Disposition: attachment; filename=".$fileName);
// Output file.
readfile ($filePath);
exit();
}
else {
die('The provided file path is not valid.');
}
?>
If you simply link to this script using a normal link the file will be downloaded.
Incidentally, the code snippet above needs to be executed at the start of a page (before any headers or HTML output had occurred.) Also take care if you decide to create a function based around this for downloading arbitrary files - you'll need to ensure that you prevent directory traversal (realpath is handy), only permit downloads from within a defined area, etc. if you're accepting input from a $_GET or $_POST.
In HTML5 download attribute of <a> tag can be used:
echo '<a href="path/to/file" download>Download</a>';
This attribute is only used if the href attribute is set.
There are no restrictions on allowed values, and the browser will
automatically detect the correct file extension and add it to the file
(.img, .pdf, .txt, .html, etc.).
Read more here.
The solution is easier that you think ;) Simple use:
header('Content-Disposition: attachment');
And that's all. Facebook for example does the same.
You can do this in .htaccess and specify for different file extensions. It's sometimes easier to do this than hard-coding into the application.
<FilesMatch "\.(?i:pdf)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
By the way, you might need to clear browser cache before it works correctly.

Categories