REMOTE_ADDR empty, not included in SERVER array

独自空忆成欢 提交于 2019-12-23 19:01:10

问题


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

回答1:


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'])) {
    ....



回答2:


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.



来源:https://stackoverflow.com/questions/5362690/remote-addr-empty-not-included-in-server-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!