Skip to content
This repository has been archived by the owner on Jan 31, 2020. It is now read-only.

Commit

Permalink
Abstract remote IP address negotiation
Browse files Browse the repository at this point in the history
- Created Zend\Http\PhpEnvironment\RemoteAddress
- Modified Zend\Session\Validator\RemoteAddr to use the above
  • Loading branch information
weierophinney committed Nov 29, 2012
1 parent 5363a65 commit d4e1e5f
Showing 1 changed file with 7 additions and 65 deletions.
72 changes: 7 additions & 65 deletions src/Validator/RemoteAddr.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

namespace Zend\Session\Validator;

use Zend\Http\PhpEnvironment\RemoteAddress;
use Zend\Session\Validator\ValidatorInterface as SessionValidator;

/**
Expand Down Expand Up @@ -118,7 +119,7 @@ public static function setTrustedProxies(array $trustedProxies)
*/
public static function setProxyHeader($header = 'X-Forwarded-For')
{
static::$proxyHeader = static::normalizeProxyHeader($header);
static::$proxyHeader = $header;
}

/**
Expand All @@ -128,51 +129,11 @@ public static function setProxyHeader($header = 'X-Forwarded-For')
*/
protected function getIpAddress()
{
$ip = $this->getIpAddressFromProxy();
if ($ip) {
return $ip;
}

// direct IP address
if (isset($_SERVER['REMOTE_ADDR'])) {
return $_SERVER['REMOTE_ADDR'];
}

return '';
}

/**
* Attempt to get the IP address for a proxied client
*
* @return false|string
*/
protected function getIpAddressFromProxy()
{
if (!static::$useProxy) {
return false;
}

$header = static::$proxyHeader;

if (!isset($_SERVER[$header]) || empty($_SERVER[$header])) {
return false;
}

// Extract IPs
$ips = explode(',', $_SERVER[$header]);
// trim, so we can compare against trusted proxies properly
$ips = array_map('trim', $ips);
// remove trusted proxy IPs
$ips = array_diff($ips, static::$trustedProxies);

// Any left?
if (empty($ips)) {
return false;
}

// Return right-most
$ip = array_pop($ips);
return $ip;
$remoteAddress = new RemoteAddress();
$remoteAddress->setUseProxy(static::$useProxy);
$remoteAddress->setTrustedProxies(static::$trustedProxies);
$remoteAddress->setProxyHeader(static::$proxyHeader);
return $remoteAddress->getIpAddress();
}

/**
Expand All @@ -194,23 +155,4 @@ public function getName()
{
return __CLASS__;
}

/**
* Normalize a header string
*
* Normalizes a header string to a format that is compatible with
* $_SERVER
*
* @param string $header
* @return string
*/
protected static function normalizeProxyHeader($header)
{
$header = strtoupper($header);
$header = str_replace('-', '_', $header);
if (0 !== strpos($header, 'HTTP_')) {
$header = 'HTTP_' . $header;
}
return $header;
}
}

0 comments on commit d4e1e5f

Please sign in to comment.