简体   繁体   中英

How can i check if page accessed directly?

Hi:) I want to forbid access of a page directly, what i mean is if some one try to access for example the page

proccess.php

He will get an error message. BUT, if the page is accessed via AJAX call. it will act normal.

i've tried:

if( preg_match( '/' . basename( __FILE__ ) . '/', $_SERVER['REQUEST_URI'] ) )
{
 die("Error!");
}

but the problem is that when i access it via AJAX call, it act like i've accessed it directly...

please help:)

you can check the HTTP_X_REQUESTED_WITH header.

if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
  // ajax request
} else {
  die('direct access is forbidden');
}

also read Can the “x-requested-with” http header be spoofed? on stackoverflow

 if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
     die("Error!");
 }

Would maybe be sufficient?

An easy solution would be to set a variable to something (either true, false, a string...anything really) in all of the scripts that call this script before it calls process.php. Then the top line in process.php should be"

if ($checkVar === NULL) {

    die("Permission denied!");

}

But that would require you to edit all the pages that call the process page.

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