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

Posted on in Categories , , , , , , , , , , , last updated April 4, 2013

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:


Example: Sample code to get an IP address

Here is the PHP code:

 <title>What is my IP address?</title>
    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";

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.

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Share this on (or read 35 comments/add one below):

35 comment

      1. 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";
    1. 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.

      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.

  1. 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.

    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

  2. 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


  3. 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?

  4. 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.

  5. 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:

    	$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';
    			{// Some code to find the userid and validate the userid and password
  6. 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:


    echo $_SERVER[‘remote_addr’];

    It returns ‘’. 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”]” : 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 that give me a link to my router and i am opening 80 port in my router forwarding it to my id address 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 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

Leave a Comment