Check file inclusion

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
thiscatis
Forum Contributor
Posts: 434
Joined: Thu Jul 20, 2006 11:00 am

Check file inclusion

Post by thiscatis »

Is there any way to check if a certain php file in included in another php file or accessed directly?
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

I'm not sure what you're trying to do, but PHP compiles all includes before parsing them, as if all the code is in the same file -- there is no way to tell which parts of code were included at runtime. You might check include_once() or require_once() just in case I misunderstood you.
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

If I understand you correctly this (or a variation of it) should work.

Code: Select all

if($_SERVER['PHP_SELF'] != __FILE__) {
  //this file is being accessed indirectly (included)
} else {
  //this file is being access directly (not included)
}
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

thiscatis
Forum Contributor
Posts: 434
Joined: Thu Jul 20, 2006 11:00 am

Post by thiscatis »

you can use this in the root page which you use to include other files,
this won't give you info to see whether a page is accessed directly for eg (modules/module1.php) or
included in the index.php
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

If you want to check against direct access, use a constant's existence to flag it. It's the easiest to do.
Post Reply