问题描述:

First of all I apologize if this question is already asked as I searched and couldn't found the exact question and answer.

So let's start I want to force .mp3 files to download instead of playing therefore I use the following code in download.php

 <?php

/**

* Download the mp3 file.

*/

$file_name = $_GET["filename"];

$file_url = $_GET["fileurl"];

header("Content-Description: File Transfer");

header('Content-type: application/mp3');

header("Content-Transfer-Encoding: Binary");

header("Content-disposition: attachment; filename=\"".$file_name."\"");

readfile($file_url);

exit;

So when users click on a link with destination http://www.example.com/download.php?filename=example.mp3&url=http://www.example.com/example.mp3 the are able to save the file.

So what I want is to prevent direct access to file http://www.example.com/download.php

and allow users to download files using url: http://www.example.com/download.php?filename=example.mp3&url=http://www.example.com/example.mp3

网友答案:

If you are using apache server you can make use .htaccess to deny access to some files.

Here is an example you can add to your .htaccess file:

<Files /example.mp3>
    Order Allow,Deny
    Allow from all
</Files>
网友答案:

Do you mean something like this?

if($_GET['filename'] == ''){
         header("Location: http://someLocation.com/");
    }
网友答案:

First off, blindly calling readfile() from a parameter defined in the request presents a huge security risk.

My recommendation is to accept filename only, then build a full filepath containing the filename and the path to your mp3 folder. Then ensure that the file exists, then do the readfile()

NOTE Your mp3 folder should be outside of your public html folder, or if not, at least configure your web server with an access rule that prevents direct access to the folder.

Secondly, the only way to prevent access to your php file with no parameters is to use a rewrite rule (if your web server supports it)

A more simple approach might be to check to see if there is no filename parameter, then have a default behavior, i.e. redirect to homepage, etc. This can also be the default behavior specified file doesn't exist.

Lastly, I have a GitHub project that you might find useful - for ideas if nothing else:

https://github.com/iNamik/PHP-Download-Tracker

相关阅读:
Top