获取文件下载,而不是打开浏览器 [英] Getting a file to download instead of opening the browser

查看:158
本文介绍了获取文件下载,而不是打开浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用php构建的网站,有.kml文件,我希望用户在点击链接时能够下载,但是当前在浏览器中打开(类似于xml的)文件。我尝试调整.htaccess文件,但没有运气。



如何获取文件下载,而不是在浏览器中打开?

解决方案

为了强制浏览器下载文件,您必须设置HTTP Content-Disposition 标题到附件。有一个简单的方法来配置您的HTTP服务器,以将此标题添加到所有 .kml 文件和仅PHP方式。



1。配置Apache添加 Content-Disposition



将以下内容放入您的Apache配置或 .htaccess 文件内容包含您的 .kml 文件:

 < Files* .kml> 
标题集Content-Disposition附件
< / Files>

您需要启用此功能 mod_headers



2。使用PHP脚本作为将文件发送到浏览器的代理



Purpletoucan提出的仅PHP解决方案是不让浏览器直接访问该文件,但是使用PHP脚本来发送它。这样,您可以使用脚本控制HTTP头文件:

 <?php 
header('Content-处理:attachment; filename ='。basename($ path)。'');
readfile($ path);
?>

因此,我假设 $ path 服务器上文件的路径。如果根据URL中给出的查询参数确定路径,则应始终检查是否给定了现有文件,允许用户下载该文件,并将其放在正确的目录中。请注意,即使您将请求中指定的字符串与目录前缀,也可以包含 ../ 来访问其他目录中的文件。


I have a site built with php, there are .kml files that I would like the user to be able to download when they click on the link, but it current opens the (xml-like) file in the browser. I have tried adjusting the .htaccess file, but no luck.

How do you get a file to download, instead of opening in the browser?

解决方案

In order to force the browser to download the file, you have to set the HTTP Content-Disposition header to attachment. There is an easy way to configure your HTTP server to add this header to all .kml files and a PHP-only way.

1. Configure Apache to add the Content-Disposition header

Place the following in your Apache configuration or in a .htaccess file inside of the directory containing your .kml files:

<Files "*.kml">
    Header set Content-Disposition attachment
</Files>

You need mod_headers enabled for this to work.

2. Use a PHP script as a proxy for sending the file to the browser

The PHP-only solution as proposed by Purpletoucan would be to not let the browser access the file directly, but use a PHP script for sending it over the line. This way, you can control the HTTP headers with the script:

<?php
header('Content-Disposition: attachment; filename="' . basename($path) . '"');
readfile($path);
?>

Thereby, I assume that $path is the path to the file on your server. If you determine the path depending on a query parameter given in the URL, you should always check that an existing file is given, that the user is allowed to download it and that it is located inside the correct directory. Note that even when you prefix the string specified in the request with the directory, it could contain ../ to access files in other directories.

这篇关于获取文件下载,而不是打开浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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