Friday 4 March 2011

Getting visitor IP address with PHP

We can easily get IP Address of visitor with php environment variables .User IP Address was stored in following php Environment variables $_SERVER['REMOTE_ADDR'],$_SERVER['HTTP_CLIENT_IP'] and $_SERVER['HTTP_X_FORWARDED_FOR'].

most common practice for to get IP address of visitor with php is













1<?php










2$ip=$_SERVER['REMOTE_ADDR'];










3echo 'User ip Address'.$ip;










4?>




We can’t trust above script generated ip address if user use proxy sever it simple return proxy IP.So to get user’s real IP address we should check for proxy and shared servers first.i have wrote one php function to get real IP address of visitor.











01<?php










02function GetUserIp() {










03if(isset($_SERVER['HTTP_CLIENT_IP'])) // check for shared servers










04{










05$ip = $_SERVER['HTTP_CLIENT_IP'];










06}










07elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) // check for proxy servers










08{










09$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];










10} else {










11$ip = $_SERVER['REMOTE_ADDR']; // general method










12}










13list($ip) = explode(',',$ip);










14return $ip;










15}










16echo GetUserIp(); // print ip address









17?>

No comments:

Post a Comment