Php 如何强制下载附件

Php 如何强制下载附件,php,wordpress,Php,Wordpress,我试图在WordPress中强制下载一个zip附件 $file_url = wp_get_attachment_url( $name->name ); header('Content-Type: application/zip'); header("Content-Transfer-Encoding: Binary"); header('Content-disposition: attachment; filename="test.zip"'); header("Content-Leng

我试图在WordPress中强制下载一个zip附件

$file_url = wp_get_attachment_url( $name->name );

header('Content-Type: application/zip');
header("Content-Transfer-Encoding: Binary");
header('Content-disposition: attachment; filename="test.zip"');
header("Content-Length: ".filesize( $file_url ));

readfile($file_url);

如果我回显
$file\u url
,它将输出正确的url。但是当我下载时,文件被破坏了。但是如果我手动将
$file\u url
设置为相同的url,则下载时文件不会损坏。有什么想法吗?

看起来一切正常,但我觉得
标题可能有问题('Content-disposition:attachment;filename=“test.zip”)。您可能有不同的文件名作为附件,并且
test.zip
是硬编码的。试着替换

header('Content-disposition:attachment;filename=“test.zip”)

标题(“内容处置:附件;文件名=\”.basename($file\u url)。“\”)


并使用
exit
after
readfile($file\u url)

如@H2Ooooo在回复中所述,不适用于URL。需要使用而不是获取路径

这起到了作用:

$file_path = get_attached_file( $name->name );

header('Content-Type: application/zip');
header('Content-Transfer-Encoding: Binary');
header('Content-disposition: attachment; filename="test.zip"');
header('Content-Length: '.filesize( $file_path ));

readfile($file_path);

URL与文件路径不同。使用文件路径。不是URL。但是如果我输入
$file\u URL=”http://domain.com/files/file.zip“
它可以工作。如果我回显
$file\u url
它会给出相同的url。您查看了返回的标题了吗<代码>文件大小
不适用于URL。似乎问题出在
文件大小
上!谢谢这是一个问题,因为它会告诉浏览器“我现在给你发送一个文件-它有0个字节长”,然后浏览器会说“好的-发送给我-谢谢-我已经收到了所有0个字节。再见”。如果您希望进度正常,您需要使用文件大小(如我所述,只需使用路径而不是URL),我会尝试,但请记住,当我将第一行更改为
$file\u URL=”时,此代码会起作用http://domain.com/files/file.zip“
。能否打印
wp\u get\u attachment\u url($name->name)检查您得到了什么?