We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

mifly on 01/01/08


Tagged

ipAddress


Versions (?)


Who likes this?

16 people have marked this snippet as a favorite

luman
heinz1959
tylerhall
brent-man
johnself
vali29
kdaviesnz
skywalker
axthos
JimiJay
hochitom
SpinZ
Keef
pixelhandler
grn
sumandahal


Getting real IP address in PHP


Published in: PHP 


URL: http://snipplr.com/extras/

Are you using $SERVER['REMOTEADDR'] to find the the client's IP address? 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['REMOTEADDR'] 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.

  1. function getRealIpAddr()
  2. {
  3. if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
  4. {
  5. $ip=$_SERVER['HTTP_CLIENT_IP'];
  6. }
  7. elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
  8. //to check ip is pass from proxy
  9. {
  10. $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
  11. }
  12. else
  13. {
  14. $ip=$_SERVER['REMOTE_ADDR'];
  15. }
  16. return $ip;
  17. }

Report this snippet 

Comments

RSS Icon Subscribe to comments
Posted By: arkin on January 3, 2008

This is not a secure way of getting the real ip address. This is how IP forgery can happen because the first 2 are passed in a users headers.

Posted By: kdaviesnz on January 14, 2008

One line alternative: $ip = !empty($SERVER['HTTPCLIENTIP'])?$SERVER['HTTPCLIENTIP']:(!empty($SERVER['HTTPXFORWARDEDFOR'])?$SERVER['HTTPXFORWARDEDFOR']:$SERVER['REMOTEADDR']);

Posted By: section31 on July 6, 2008

Agreed, it's very rare that you need to get their forwarded ip.

You need to login to post a comment.