I've successfully implemented some PHP to download an image:
PHP:
<?php
$image = "path/to/image.jpg"
header('Content-disposition: attachment; filename=image.jpg');
header('Content-type: image/jpeg');
readfile($image);
?>
Here is an example image that I've saved to my server: http://www.thenally.com/work/php-tests/header/files/herzog.jpg
If I view the image in the browser, then right-click to save, it acts as a typical image on my local Windows box (ie. viewable in Windows Photo Viewer). When I download the image using the PHP script above, the image can't be viewed in the same way, although the filesize is accurate and I can open it in Photoshop. I don't know much about image encoding/decoding etc but obviously the file changes when I download using the method above.
EDIT:
The Windows Photo Viewer error is as follows:
"Windows Photo Viewer can't open this picture because either Photo Viewer doesn't support this file format, or you don't have the latest updates to Photo Viewer".
There are no PHP errors in my log file, but this came up in my Chrome console:
"Resource interpreted as Document but transferred with MIME type image/jpeg: "http://thenally.com/work/php-tests/header/index.php".
try this
header('Content-Transfer-Encoding: binary');
I ran a similar issue and managed to fix it by removing any blank space/new lines between PHP tags.
Basically had to do this:
<?php
//stuff
?>
--REMOVE THIS SPACE--
<?php
//stuff
?>
Just make sure you do not have any blank spaces before any PHP tags and you should be good!
Related
Im trying to get a website to have a button that forces a download of a pdf.
Heres the html of the button:
<a href=scripts/download.php>
<input type="image" src="images/download.gif" alt="Submit button"/>
</a>
And the php script so far:
<?php
header('Content-Type: application/pdf');
header('Content-disposition: attachment;filename=documents/ECM_IT_ResumeDownload.pdf');
readfile('documents/ECM_IT_ResumeDownload.pdf');
?>
This seems to download the file fine but when I go to open it i get this error:
"Adobe Reader could not open 'documents_ECM_IT_ResumeDownload.pdf' because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded)."
Any help would be greatly appreciated.
EDIT
Opened the pdf in a text editor and got this message:
"
Warning: readfile(documents/ECM_IT_ResumeDownload.pdf) [function.readfile]: failed to open stream: No such file or directory in html/scripts/download.php on line 4
"
The document is definitely there though. in html/documents/ECM_IT_ResumeDownload.pdf
$file_url = www.example.com/pdffolder/$pdfname;
header('Content-Type: application/pdf');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=".$pdfname);
readfile($file_url);
Try removing the path to the file and just leave the file name in the content:
header('Content-Type: application/pdf');
header('Content-disposition: attachment; filename=ECM_IT_ResumeDownload.pdf');
Have you tried getting rid of the closing PHP tag (the ?>) at the end? It will treat the page as a pure PHP page, removing any possible new lines that might accidentally get appended to the end of the output. This helped me when I was dynamically creating excel files for download, and they were downloading as corrupted. Check out this page for more information:
http://www.php.net/manual/en/language.basic-syntax.phptags.php
From your edited question, it seems like PHP is unable to find the file. Try using an absolute path to the file like so: "c:\blah\de\blah\bloo.pdf" or "c:/blah/de/blah/bloo.pdf". If one of those paths works and downloads correctly, your relative path is incorrect in some way.
I always use Gowon Patterson's download script, it also has hotlink protection:
http://by.gowondesigns.com/getfile/
By the way, a bit late, but to identify the problem properly here:
Your download script is at scripts/download.php and the file you want to download is at documents/[...].pdf.
Therefore, your readfile() function should be traversing to the parent directory (outside of scripts/), e.g. readfile('../documents/[...].pdf');.
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
well I'm just wondering how I can get an mp3 download to start instantly, as oppose to it simply starting to play in the browser when you directly go to it.
Preferably using php headers.
So essentially when you click the file, I want a download box to appear saving save etc. Right now it just opens and starts playing in the browser.
Thanks
You'll need to create a PHP file that "redirects" to the MP3 file, and point your links to that PHP file.
Code as below:
<?php
header('Content-type: audio/mpeg');
header('Content-Disposition: attachment; filename="fileName.mp3"');
readfile('originalFile.mp3');
?>
Note: The line that sets the Content-Disposition header is the critical one.
I am trying to get my php video handler file to serve up videos and am testing it on the file handler page itself without luck.
Weird behaviour: A window just pops up asking me if I want to download the file, even if I delete the readfile(). If I change video/x-flv to video/flv then a player loads in my window but the file does not play. Also if I take away that header all together my browser crashes.
I figured this script should place the video in the browser at the least and have it be playable in the browser if I am testing the file directly with the browser. The file path is correct after the query... Also the file is outside of my web directory but I don't think that should matter because I can serve images outside the directory successfully using a similar script. Anyone have any ideas?
$sql="SELECT file_name FROM video WHERE vid_id=?";
$stmt=$conn->prepare($sql);
$result=$stmt->execute(array($ID));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$file_name = $row['file_name'].".flv";
}
$path="/home/g/Desktop/processed/".$file_name."";
//check if image is readible and type
if (is_readable($path)) {
header('Content-Length: '.filesize($path)); // provide file size
header("Expires: -1");
header('Content-Type: video/x-flv');
$content=readfile($path);
}
else {
error_log("Can't serve video: $file_name");
}
Streaming doesn't work like that.
To have a proper streaming you need to use a Player like: http://flowplayer.org/
If you just send the content of the video, the browser will pop up the save dialog
I was unable to use php to pass videos to OS player. I switched to flow player and things are working.
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"