简体   繁体   中英

Download PHP script instead of executing it

I have a downloads directory on a website where I store a bunch of different files for people to download (zip, exe, java, php, etc). The problem is that my website is written in PHP, so the web server, Apache, tries to execute the scripts instead of letting people download them. Without having access to Apache config (I'm on shared hosting), what is the easiest way to prevent Apache from executing scripts in a single directory?

I tried using mod_mime unsuccessfully. AddType doesn't work because (I'm guessing) a MIME type is already associated with PHP scripts. ForceType doesn't work because I store different types of files in the directory. Are there any other options?

If you have sufficient permissions for that, putting the following line in a .htaccess file in the directory in which you don't want PHP script to be executed might do the trick :

php_flag engine off

(Just tested on my webserver, and I got the source of a PHP script -- which had not been executed)

You could write a separate PHP script which sends the right Content-type header and then uses readfile() to pass through the contents of the PHP file without PHP actually executing them (and since Apache already passed off the request to PHP, it no longer cares). Just make sure you restrict it to only serving things out of that directory.

我认为通常的解决方案是给文件扩展名为phps

I think I have the solution for you. Check this out:

http://www.boutell.com/newfaq/creating/forcedownload.html

Basically, it says that you should have the following code in your php page:

<?php
header('Content-disposition: attachment; filename=whatever.php');
header('Content-type: text/html');
readfile('whatever.php');
?>

I made a sample here:

http://sotkra.com/test.php

This forces the 'download' file prompt where the file download is the whatever.php

Cheers

You should have a download gateway script, such as download.php . It should take a query string argument which lists the file that needs downloaded.

That argument should be matched against a pre-existing ARRAY of accessible files (big security point there).

Then use:

<?php
$file = trim(isset($_GET['file']) ? $_GET['file'] : '');

$allow = array(
    'foo.php' => 'text/plain',
    'foo.jpg' => 'image/jpeg',
);    

if(! isset($allow[$file]))
   die('File not found.');

header('Content-Type: ' . $allow[$file]);
readfile($file);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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