Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.  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;
            }
like image 558
hikari Avatar asked Nov 24 '25 13:11

hikari


1 Answers

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'])) {
    ....
like image 123
Andrei Serdeliuc ॐ Avatar answered Nov 26 '25 04:11

Andrei Serdeliuc ॐ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!