PHP Get user IP Address

From JumbaWiki

Jump to: navigation, search

You often want to get a user's IP Address for some form of semi-unique identification.

To display it on the page you can use this code:

<?php echo $_SERVER["REMOTE_ADDR"] ?>

To use it as a variable so you can use it in other scripts,

<?php $Users_IP_address = $_SERVER["REMOTE_ADDR"] ?>

If the user is operating via a proxy server, the above code may not work. In this case use this simple function:

 <?php
 
 function VisitorIP()
    { 
    if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $TheIp=$_SERVER['HTTP_X_FORWARDED_FOR'];
    else $TheIp=$_SERVER['REMOTE_ADDR'];
 
    return trim($TheIp);
    }
 
?>

Then set your variable like this:

 <?php
 
 $Users_IP_address = VisitorIP();
 
 ?>


See also

Personal tools
Australian Photographs | Unique Views of Reality | Daedalus