Link to home
Get AccessLog in
Avatar of keith1001
keith1001Flag for United States of America

asked on

PHP - Force file to download - not working

I'm trying to force the download of a file instead of displaying it in a browser and the below code allows me to download the file, but seems not to get the full file.  I can not display any of the jpgs that I download.  Any ideas on what I have wrong?  Keep in mind images may be just one type of a download, as there could be .txt or .pdf etc...

<?php
$file="c:\upload_test\\robot-100_1.jpg"; //file location 
header("Content-Description: File Transfer"); 
header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.basename($file).'"'); 
header('Content-Length: ' . filesize($file));
header('Connection: close');
readfile($file);

?>

Open in new window

Avatar of Mukesh Yadav
Mukesh Yadav
Flag of India image

Remove line 7.

File is not downloading because you are saying browser that connection is closed. After receiving this header browser closes connection.
Avatar of keith1001

ASKER

Even if I remove line 7, same issue.

Also changed line 4 to :  image/jpg

It always appears the file is just a little smaller than what is suppose to be.
Means you are getting file smaller than it is actually?
ASKER CERTIFIED SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Link to home
membership
This content is only available to members.
To access this content, you must be a member of Experts Exchange.
Get Access
Then confirm that you file exists or not?
Are you sure there is nothing wrong with your source image?

The code you works perfectly when I tested it on my own image.
SOLUTION
Link to home
membership
This content is only available to members.
To access this content, you must be a member of Experts Exchange.
Get Access
Ray, your script works fine to download image files too in the version I posted above.
My script downloads but the image will not display.

I run Ray's script above and it works.
Dave, thanks.  I updated the older version recently and added better comments for my teaching library.  In most cases, either version would work correctly.
Sorry for the delay, and thanks again for your support and working code/answer.
You're welcome.