hpaknia
hpaknia

Reputation: 3108

How to find out a php file is included or accessed directly?

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)

Upvotes: 11

Views: 1686

Answers (2)

Axel Advento
Axel Advento

Reputation: 3065

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
}

Upvotes: 3

ceejayoz
ceejayoz

Reputation: 179994

if(__FILE__ != $_SERVER['SCRIPT_FILENAME']) {
  // we're in an include
}

Upvotes: 16

Related Questions