Sean Kimball
Sean Kimball

Reputation: 4494

Test if a php include is called from a local file

I have a php include with one function in it, I need to ensure that it can only be executed by inclusion within a local file and not from any external source.

What is the best method of testing for this?

-thanks -sean

UPDATE:

thanks, here is some more info, - I can't move it outside the webroot, I'm updating an existing site - testing for REMOTE_ADDR will always return the clients ip - the only way I want this file called is by: include_once "sendmail.php";

Upvotes: 2

Views: 785

Answers (4)

Ostin
Ostin

Reputation: 1541

I see two cases of your problem:

  1. File can be accessed over http with any browser. In that case you can define a CONST in your main application and then chek it in includes:

    main file:

    define('MY_APP', true);
    

    included file:

    if (!defined('MY_APP') || MY_APP !== true) {
      die('Access denied');
    }
    
  2. File can be accessed via file system (from nearby virtual host for example). Than you can use SERVER_NAME and REQUEST_URI checks.

Upvotes: 2

Patrick Desjardins
Patrick Desjardins

Reputation: 140993

You can use the $_SERVER array to return the IP of the caller.

$callerIP = $_SERVER['SERVER_ADDR'];

You can than check if the $callerIP is localhost.

Upvotes: 1

Jules
Jules

Reputation: 7233

If you always include and execute it from the same file you could make a URL check in your function.

function curPageURL() {
     $pageURL = 'http';
     if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
     $pageURL .= "://";
     if ($_SERVER["SERVER_PORT"] != "80") {
         $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
     } else {
         $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
     }
     return $pageURL;
}


//Your included function:
function doSomething() {
    if (curPageUrl() == "http://www.yourwebsite.com/function.php") {
        ... execute code...
    }
}

Upvotes: 1

Quentin
Quentin

Reputation: 944320

Forget testing. Just keep the file outside the webroot.

If it can't be served over HTTP then it can't be used externally.

(Although, if it just contains a function, and no statements that execute automatically, then any external request is going to end up with a blank HTTP response unless the server starts serving up PHP files as plain text)

Upvotes: 2

Related Questions