Hey, PHP newbie here when I try to run this to get an IP it give me
Fatal error: Cannot access self:: when no class scope is active in /home/content/56/6442856/html/unlocking/Untitled-4.php on line 14
What am I doing wrong here?
Also, please remember: PHP newbie here, so explain as much as possible.
Thanks
<?php
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_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)
{
self::$ip = $ip; return $ip;
}
}
}
}
}
get_ip_address();
echo $ip;
?>
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_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)
{
return $ip;
}
}
}
}
}
echo get_ip_address();
And i don't know if you really need such a function to get the IP of the client.
echo $_SERVER['REMOTE_ADDR'];
could be sufficient imo
You're getting the error because of this line :
self::$ip = $ip; return $ip;
You use self
when you're inside a class and referring to one of its static members :
class Foo
{
public static $my_static = 'foo';
public function staticValue() {
return self::$my_static; //It's correctly used here
}
}
as for the solution specific to your problem yes123 has already covered it.