如何使用 PHP 强制下载文件 [英] How to force file download with PHP

查看:32
本文介绍了如何使用 PHP 强制下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要求在用户使用 PHP 访问网页时下载一个文件.我认为它与 file_get_contents 有关,但我不确定如何执行它.

I want to require a file to be downloaded upon the user visiting a web page with PHP. I think it has something to do with file_get_contents, but am not sure how to execute it.

$url = "http://example.com/go.exe";

下载带有 header(location) 的文件后,它不会重定向到另一个页面.它只是停止.

After downloading a file with header(location) it is not redirecting to another page. It just stops.

推荐答案

阅读关于内置 PHP 函数的文档 读取文件

Read the docs about built-in PHP function readfile

$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename="" . basename($file_url) . """); 
readfile($file_url); 

还要确保根据您的文件应用程序/zip、应用程序/pdf 等添加正确的内容类型 - 但前提是您不想触发另存为对话框.

Also make sure to add proper content type based on your file application/zip, application/pdf etc. - but only if you do not want to trigger the save-as dialog.

这篇关于如何使用 PHP 强制下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆