≡ Menu

PHP: Determine or Retrieve Visitor’s IP Address Using PHP Script

How do I determine or retrieve visitor’s IP address using PHP server side programming under Unix/Windows operating systems?

Use the following environment variables to get visitor’s IP address:

No Proxy detection
REMOTE_ADDR – Get the remote client IP address

With Proxy detection
HTTP_X_FORWARDED_FOR – Get the proxy server IP address.

PHP getenv() function
Use php getenv() function to read the value of the environment. The syntax is:

getenv('VAR-NAME-HERE')

Example: Sample code to get an IP address

Here is the PHP code:

<html>
<head>
 <title>What is my IP address?</title>
</head>
<body>
<?php
 
    if (getenv('HTTP_X_FORWARDED_FOR')) {
        $pipaddress = getenv('HTTP_X_FORWARDED_FOR');
        $ipaddress = getenv('REMOTE_ADDR');
echo "Your Proxy IP address is : ".$pipaddress. "(via $ipaddress)" ;
    } else {
        $ipaddress = getenv('REMOTE_ADDR');
        echo "Your IP address is : $ipaddress";
    }
?>
</body>
</html>

If GEOIP database installed and configured using Apache/Nginx/Lighttpd, try the following php code to get the visitors country name:

   $country = getenv('GEOIP_COUNTRY_NAME');
   echo "Your country : $country";

You can try the demo by visiting this url.

Share this tutorial on:

Your support makes a big difference:
I have a small favor to ask. More people are reading the nixCraft. Many of you block advertising which is your right, and advertising revenues are not sufficient to cover my operating costs. So you can see why I need to ask for your help. The nixCraft, takes a lot of my time and hard work to produce. If you use nixCraft, who likes it, helps me with donations:
Become a Supporter →    Make a contribution via Paypal/Bitcoin →   

Don't Miss Any Linux and Unix Tips

Get nixCraft in your inbox. It's free:



{ 35 comments… add one }
  • Abhishek October 17, 2006, 3:55 am

    it is working on localhost
    but it doesn’t work after uploading it on website
    i m getting blank page..

    • Abdul Manan January 16, 2016, 2:18 pm

      it is also not working on local host,
      can you send me detailed code please

      • Harry March 15, 2016, 10:18 am

        It works. Your url will show as :::1

        The code is:

        // Check connection
        if (!$conn) {
            die("Connection failed: " . mysqli_connect_error());
        }
        
        if (getenv('HTTP_X_FORWARDED_FOR')) {
                $pipaddress = getenv('HTTP_X_FORWARDED_FOR');
                $ipaddress = getenv('REMOTE_ADDR');
        echo "Your Proxy IP address is : ".$pipaddress. "(via $ipaddress)" ;
            } else {
                $ipaddress = getenv('REMOTE_ADDR');
                echo "Your IP address is : $ipaddress";
            }
        
  • Marvin Henry February 6, 2007, 7:42 am

    I tried with the given php code “to determine or retrieve visitors ip address in PHP” in two different machines and got the same ip address.

  • Rahman July 3, 2007, 11:07 am

    I want to get visitor IP address into table of my database.

    please help me

    thanks

    • chenna kiran September 27, 2012, 8:24 am

      you can do it by simple code
      just change host, user, password, dbname and table
      first create a table and add two columns at least like ip_id and ipaddress.
      then copy and paste the below code at last just change what you want.

      code:
      ______________________________________________________
      mysql_connect(“host”,”user”,”password”) or die(‘problem in conection’);
      mysql_select_db(“dbname”) or die(‘problem in database’);
      mysql_query(“INSERT INTO table_name (‘ipaddress’) VALUES (‘”.$ipaddress .”‘)”) or die(“error in querry”);

      now you have ipaddress in your database table.

  • trupti July 15, 2007, 2:53 pm

    i am getting a blank page after i paste the code onto my website. plz help.

  • Ogaden October 11, 2007, 8:30 pm

    Excellent tutorial!

    It works for me. I havent uploaded it to my site yet. But it looks find and i guess it should work.

    Thanks :)

  • erti November 9, 2007, 10:14 pm

    In line 12 and 15 delete and rewrite the ” and it will work.

  • RK Aggarwal November 24, 2007, 1:14 am

    very nicely given. thanx a tone

  • Muhammad March 23, 2008, 8:12 pm

    The tutorial is really great it solved my problem at once…On my local machine and on my webserver it worked.

    Thanx,
    Umair

  • Deepak Poolamadai June 13, 2008, 11:44 pm

    Hi All
    This code worked for me fine……
    Thanks to the programmer……

    And For this
    # Marvin Henry Says:
    February 6th, 2007 at 7:42 am

    I tried with the given php code “to determine or retrieve visitors ip address in PHP” in two different machines and got the same ip address.

    Reply
    I think u get a Ip address from the DHCP server.
    In This case You should the ip address of the Server and not of the client Machine.

    Anyways this solved my problem….
    Thanks a ton.

    Deepak Poolamadai

  • fRank September 28, 2008, 4:28 am

    nice work :)..

    But how will you know if the user is using a socks server?

  • CN October 2, 2009, 3:21 am

    When putting this code into a page, make sure has the “.php” extension, and not “.html” or “.htm”

  • Gopalakrishana October 18, 2010, 10:11 am

    Help me .I want try connect to computer in php programing .so please some example progarm and explain me
    Thank You

  • Gopalakrishnan October 18, 2010, 10:14 am

    Help me .I want try connect two computer in php programing using socket programing.so please some example progarm and explain me

  • Sumesh Narmath November 2, 2010, 1:39 pm

    Excellent one! Thanks for uploading…

  • zahid November 22, 2010, 4:01 pm

    Great … Thanks for the post .. I was thinking about how to determine the country from this ip address ?

  • RaphG March 9, 2011, 3:04 am

    Good code. It’s useful. Thanks for providing that one.

  • love May 12, 2011, 7:14 am

    Hello evry1….I wanna 9 the ip address of local machine in the form of 192.168…….but i m getting the server’s ip address……. so can any1 give me solution of dis problm

    THANKS IN ADVANCE

  • Nitesh Ahir May 18, 2011, 12:42 pm

    I am PHP web developer & CEO of web development company. I have excluded my office’s IP address from Google analytics.

    But, I am little bit confuse with data of Google analytics which still give me details regarding my office staff member’s visit.

    Can I make some integration to solve this issue? I want to check IP address of all visitors who are visiting my website in specific time frame.

    Can you give me some idea about it or not? May I do it with help of Google analytics?

  • Private101 August 9, 2011, 7:01 pm

    Hold on. You said it can get the IP address of someone using a proxy. NOT TRUE. I’ve just tested this on a variety of proxies, and it didn’t stop it. Totally useless extra line of code.

  • Tim November 8, 2011, 12:17 am

    I am enhancing my website with php code I have the following code that will display a message to the suspect of an sql injection what I would like to do is add some code to log the visitors IP address to a table called sql_injection_suspects where it will store the IP address and the time of the event and the value of the save string:

    $PUserid=strip_tags($_POST['lUSER']);
    	$Ppassword=Strip_tags($_POST['lPASSWORD']);
    	$sqlSafeUserid=mysqli_real_escape_string($con, $_POST['lUSER']);
    	//Query users table and Email table to see if either exist
    		$queryUserid = mysqli_query($con,"SELECT UserID, Password FROM tt_users WHERE UserID='$sqlSafeUserid'");
    		$rowUserid = mysqli_num_rows($queryUserid);
    			if (strpos($sqlSafeUserid, '\\') !== false)
    			{
    			
    			echo 'your attempt to inject sql into my database has been reported we have modified your input to: ' .$sqlSafeUserid .'';
    			echo '\'s and "s are not permited in feilds that query databases and will be prefixed with a \\';
    			echo 'Click here to leave my website with your head hanging in shame';
    			}
    			else
    			{// Some code to find the userid and validate the userid and password
    }
    
  • AlAa YoSeF March 21, 2012, 3:32 pm

    Hi every one my name is AlAa

    My problem with $_SERVER[‘remote_addr’]

    I’m not sure if I’m having a problem with the installation of PHP on the server or if there’s something that I’m not doing right in the code, but I am trying to capture the IP address of anyone that is trying to log into a secure part of a site. Regardless of my IP address, when I do:

    Code:

    echo $_SERVER[‘remote_addr’];

    It returns ‘192.168.1.1’. This is the first time I’ve written code that is being used on a Windows Server, so I don’t know if that has anything to do with it.

    I’ve run phpinfo(), and in the PHP Variables section, it shows “_SERVER[“REMOTE_ADDR”]” : 192.168.1.1. Does this mean that the php.ini file is setup wrong, or am I missing something?

    i am running my own server on windows 7 iis7.5 with php as fastcgi and i am behind a router with a dynamic ip not static and i am using
    http://www.no-ip.com/ that give me a link to my router and i am opening 80 port in my router forwarding it to my id address 192.168.1.5 and i have tested a php file that contains

    tested it using tor network that give me ip out of my network to test that file always give me the same result 192.168.1.1 i am trying to get IP address of the visitor and i asked someone of my friends to use this form it sends the same ip

    i hope someone tells me what i am doing wrong and the solution for this problem

    Thanks in advance

  • toodle bumpleskin May 11, 2012, 4:22 pm

    This is a good link, fixed the same error for me when I went through it!

  • PhpDev September 27, 2012, 11:38 pm

    Hay!!!

    It’s a great thing what you have given here… It solved my problem on Server.

    Again thank you very much for this.

    Thanks & Regards,
    PhpDev

  • Ganesh February 9, 2013, 4:25 am

    i want add in my blogger , blogspot site, please help me your code php not work with blogspot any other idea please give me, i want see my visitors ip..!

  • Mahi September 12, 2014, 7:28 am

    Am using this code but i am getting only last part of ip address( : : :1).how can i get full ip address..if any one know answer please reply.

  • Mi ip December 17, 2014, 11:51 am

    hi! Thanks for share!!! It,s work for me. How can i make a my ip widget ?
    Thanks again!

  • Naushad Ali December 22, 2014, 4:07 pm

    THIS IS NOT WORKING…
    KEEP TO UPDATE YOUR TUTORIAL…

  • seema February 4, 2015, 8:30 pm

    Hi,

    Iam using same code but its displaying Your IP address is : ::1 .Please help me.
    Thanks

    • srinu July 13, 2015, 12:34 am

      u r seeing in server comp so this way it will displays loopback address::
      check it in other computer you will see the ip .

  • Shubham Rana October 16, 2015, 10:19 am

    It’s a Nice and Simple Code…
    Thnx

  • zuber October 17, 2015, 9:45 am

    create a php page which show the ip address of client who is visting the website , on page load, alert my id address ,

    so plz help me dear sir plz help this problume

  • rufo February 3, 2016, 3:10 am

    nah. this gives ip address of the proxy server. Zzzz

Leave a Comment

You can use these HTML tags and attributes: <strong> <em> <pre> <code> <a href="" title="">


   Tagged with: , , , , , , , , , , ,