开发者

Test if a php include is called from a local file

开发者 https://www.devze.com 2023-03-19 17:38 出处:网络
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.

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 web开发者_StackOverflow中文版root, 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";


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.


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)


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...
    }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消