I know that CHttpRequest::getUserHostAddress() can be improved, the default implementation being just a rough wrapper over $_SERVER[‘REMOTE_ADDR’] which in some cases returns wrong ip address.
That’s why, i extended the class with my own and made an better version of the method :
<?php
class CmsCHttpRequest extends CHttpRequest
{
private $_ipAddress;
public function init()
{
parent::init();
}
public function getUserHostAddress()
{
if($this->_ipAddress !== null)
return $this->_ipAddress;
if (isset($_SERVER['REMOTE_ADDR']) AND isset($_SERVER['HTTP_CLIENT_IP']))
$this->_ipAddress = $_SERVER['HTTP_CLIENT_IP'];
elseif (isset($_SERVER['REMOTE_ADDR']))
$this->_ipAddress = $_SERVER['REMOTE_ADDR'];
elseif(isset($_SERVER['HTTP_CLIENT_IP']))
$this->_ipAddress = $_SERVER['HTTP_CLIENT_IP'];
elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$this->_ipAddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
if ($this->_ipAddress === FALSE)
{
$this->_ipAddress = '0.0.0.0';
return $this->_ipAddress;
}
if (strpos($this->_ipAddress, ',') !== FALSE)
{
$x = explode(',', $this->_ipAddress);
$this->_ipAddress = trim(end($x));
}
if (!$this->isValidIp($this->_ipAddress))
$this->_ipAddress = '0.0.0.0';
return $this->_ipAddress;
}
public function isValidIp($ip)
{
$ipSegments = explode('.', $ip);
if (count($ipSegments) != 4)
return false;
if ($ipSegments[0][0] == '0')
return false;
foreach ($ipSegments as $segment)
{
if ($segment=='' OR preg_match("/[^0-9]/", $segment) OR $segment > 255 OR strlen($segment) > 3)
return false;
}
return true;
}
}
This is my first post in this forum . Started learning Yii just a week ago . Could you please let me know how to use the helper class you wrote in module class . I copied your code and created a file under /components with CmsCHttpRequest.php
To use Yii::app()->request->userHostAddress , it is calling from CHttpRequest and when I use
CmsCHttpRequest::getUserHostAddress() throwing some errors .
Please guide me how to use this in your free time and thanks for your help
Basically the above line of code tells yii that when you call Yii::app()->request it should use the CmsCHttpRequest instead of the default one CHttpRequest.
Now, after these changes, when you call Yii::app()->request->getUserHostAddress() you will actually call the new method from the CmsCHttpRequest file with the extra enhancements.