3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Session\Validator
;
12 use Zend\Http\PhpEnvironment\RemoteAddress
;
13 use Zend\Session\Validator\ValidatorInterface
as SessionValidator
;
15 class RemoteAddr
implements SessionValidator
25 * Whether to use proxy addresses or not.
27 * As default this setting is disabled - IP address is mostly needed to increase
28 * security. HTTP_* are not reliable since can easily be spoofed. It can be enabled
29 * just for more flexibility, but if user uses proxy to connect to trusted services
30 * it's his/her own risk, only reliable field for IP address is $_SERVER['REMOTE_ADDR'].
34 protected static $useProxy = false;
37 * List of trusted proxy IP addresses
41 protected static $trustedProxies = array();
44 * HTTP header to introspect for proxies
48 protected static $proxyHeader = 'HTTP_X_FORWARDED_FOR';
52 * get the current user IP and store it in the session as 'valid data'
54 public function __construct($data = null)
57 $data = $this->getIpAddress();
63 * isValid() - this method will determine if the current user IP matches the
64 * IP we stored when we initialized this variable.
68 public function isValid()
70 return ($this->getIpAddress() === $this->getData());
74 * Changes proxy handling setting.
76 * This must be static method, since validators are recovered automatically
77 * at session read, so this is the only way to switch setting.
79 * @param bool $useProxy Whether to check also proxied IP addresses.
82 public static function setUseProxy($useProxy = true)
84 static::$useProxy = $useProxy;
88 * Checks proxy handling setting.
90 * @return bool Current setting value.
92 public static function getUseProxy()
94 return static::$useProxy;
98 * Set list of trusted proxy addresses
100 * @param array $trustedProxies
103 public static function setTrustedProxies(array $trustedProxies)
105 static::$trustedProxies = $trustedProxies;
109 * Set the header to introspect for proxy IPs
111 * @param string $header
114 public static function setProxyHeader($header = 'X-Forwarded-For')
116 static::$proxyHeader = $header;
120 * Returns client IP address.
122 * @return string IP address.
124 protected function getIpAddress()
126 $remoteAddress = new RemoteAddress();
127 $remoteAddress->setUseProxy(static::$useProxy);
128 $remoteAddress->setTrustedProxies(static::$trustedProxies);
129 $remoteAddress->setProxyHeader(static::$proxyHeader);
130 return $remoteAddress->getIpAddress();
134 * Retrieve token for validating call
138 public function getData()
144 * Return validator name
148 public function getName()