使用CLI定時自動執行程式時,出現了一段錯誤訊息:

<h4>A PHP Error was encountered</h4>
<p>Severity: Notice</p>
<p>Message: Undefined index: REMOTE_ADDR</p>
<p>Filename: core/Input.php</p>
<p>Line Number: 351</p>


原來 Input.php 裡面語法是這樣子的

$this->ip_address = $_SERVER[‘REMOTE_ADDR’];

因為是本機呼叫,所以哪來的 REMOTE_ADDR 可以取的值?
底下列出幾種改法:

方法一:

// 讓他返回 false
$this->server('REMOTE_ADDR');

方法二:

//讓他返回 0.0.0.0
if(isset($_SERVER['REMOTE_ADDR'])){
  $this->ip_address = $_SERVER['REMOTE_ADDR'];
}else{
  $this->ip_address = '0.0.0.0';
}

方法三:

// 整個 function 改掉
function ip_address()
{
  if ($this->ip_address !== FALSE)
  {
    return $this->ip_address;
  }

  if (config_item('proxy_ips') != '' && $this->server('HTTP_X_FORWARDED_FOR') && $this->server('REMOTE_ADDR'))
  {
    $proxies = preg_split('/[\s,]/', config_item('proxy_ips'), -1, PREG_SPLIT_NO_EMPTY);
    $proxies = is_array($proxies) ? $proxies : array($proxies);

    $this->ip_address = in_array($_SERVER['REMOTE_ADDR'], $proxies) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
  }
  elseif ($this->server('REMOTE_ADDR') AND $this->server('HTTP_CLIENT_IP'))
  {
    $this->ip_address = $_SERVER['HTTP_CLIENT_IP'];
  }
  elseif ($this->server('REMOTE_ADDR'))
  {
      $this->ip_address = $_SERVER['REMOTE_ADDR'];
  }
  elseif ($this->server('HTTP_CLIENT_IP'))
  {
      $this->ip_address = $_SERVER['HTTP_CLIENT_IP'];
  }
  elseif ($this->server('HTTP_X_FORWARDED_FOR'))
  {
      $this->ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
  }

  if ($this->ip_address === FALSE)
  {
      $this->ip_address = '0.0.0.0';
      return $this->ip_address;
  }

  if (strpos($this->ip_address, ',') !== FALSE)
  {
      $x = explode(',', $this->ip_address);
      $this->ip_address = trim(end($x));
  }

  if ( ! $this->valid_ip($this->ip_address))
  {
      $this->ip_address = '0.0.0.0';
  }

  return $this->ip_address;
}

發表迴響