Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

Force file download with php using header()

I want the user to be able to download some files I have on my server, but when I try to use any of the many examples of this around the internet nothing seems to work for me. I've tried code like this:

<?php

$size = filesize("Image.png");

header('Content-Description: File Transfer');
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename="Image.png"');
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: ' . $size);
readfile("Image.png");

I've even tried to use the most basic example I could find, like this:

<?php
header('Content-type: image/png');
header('Content-Disposition: attachment; filename="Image.png"');
readfile('Image.png');

When I've tested this I have removed all the other code I have and used an empty file with just this code to remove any faults created by external sources.

When I look in the console the file gets sent with the right headers i.e

'Content-Disposition: attachment; filename="Image.png"'

But the save dialog isn't displayed.

I've also tried with inline instead of attachment in the content disposition header but that didn't make a difference either, I've tested this in Firefox 8.0.1 Chrome 15.0.874.121 and Safari 5.1.1.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I’m pretty sure you don’t add the mime type as a JPEG on file downloads:

header('Content-Type: image/png');

These headers have never failed me:

$quoted = sprintf('"%s"', addcslashes(basename($file), '"\'));
$size   = filesize($file);

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $quoted); 
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...