开发者

Detect if PHP file directly loaded

开发者 https://www.devze.com 2023-01-25 14:15 出处:网络
I\'m using some PHP pages do some AJAX stuff but I don\'t want them to be directly accessible.Facebook does a similar thing so for example: domain.com/ajax/my_ajax_form.php

I'm using some PHP pages do some AJAX stuff but I don't want them to be directly accessible. Facebook does a similar thing so for example: domain.com/ajax/my_ajax_form.php

If I was to load that page using AJAX it would work fine, but if a user were to try and loading the file directly by typing in that url it would do through an error so e.g.

开发者_如何学C
if( IS FILE LOADED DIRECT? )
{
header ( HTTP/1.0 404 );
}


This isn't possible. You cannot rely on $_SERVER['HTTP_X_REQUESTED_WITH'], and even if you could, it doesn't matter. Anyone can send the same request to your server that your browser does, via POST or GET.

What you should do is validate the request, and return the proper result if it is valid. If it is invalid, do not return a 404. (Browsers can cache errors like 404. If your client-side code had a trouble, subsequent requests may fail!) If the request is invalid, return an error of some sort.

Again, it is impossible to secure stuff like this. You should be validating the session and request data. That's all.


You can look for the HTTP_X_REQUESTED_WITH header.

$is_ajax = array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) 
           && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';

if (! $is_ajax) {
    die('go away.');
}

Note, though, that it's not standard, but needs to be set explicitly on the requesting side. AFAIK, at least jQuery and Mootools set it though, probably most others as well, but don't take my word for it.


Simplest way is to only access that page via POST, and not via GET. Though keep in mind - if a browser can do it - then a hacker can too.


You have to use session variables, or more generally, cookies.

With cookies: (set in JavaScript)

  1. JavaScript: Set token in cookie
  2. JavaScript: Make XMLHttpRequest
  3. Server side: Check token from cookie
  4. Server side: Return JSON output or error message

Please note that this is no way secure! This just prevents easy linking.

With session variables: (cookies set in server side)

  1. Server side: Authenticate user, set privileges
  2. JavaScript: Make XMLHttpRequest
  3. Server side: Check privileges
  4. Server side: Return JSON output or error message

This method is as secure as the user authentication is.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号