2

I am trying to prevent a php file from being accessed directly through a browser or anything else, unless its coming from a authorised domain.

I used the php header Access-Control-Allow-Origin like this:

header('Access-Control-Allow-Origin: http://www.example.com');

But it still doesn't block direct access.

UPDATE:

I tried to .htaccess method:

order deny,allow
deny from all
allow from <your ip> 

and this one too:

<RequireAll>
    Require ip <your ip> 
</RequireAll>

I also tried using both with domain names.

With this I managed to block direct access, but I also blocked my app from accessing it too.

I get:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

and I added:

header('Access-Control-Allow-Origin: myappdomain.com');

Still not working.

ricardolobo
  • 77
  • 3
  • 8
  • 1
    you should look into using [`.htacess` files](http://www.htaccess-guide.com/) if your host allows them – happymacarts Jan 23 '17 at 16:22
  • You could always set up a function to check your database for trusted domains that have been added in? This way you can have an admins section also to add the trusted domains in. – Option Jan 23 '17 at 16:22
  • @happymacarts Yes it does. Its a dedicated server. I remember trying htaccess but I couldn't get it to allow access to the file from other domain. something like this: – ricardolobo Jan 23 '17 at 16:26
  • 2
    Possible duplicate of [Deny all, allow only one IP through htaccess](http://stackoverflow.com/questions/4400154/deny-all-allow-only-one-ip-through-htaccess) – happymacarts Jan 23 '17 at 16:31
  • `accessed directly through a browser or anything else` I have to say: Then setting just an `header()` will not work. Because a User can always write a url into a browser. You have to prevent the acces via `.htaccess` or with something like @Antony has shown. – JustOnUnderMillions Jan 23 '17 at 16:31
  • @happymacarts I think you just gave me the answer with that thread link. I'll try that. – ricardolobo Jan 23 '17 at 16:33
  • 2
    CORS and `Access-Control-Allow-Origin` and all other `Access-Control-*` headers intentionally doesn’t prevent users from directly navigating to a URL—any more than they prevent anybody from using curl or whatever to get to it. CORS and those headers only affects cross-origin scripted requests to the URL, using XHR or the fetch API. – sideshowbarker Jan 23 '17 at 17:06

1 Answers1

1

How about using $_SERVER['HTTP_REFERER']?
Sample code:

if($_SERVER['HTTP_REFERER'] !== 'gooddomain.com'){
    die('Unauthorized access');
}

Although this can be manipulated or altered quite easily, unless you control both the sending and the receiving server there isn't much more you can do.

Antony
  • 1,253
  • 11
  • 19