Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Here is a shorter, cleaner way to get the IP address:</strong></p> <pre><code>function get_ip_address(){ foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){ if (array_key_exists($key, $_SERVER) === true){ foreach (explode(',', $_SERVER[$key]) as $ip){ $ip = trim($ip); // just to be safe if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){ return $ip; } } } } } </code></pre> <p>I hope it helps!</p> <hr> <p>Your code seems to be pretty complete already, I cannot see any possible bugs in it (aside from the usual IP caveats), I would change the <code>validate_ip()</code> function to rely on the filter extension though:</p> <pre><code>public function validate_ip($ip) { if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) { return false; } self::$ip = sprintf('%u', ip2long($ip)); // you seem to want this return true; } </code></pre> <p>Also your <code>HTTP_X_FORWARDED_FOR</code> snippet can be simplified from this:</p> <pre><code>// check for IPs passing through proxies if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { // check if multiple ips exist in var if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') !== false) { $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); foreach ($iplist as $ip) { if ($this-&gt;validate_ip($ip)) return $ip; } } else { if ($this-&gt;validate_ip($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR']; } } </code></pre> <p>To this:</p> <pre><code>// check for IPs passing through proxies if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); foreach ($iplist as $ip) { if ($this-&gt;validate_ip($ip)) return $ip; } } </code></pre> <p>You may also want to validate IPv6 addresses.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload