Getting real IP address in PHP

Advertisement

Are you using $_SERVER[‘REMOTE_ADDR’] to find the the client’s IP address in PHP? Well dude, you might be amazed to know that it may not return the true IP address of the client at all time. If your client is connected to the Internet through Proxy Server then $_SERVER[‘REMOTE_ADDR’] in PHP just returns the the IP address of the proxy server not of the client’s machine. So here is a simple function in PHP to find the real IP address of the client’s machine. There are extra Server variable which might be available to determine the exact IP address of the client’s machine in PHP, they are HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR.

Function to find real IP address in PHP

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

In this PHP function, first attempt is to get the direct IP address of client’s machine, if not available then try for forwarded for IP address using HTTP_X_FORWARDED_FOR. And if this is also not available, then finally get the IP address using REMOTE_ADDR.

Enter your email address and get free tutorials, tips and tricks of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

79 Comments on “Getting real IP address in PHP”

  • Mancub wrote on 1 January, 2008, 14:58

    1) You forgot to return $ip
    2) The problem with “HTTP_” headers is that they can easily be faked by the client. I could make your function belive I have any address, simply by sending it an X-Forwarded-For header. Here’s a little proof of concept (what you see is a script that echoes the return value of your function):

    ovidiu@ovidiu-desktop:~$ telnet localhost 80
    Trying 127.0.0.1…
    Connected to localhost.
    Escape character is ‘^]’.
    GET /delme/ HTTP/1.0

    HTTP/1.1 200 OK
    Date: Tue, 01 Jan 2008 14:54:49 GMT
    Server: Apache/2.2.4 (Ubuntu) PHP/5.2.3-1ubuntu6.2
    X-Powered-By: PHP/5.2.3-1ubuntu6.2
    Content-Length: 10
    Connection: close
    Content-Type: text/html

    127.0.0.1
    Connection closed by foreign host.
    ovidiu@ovidiu-desktop:~$ telnet localhost 80
    Trying 127.0.0.1…
    Connected to localhost.
    Escape character is ‘^]’.
    GET /delme/ HTTP/1.0
    X-Forwarded-For: 10.0.0.1

    HTTP/1.1 200 OK
    Date: Tue, 01 Jan 2008 14:55:27 GMT
    Server: Apache/2.2.4 (Ubuntu) PHP/5.2.3-1ubuntu6.2
    X-Powered-By: PHP/5.2.3-1ubuntu6.2
    Content-Length: 9
    Connection: close
    Content-Type: text/html

    10.0.0.1
    Connection closed by foreign host.
    ovidiu@ovidiu-desktop:~$

    Of course, in real life you wouldn’t use telnet. That was just a demonstration. You would send that header using cURL or fsockopen(). You could generate IP addresses randomly and fool the script every time.

  • Roshan wrote on 1 January, 2008, 17:57

    Thanks for figuring out the missing return statement, i’ve placed it in the code now.

    And you’re right about “HTTP_” headers, they can easily be faked.

    And, if you really want to fake the IP address then you can easily do it by browing the web anynomously with fake proxy server. You can find lots of such websites which allows you to browse the web anynomously.

  • Andrew wrote on 3 January, 2008, 21:50

    Although we are trusting the user not to spoof the HTTP headers, there is another flaw depending on what you want from this function. Very often you’ll just get a 192.168.*.* or 10.*.*.* address, telling you just the private address the client got from their DHCP server.

    I’ve written a Perl module that uses NetAddr::IP to determine if an IP address is private or public. I then check each of HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR and REMOTE_ADDR and return the first one that is public. If none of them are public I return REMOTE_ADDR.

  • Benji Madden wrote on 11 January, 2008, 23:51

    Hi there…Thanks for the nice read, keep up the interesting posts..what a nice Friday

  • Vipul wrote on 15 January, 2008, 13:29

    So, dear Php Gurus, what’s the final code? Please let me know.

  • Kim Smith wrote on 19 January, 2008, 12:08

    Hey!…Thanks for the nice read, keep up the interesting posts..what a nice Saturday

  • alexf2000 wrote on 25 January, 2008, 22:45

    There are much more headers that you can check if someone is using proxy. Thes is what I know:
    HTTP_PRAGMA, HTTP_XONNECTION, HTTP_CACHE_INFO, HTTP_XPROXY, HTTP_PROXY, HTTP_PROXY_CONNECTION, HTTP_CLIENT_IP, HTTP_VIA, HTTP_X_COMING_FROM, HTTP_X_FORWARDED_FOR, HTTP_X_FORWARDED, HTTP_COMING_FROM, HTTP_FORWARDED_FOR, HTTP_FORWARDED, ZHTTP_CACHE_CONTROL

  • Kim Smith wrote on 26 January, 2008, 16:01

    Hi there…Man i love reading your blog, interesting posts ! it was a great Saturday

  • Benji Madden wrote on 28 January, 2008, 11:51

    Hello…I Googled for benji smith, but found your page about …and have to say thanks. nice read.

  • tux86 wrote on 4 February, 2008, 16:11

    I love magic!

    function getIpAddress() {
    return (empty($_SERVER[‘HTTP_CLIENT_IP’])?(empty($_SERVER[‘HTTP_X_FORWARDED_FOR’])?
    $_SERVER[‘REMOTE_ADDR’]:$_SERVER[‘HTTP_X_FORWARDED_FOR’]):$_SERVER[‘HTTP_CLIENT_IP’]);
    }

  • sha wrote on 26 February, 2008, 7:05

    How to get the username and computer name using PHP..? Thanks In advance

  • Roshan wrote on 27 February, 2008, 7:31

    if the user is using WAN then you can use gethostbyaddr($_SERVER[‘REMOTE_ADDR’]); to get the hostname , in LAN it’s not possible.

  • ewanm89for wrote on 15 March, 2008, 5:27

    It is possible to find said information on a LAN, it just has to be a LAN with reverse DNS for all machines in the DNS servers. This should also be possible with zeroconf (also under many other names) networking, but I don’t believe PHP functions exist for this yet.

  • Haroon Ahmad wrote on 8 July, 2008, 5:55

    This function does not track Proxy servers. e.g I tested it using anonymous browsing site e.g hidemyass.com and the site bypassed this function by sending fake ip to me.

  • Roshan wrote on 8 July, 2008, 11:00

    Haroon…it’s true that this function can’t help from anonymous browsing man…

  • jayu wrote on 12 July, 2008, 12:23

    Hi Roshan,

    Thanks for your post. Its nice and useful.

    Thanks
    Jayu shah

  • Ed wrote on 14 July, 2008, 16:18

    This is a very interesting article. I do agree with what one user posted about DHCP. IP addresses such as 192.168 are for wireless network routers, and users on laptops like me can set their own IP address. This is NOT the IP address you want to collect when trying to get the users real IP address.

    In the end, I believe this function isn’t any more reliable that REMOTE_ADDR. It only shows hackers, spammers, and/or other malicious people how to block their IP address! If you want to go hardcore on getting their IP, I would suggest collecting all their possible IP addresses, including the HTTP_ and the REMOTE_ADDR. This script does not guarantee in any way that the IP address is right.
    Note besides using $_SERVER, this is also getenv.
    ex.
    $ip = getenv(‘REMOTE_ADDR’);

    If you really want to look more into this post, go to the page on PHP.net for the getenv function, there are numerous post very similar to this containing more complex functions to collect user’s IP address, I think mkaman has the best post, go to the page:
    http://us3.php.net/getenv

  • miaki wrote on 15 July, 2008, 7:45

    hi,
    how can i determine the country of the ip after i get the ip??
    thank’s

  • Roshan wrote on 15 July, 2008, 16:19

    @miaki…I’ll write a post about the soon..

  • Jerald wrote on 19 July, 2008, 6:25

    Thank alot! it helped me more bout IP in PHP

    thanks again! your code is usefull!

  • lolas wrote on 28 July, 2008, 17:17

    this code is very useful – thanks

  • Manabharana wrote on 5 August, 2008, 14:29

    Thank alot!

  • Mamoon Rahid wrote on 21 August, 2008, 7:01

    Thanks for useful information

  • ip address finding wrote on 30 September, 2008, 5:32

    But how do you get the IP of someone behind a proxy?

  • Roshan wrote on 30 September, 2008, 7:46

    @ip address finding – There is no way to find the IP address behind the anonymous proxy

  • Dwayne from Probably Sucks Blog wrote on 14 October, 2008, 1:12

    Very nice and simple method to return the IP address of a visitor to your site (most of the time).

    You can’t prevent the spoofing, it’s something you have to live with.

  • Vikas wrote on 20 October, 2008, 10:20

    For me,it did not give up my ip address.It just displays the loop back address.my ip inside LAN is 192.168.1.107.This is my internal IP.your script is just showing up the loop back address i.e., 127.0.0.1

  • A QUESTION FROM AN IDIOT wrote on 16 November, 2008, 3:39

    is there a way in php of knowing if the email address supplied by the user is existing?

    thanks…

    -A QUESTION FROM AN IDIOT

  • ducan wrote on 21 November, 2008, 6:28

    function getIpAddress() {
    return (empty($_SERVER[‘HTTP_CLIENT_IP’])?(empty($_SERVER[‘HTTP_X_FORWARDED_FOR’])?
    $_SERVER[‘REMOTE_ADDR’]:$_SERVER[‘HTTP_X_FORWARDED_FOR’]):$_SERVER[‘HTTP_CLIENT_IP’]);
    }

    isn’t useless because some proxy can cheat it, maybe java script is powerfull to handle this…

  • Roshan wrote on 21 November, 2008, 9:06

    @ducan – there is no way you can get rid of anonymous proxy..

  • Akram wrote on 30 December, 2008, 17:58

    I have go through this post and found very helpful but i still could not able to found the real ip. I use geoip api to track the country but when i get the ip from given function it could not return country and if i try http://www.whatismyip.com ip address it return the country correctly.
    thanks,
    akram.

  • feona wrote on 10 January, 2009, 14:21

    i use http://www.tracemyip.com so far it has given me the correct ip

  • Evan Donovan wrote on 30 January, 2009, 21:51

    Thanks so much for this code! It has been invaluable in creating a localization solution for our site.

  • Dennis Quek wrote on 5 February, 2009, 8:30

    So can I just copy and paste this PHP script onto another server, and then poll this script to return my own IP ?

  • Ben wrote on 5 February, 2009, 22:00

    This doesn’t work no matter what you do! I am behind a router and this script will give the router ip, but not mine!

  • tarang wrote on 12 March, 2009, 1:26

    hi
    couple of months ago u upload a ip locator code using which using user can easily implement that code in his website.i download the same.i just want to know y there is need to create the mysql database i.e “Visitormap” as we are using the database online.

  • Ricky wrote on 24 March, 2009, 13:51

    thanks tux86…………ur code works for me…..

  • Bagesh Singh wrote on 27 March, 2009, 12:39

    if we want to find the proper location using IP the how is it possible

  • fahad mahmood wrote on 16 April, 2009, 7:46

    thnx everybody, it will help me to filter my visits statistics more

  • Ben wrote on 17 April, 2009, 18:32

    None of anything listed here will give you the true user IP address if a user here thinks they have gotten it then the have no clue that they are talking about. This will give the public IP, but unless it is static then you cannot use it for any software security or anything else.

  • Rafael wrote on 23 May, 2009, 18:24

    Thank you! Excellent post. I look forward to its use and implementation in my website.

  • mescript wrote on 13 June, 2009, 13:02

    superb script

  • Advert wrote on 19 July, 2009, 12:22

    This could be a (potential) security exploit.
    Fake it like mentioned, but instead of using an IP address, fill it with junk.

  • Brandon wrote on 24 July, 2009, 3:24

    hi, just wanna say thx for sharing the code.

  • Ponjee wrote on 25 July, 2009, 7:50

    $_SERVER header almost always empty?

    http://www.thuiss.nl/iptest.php

  • haberler wrote on 26 July, 2009, 11:13

    i used this function and its working . Thank you.

  • Joshua K Roberson wrote on 2 August, 2009, 5:27

    Here are different ways to store an IP or an IP range as well as query for the IPs.
    http://strictcoder.blogspot.com/2009/08/different-ways-to-query-for-ip-in-your.html

  • Vladimir wrote on 5 September, 2009, 13:41

    Thanks for the help with code that I searched and interesting subject discussion.

  • Gautam wrote on 14 September, 2009, 5:12

    The final code is

  • classifier wrote on 20 September, 2009, 13:00

    As Andrew wrote on 3 January, 2008,
    I’ve written a Perl module that uses NetAddr::IP to determine if an IP address is private or public. I then check each of HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR and REMOTE_ADDR and return the first one that is public. If none of them are public I return REMOTE_ADDR.
    Any option to have this code shared ?

  • Vinayak wrote on 25 September, 2009, 9:29

    Thanks Dude! You helped alot! Keep rockingggggg

  • ravi wrote on 3 October, 2009, 16:35

    Hey!…Thanks for the nice read, keep up the interesting posts..what a nice Saturday

  • Jason wrote on 24 October, 2009, 14:08

    Brilliant – this will work 98% of the time – and if someone is trying to fake there IP address I don’t care.

  • bucabay wrote on 28 October, 2009, 8:17

    “is there a way in php of knowing if the email address supplied by the user is existing?”

    Yes, take a look at this PHP library – http://code.google.com/p/php-smtp-email-validation/
    It validates email addresses through SMTP.

  • Roger wrote on 10 November, 2009, 1:34

    I did the following, however, please note that I required the VPN detection and simply return VPN for local ips.

    function getRealIP($fakeip=false) {

    $ip = (!empty($_SERVER[‘HTTP_CLIENT_IP’])) ? (!empty($_SERVER[‘HTTP_X_FORWARDED_FOR’])) ? $_SERVER[‘HTTP_CLIENT_IP’] : preg_replace(‘/(?:,.*)/’, ”, $_SERVER[‘HTTP_X_FORWARDED_FOR’]):$_SERVER[‘REMOTE_ADDR’];
    $ip = (!$fakeip) ? $ip:$fakeip;

    // local check class b and c
    $patterns = array(“/(192).(168).(\d+).(\d+)/i”,”/(10).(\d+).(\d+).(\d+)/i”);
    foreach($patterns as $pattern) {
    if(preg_match($pattern,$ip)) {
    return “VPN”;
    }
    }
    // local check class a
    $parts = explode(“.”,$ip);
    if($parts[0]==172 && ($parts[1]>15 || $parts[1]<32)) {
    return "VPN";
    }
    return trim($ip);
    }

  • Travis wrote on 10 November, 2009, 3:49

    Ben: You’re an idiot, this script gets the physical location IP address for geostatistics. The person’s private IP (192.168.0.x) means absolutely nothing to a web page owner.

  • Michael wrote on 17 March, 2010, 8:33

    Thanks, very simple, fast and right way to get client`s ip adress. Got to use it in my scripts.

  • oyunlar1 wrote on 20 March, 2010, 7:59

    thanks.. used this in my webpage. its worked for me.

  • Ben wrote on 22 March, 2010, 14:20

    Actually your an idiot because if you have the public IP it licenses the entire site! So you must write really stupid code! your an idiot for not even knowing why someone would want the local IP! So you don’t really write applications you just work with web sites! So shut up idiot and continue to to write you TRASH code!

  • Ben wrote on 22 March, 2010, 14:22

    That was for you TRAVIS! Someone told you it was useless so you repeated it! D@MN you are STUPID!

  • Ben wrote on 22 March, 2010, 14:23

    Yes, I see you say WEB PAGE OWNER and since you don’t need to license the WEBSITE then it is no big deal! You must be ENTRY LEVEL!!!!

  • Ben wrote on 22 March, 2010, 14:34

    TRAVIS is the kind of person that uses TEMPLATE MONSTER to do most of his work so that is why he would NEVER have to license something! IF ANYONE LISTENS TO TRAVIS YOU WILL FAIL HE IS AN DUMB A$$!

    Explain to us TRAVIS how you license you PHP web applications? You don’t and you might script a little, but you are NOT a WEB APPLICATION DEVELOPER! I DO COLLECT THE PUBLIC IP AND THEN ALL THE LOCAL IP ADDRESSES AND MANAGE THE NUMBER OF TIMES A USER LOGS INTO MY APP USING A COMBINATION OF LOCAL IP, MAC ADDRESS AND USER INFO! MAN YOU ARE A DUMB A$$!

  • Anil Kumar Panigrahi wrote on 23 March, 2010, 8:42

    Hi Rohan,

    I got the real IP address, but i need Router IP Address (LAN IP) which is like http://www.find-ip-address.org/ , can you please suggest how to get the code using php code.

    Thank you in advance.

  • Motyar wrote on 23 March, 2010, 15:22

    @AnilKumarPanigrahi See they are using JAVA for it, download the class http://www.find-ip-address.org/MyAddress.class and use it as they are using. Its simple

  • json wrote on 12 April, 2010, 13:56

    Ben, calm down, this is a topic about PHP and ip addresses, not MAC addresses. If you are coding licensed works using PHP you are indeed an even bigger arse hole! You rant how you keep track of IP addresses, both public and private combinations in order to keep track of licensing…. don’t make me laugh! If that’s your licensing security solution it’s dumb in more ways than I can begin to break down. MAC codes I can see but IP, laughable!!!! Flame me all you like though kid as you obviously know more than someone with as much experienced as me ;) Commercial developer with PHP/Mysql/Linux/Apache since 1996.

Trackbacks

  1. Updates From Sam Jones » Blog Archive » links for 2008-01-25
  2. links for 2008-04-02 « ueXpected
  3. 8 useful server variables in PHP
  4. My Dict » 8 Useful server variables available in PHP
  5. Getting country , city name from IP address in PHP
  6. The html blog | 10 code snippets for PHP developers
  7. Get The IP Address Of A Visitor Through PHP | Talk In Code
  8. links for 2009-02-05 « Page 2
  9. 10 code snippets for PHP developers | Bookmarks
  10. Obtener Dirección IP con PHP » unijimpe
  11. How To Trace the Actual Client’s IP Address using PHP Script? | Engineering Blog
  12. Goldendevelopersworld.com » Blog Archive » 10 code snippets for PHP developers
  13. El Blog de JF » Obtener Dirección ip en PHP
  14. PHP ile IP Adresi Ö?renme | Ali OKTAY
Copyright © 2014 Roshan Bhattarai's Blog. All rights reserved.
Powered by WordPress.org, Custom Theme and ComFi.com Calling Card Company.