سؤال

Here's the situation.

I have a primary web server that needs to be able to access files on a remote web server with PHP. I also have a remote server. The files on the remote server are private. That is, I only want to access them through my PHP script on the primary server.

How do I only allow access to a directory of files from the primary server, but deny access to anyone else?

هل كانت مفيدة؟

المحلول

In your .htaccess file:

AuthName "Protected" 
AuthType Basic 
<Limit GET POST> 
order deny,allow 
deny from all 
allow from YOUR.SERVER.IP.ADDRESS 
</Limit> 

That's how I'd do it. Place that in the .htaccess file in the directory you are trying to protect. Only requests which come from YOUR.SERVER.IP.ADDRESS (obviously change that to your server IP) will be allowed, everyone else gets a 403 error.

Given your comments, then you'd want to do it some way with access tokens or something. The way I'd set it up would be to make a PHP script on the remote file server which will serve the files if an access token is matched, and you could just fetch the file with cURL then. If the access token is not matched, set the 403 Forbidden header.

Then, they'd only be able to access the files with your access token. To make the token dynamic so it can't be stolen easily, you could take the MD5 hash of a salt plus a dynamic variable that could be shared between servers, like the day of the month. The more frequently the dynamic variable updates, the more frequently the access token updates and the more secure you'll be. Try to keep what you're using for a salt and the hashing algorithm secret, for the best protection.

Basic script you could keep on the file server:

if($_GET['access'] != md5('aihdhgsa8gas8gasgsa8asgdds' . $YOUR_UPDATING_VALUE)){
    //Improper access hash
    header('HTTP/1.1 403 Forbidden');
    die();
}

$files = array('blah.png', 'lol.exe');
$file_to_serve = $_GET['file'];
if(!in_array($file_to_serve, $files)){
    //File isn't in our array
    header('HTTP/1.1 403 Forbidden');
    die();
}else{
    die(file_get_contents($file_to_serve)); //Serve however you need.
}

And on your main server:

$file = file_get_contents('http://example.com/serve.php?file=' . $filename . '&access=' . md5('aihdhgsa8gas8gasgsa8asgdds' . $YOUR_UPDATING_VALUE));

These are very rough examples and you'd need to rework the serving and fetching to your system configuration, but you get the point. $YOUR_UPDATING_VALUE should be something both servers can calculate that updates kinda frequently, I'd advise against microtime because there would be a delay in fetching from the other server and it'd always be false.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top