11

Is there any way to find out if a php script is accessed directly or it's included.

  1. Suppose we don't where it's included, so setting session variable won't solve the problem. I can not check where it's included. it may be more than 20 places!
  2. It should be detected in php script. (via php functions and variables)
hpaknia
  • 2,769
  • 4
  • 34
  • 63
  • 1
    possible duplicate of http://stackoverflow.com/questions/2397004/php-check-if-a-file-is-loaded-directly-instead-of-including – Alex Shesterov Apr 22 '13 at 18:18
  • 3
    [List your includes](http://php.net/manual/en/function.get-included-files.php) and [Prevent Direct Access](http://stackoverflow.com/questions/409496/prevent-direct-access-to-a-php-include-file) – Unexpected Pair of Colons Apr 22 '13 at 18:18
  • no it's not duplicate, see point 1 of my question, I can not check where it's included. it may be more than 20 places! – hpaknia Apr 22 '13 at 18:24

2 Answers2

16
if(__FILE__ != $_SERVER['SCRIPT_FILENAME']) {
  // we're in an include
}
ceejayoz
  • 176,543
  • 40
  • 303
  • 368
3

Used ceejayoz's answer but I have troubles when using symlinked files and paths due to __FILE__ being resolved to the real path automatically. So I used realpath() function on $_SERVER['SCRIPT_FILENAME'] instead to resolve both paths to the real path to solve the problem.

if(__FILE__ != realpath($_SERVER['SCRIPT_FILENAME'])) {
    // we're in an include
}
Axel Advento
  • 2,995
  • 3
  • 24
  • 32