Getting User’s IP in PHP

Written by admin on May 17th, 2008 in PHP Tutorials, Tutorials.

Sometimes you may need to get a users IP that is browsing your website and store it for protection or display it to the user.

In PHP this is simply done by using the $_SERVER variable.

The code below will store a users IP into a variable:

<?php

$UsersIP = компютри$_SERVER[’REMOTE_ADDR];

?>

REMOTE_ADDR simply grabs the remote IP Adress being used.

Lots more info can be obtained this way. But that is how to grab a Users IP.

One Response to “Getting User’s IP in PHP”

  1. Nick Tompson Says:

    You could also more accurately obtain the IP address using the following, which can attempt to get proxy’s etc.

    // Setup from env
    $requestIP = $_SERVER[ "REMOTE_ADDR" ];
    
    if ( $_SERVER[ "HTTP_CLIENT_IP" ] )
    {
    	$requestIP = $_SERVER[ "HTTP_CLIENT_IP" ];
    }
    else if ($_SERVER[ 'HTTP_X_FORWARDED_FOR' ] AND preg_match_all( "#d{1,3}.d{1,3}.d{1,3}.d{1,3}#s", $_SERVER[ 'HTTP_X_FORWARDED_FOR' ], $matches ) )
    {
    	foreach ( $matches[0] as $IP )
    	{
    		// Chuck out RFC1918 IP
    		if ( !preg_match( "#^(10|172.16|192.168).#", $IP ) )
    		{
    			$requestIP = $IP; break;
    		}
    	}
    }
    else if ( $_SERVER[  "HTTP_FROM" ] )
    {
    	$requestIP = $_SERVER[ "HTTP_FROM" ];
    }
    else if ( $_SERVER[ "HTTP_PROXY_USER" ] )
    {
    	$requestIP = $_SERVER[ "HTTP_PROXY_USER" ];
    }
    

Leave a Reply

You must be logged in to post a comment.



Site Navigation SEO Services