1

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 :)

3 Answers3

5

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

Community
  • 1
  • 1
knittl
  • 246,190
  • 53
  • 318
  • 364
0
 if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
     die("Error!");
 }

Would maybe be sufficient?

isakkarlsson
  • 1,111
  • 9
  • 13
  • i want to forbid direct access via URL, but if i am calling the page via AJAX it will work normal... –  Jun 03 '11 at 16:37
  • 2
    You cannot entierly forbid this. Both are from clients and one might spoof into the other. This is just a dumb check, but it's working as you like. – isakkarlsson Jun 03 '11 at 16:43
0

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.

Battle_707
  • 708
  • 5
  • 15