PHP Superglobal Variables

PHP Superglobal Variables

PHP SuperGlobal Variables are predefined variables in PHP that are always accessible (You can access them from any function, class or file), regardless of scope.
Below is the list of superglobal variables available in PHP:

  1. $GLOBALS
  2. $_SERVER
  3. $_REQUEST
  4. $_GET
  5. $_POST
  6. $_SESSION
  7. $_COOKIE
  8. $_FILES
  9. $_ENV

$_SERVER

$_SERVER is a PHP superglobal variable, an array containing information about headers, paths or script locations.

<pre>
<?php print_r($_SERVER);?>
</pre>

Finding an IP Address with PHP

echo $_SERVER['REMOTE_ADDR'];

::1 is the actual IP for localhost. It is an ipv6 loopback address. If you were using ipv4 it would be 127.0.0.1.
If you connect to the server through a different network interface You will get a different IP address.

If you are going to save the IP to a database as a string, make sure you have space for at least 45 characters. IPv6 is here to stay and those addresses are larger than the older IPv4 addresses.

What happens if someone connects to the server using a proxy?

The proxy server will hide the user IP address so the $_SERVER[‘REMOTE_ADDR’] will show the proxy IP address. In this case, the proxy may have set the $_SERVER[‘HTTP_X_FORWARDED_FOR’], but this value is easily spoofed.

Most proxy servers will use HTTP_X_FORWARDED_FOR, HTTP_FORWARDED or HTTP_X_FORWARDED or HTTP_CLIENT_IP, etc to send the response back to the user.
Neither of these headers is officially standardized, so different proxies may implement these, or may not. Implementations may vary from one proxy to another.

Finding a Forwarded IP Address that has been set by a Proxy Server

function find_ip_address(){
		$ip = $_SERVER['REMOTE_ADDR'];
		echo "Your ip address is: $ip";	
}
function find_forwarded_ip_address(){
		$headers = array('HTTP_X_FORWARDED_FOR','HTTP_X_FORWARDED','HTTP_FORWARDED_FOR','HTTP_FORWARDED','HTTP_CLIENT_IP');
		foreach($headers as $header){
			if(isset($_SERVER[$header])){
				echo $_SERVER[$header];
				$ip_array = explode(',',$_SERVER[$header]);
				foreach($ip_array as $ip){
					$ip = trim($ip);
					return $ip;
				}
			}
		}
		return '';
	}
	
//validate any IPv4 and IPv6 IP address as long as it is not a reserved or private range IP address:
function validate_ip($ip){
	if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
	  echo "You use a proxy server with forwarded ip address: $ip";
	}
}
$ip = find_forwarded_ip_address();
validate_ip($ip);

Test the script here Find my IP Address

Hello there!

I hope you find this post useful!

I'm Mihai, an online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

Leave a Reply

Your email address will not be published. Required fields are marked *