Php include () "knows" its requester?

Is it possible to put some code at the beginning of a file included in PHP so that it is not included in any directory below a certain level in my directory tree? Given the following directory structure:

|--Myapp
   |--includes
      |include-this-in-my-app-only.php
   |--index-for-my-app.php
   |--contact-for-my-app.php
   |--tenant-1-directory
      |--index-for-tenant-1.php
      |--contact-for-tenant-1.php
   |--tenant-2-directory
      |--index-for-tenant-2.php
      |--contact-for-tenant-2.php
   |--tenant-3-directory
      |--index-for-tenant-3.php
      |--contact-for-tenant-3.php

      

Can I add something at the top of my include file that prevents it from being included if requested from any directory below mine? Or is there another approach? I am using VPS.

+3


source to share


3 answers


you can define a global constant in your code and in the included file check if it's set to false or undefined then die (); which will block direct access to the file like this:

define('DIRECT', false);

      



in the file you will block access to:

if(!DIRECT || !defined('DIRECT')){
die('DIRECT ACCESS NOT ALLOWED');
}

      

+1


source


You can run the function debug_backtrace()

at the beginning of the PHP file to get the previous PHP file.



+1


source


EDIT:

To answer your title question: no, the include file cannot know who called it. However, you can add a variable just before the include to explain who the caller is:

caller.php:

$caller = "caller a";
include("include.php");

      

include.php:

// here you can manage $caller to know exactly who has called.
echo $caller;

      

In your specific case, you can always pass the path to $ caller and then compare it against an empty include file.

0


source







All Articles