我想在用户用PHP访问一个网页时要求下载一个文件。我想这与file_get_contents有关,但不确定如何执行。
file_get_contents
$url = "http://example.com/go.exe";
用header(location)下载完一个文件后,没有重定向到另一个页面。它只是停止了。
header(location)
阅读关于内置PHP函数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); // do the double-download-dance (dirty but worky)
还要确保根据你的文件的应用/zip、应用/pdf等添加适当的内容类型。- 但前提是你不想触发另存为对话框。
header("Content-Type: application/octet-stream"); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"file.exe\""); echo readfile($url);
是正确的
或者更好的是用于exe类型的文件
header("Location: $url");
<?php $file = "http://example.com/go.exe"; header("Content-Description: File Transfer"); header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"". basename($file) ."\""); readfile ($file); exit(); ?>
或者,当文件无法用浏览器打开时,你可以直接使用Location头。
Location
<?php header("Location: http://example.com/go.exe"); ?>
阅读关于内置PHP函数readfile的文档。
还要确保根据你的文件的应用/zip、应用/pdf等添加适当的内容类型。- 但前提是你不想触发另存为对话框。
是正确的
或者更好的是用于exe类型的文件
或者,当文件无法用浏览器打开时,你可以直接使用
Location
头。