Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

php - Getting a file to download instead of opening the browser

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are two different approaches depending in your scenario.

If your KML files are static and you are serving them directly without PHP then you should look at configuring the .htaccess file appropriately and ensuring that your web server is configured to observe .htaccess files.

If your KML files are dynamic or are being proxied by a PHP script then you need to serve the right headers to force a download. The header to encourage download is Content-Disposition:

header("Content-Disposition: attachment; filename="$filename"");

In PHP, any header directive should be served BEFORE any other content, including any whitespace.

If you find that your server isn't configured to observe .htaccess files and you aren't able to configure it appropriately then a simple proxy script like this would work:-

<?php
header("Content-Disposition: attachment; filename="myData.kml"");
include 'myData.kml';
?>

...replacing the relevant filename. You can expand this out to work for multiple KML files using variables but for security, make sure that your script checks that any requested files are valid rather than just blindly 'including' any file that is requested.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...