简体   繁体   中英

Prevent Direct Access to a php file and allow only one domain

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, ie 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

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