简体   繁体   English

PHP:单击按钮下载文件?

[英]PHP: Download a file on button click?

I created a form, which, when a contained button is clicked, should open a download dialog to download a certain file. 我创建了一个表单,当单击一个包含的按钮时,该表单应打开一个下载对话框以下载某个文件。 The file is placed on the same server. 该文件放置在同一服务器上。

I tried: 我试过了:

header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=" . $file . '"'); 

Where $file is a local path + the file name, for example c:\\mypath\\myfile.xls. 其中$ file是本地路径+文件名,例如c:\\ mypath \\ myfile.xls。 This does not work though. 但是,这不起作用。 It offers me a file, but its not a valid file. 它为我提供了一个文件,但它不是有效的文件。 How else could I do that? 我还能怎么做?

Note: I wrote c:\\ because its still on my local machine for testing. 注意:我写了c:\\,因为它仍然在我的本地机器上进行测试。

Thanks! 谢谢!

Try this 尝试这个

header("Pragma: public", true);
header("Expires: 0"); // set expiration time
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=".basename($file));
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
die(file_get_contents($file));

I think file_get_contents() function is no longer work with PHP 5.0.3 我认为file_get_contents()函数不再适用于PHP 5.0.3

Try this : 尝试这个 :

$path = "http://www.example.com/files/";
$filename = "abc.gif";

header("Content-Type:image/gif");
header("Content-Disposition: attachment; filename=".$filename);
header("Cache-control: private");
header('X-Sendfile: '.$path);
readfile($path);
exit;

PHP runs in server side, you can not download the files in clients machine. PHP在服务器端运行,您无法在客户端计算机上下载文件。

Upload the files to server and then give that path for download. 将文件上传到服务器,然后提供下载路径。

Path must be refered from the site root...move the file ex: script path : C:/wamp/www/test.php file C:/script.js then: 必须从站点根目录引用路径...将文件移至以下位置:脚本路径:C:/wamp/www/test.php文件C:/script.js然后:

if(file_exists('../../user.js'))
{
    echo "OK";
}

Still a bad ideea.. 仍然是一个糟糕的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM