开发者

REMOTE_ADDR empty, not included in SERVER array

I'm having a weird problem after moving to a new server. A cron to fetch mails checks for authorized IPs, one of which is by default 127.0.0.1

It stopped working after the move, because the REMOTE_ADDR variable isn't populated. It is when called from the browser, but not when ran internally from a cron or from console with php. I dumped the $_SERVER variable and this is all it has from cron/console

(
   [SHELL] => /bin/sh
   [MAILTO] => *removed*
   [USER] => *removed*
   [PATH] => /usr/bin:/bin
   [PWD] => /home/*removed*
   [SHLVL] => 1
   [HOME] => /home/*removed*
   [LOGNAME] => *removed*
   [_] => /usr/local/bin/php
   [PHP_SELF] => /home/*removed*/public_html/support/cron.php
   [SCRIPT_NAME] => /home/*removed*/public_html/support/cron.php
   [SCRIPT_FILENAME] => /home/*removed*/public_html/support/cron.php
   [PATH_TRANSLATED] => /home/*removed*/public_html/support/cron.php
   [DOCUMENT_ROOT] =>
   [REQUEST_TIME] => 1300522141
   [argv] => Array
       (
           [0] => /home/*removed*/public_html/support/cron.php
       )

   [argc] => 1
)

if(!$cron->isValidIp($_SERVER['REMOTE_ADDR'])) {
    echo sprintf("[ERROR]: Your IP %s is not authorized to run scheduled tasks.  Plea开发者_如何学Pythonse notify your administrator.",
        $_SERVER['REMOTE_ADDR']
    );

        // [JAS]: Test all our IPs for a wildcard match
        if(is_array($this->valid_ips))
        foreach($this->valid_ips as $mask) {
            if(empty($mask)) continue;
            if(0 == strcmp(substr($ip,0,strlen($mask)),$mask)) {
                return true;
            }


The $_SERVER['REMOTE_ADDR'] variable is populated because of Apache, running from the command line, this variable won't be set, as well as many others.

Also, even if it were set, REMOTE_ADDR would always be the local ip of the machine the cron is running on, as you wouldn't be able to run it remotely.

[edit]

Just for consistency, here's an example using php_sapi_name

if(php_sapi_name() === 'cli') {
    // You're running locally from the CLI
} else {
    // You're running remotely, check against list of authorized ip addresses.
}

In your case, you could just change your if to:

if(php_sapi_name() != 'cli' && !$cron->isValidIp($_SERVER['REMOTE_ADDR'])) {
    ....


REMOTE_ADDR isn't populated when run from a command line script, as its value is obtained from HTTP headers.

Are you trying to check this to make sure the script is not run from the web browser? If this is the case you could move it to a directory above the web root and allow cron to run it that way.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜