The simplest way to get the client IP address is to directly use REMOTE_ADDR, but this kind of IP address cannot be obtained if there is a proxy IP address, so we need to use HTTP_X_FORWARDED_FOR to obtain it, next, I will introduce you to a function for obtaining IP addresses from the client. Our simplest method is to directly use REMOTE_ADDR, but this method cannot be obtained if a proxy IP address exists, therefore, we need to use HTTP_X_FORWARDED_FOR to obtain the IP address. Next we will introduce a function for getting the IP address.
Script ec (2); script
Simplest practice
| The Code is as follows: |
|
|
Function getRealIpAddr ()
{
If (! Emptyempty ($ _ SERVER ['HTTP _ CLIENT_IP '])
{
$ Ip = $ _ SERVER ['HTTP _ CLIENT_IP '];
}
Elseif (! Emptyempty ($ _ 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;
}
|
I wrote this myself.
| The Code is as follows: |
|
If (getenv ('HTTP _ CLIENT_IP ') & strcasecmp (getenv ('HTTP _ CLIENT_IP'), 'unknown ')){
$ Onlineip = getenv ('HTTP _ CLIENT_IP ');
} Elseif (getenv ('HTTP _ X_FORWARDED_FOR ') & strcasecmp (getenv ('HTTP _ X_FORWARDED_FOR'), 'unknown ')){
$ Onlineip = getenv ('HTTP _ X_FORWARDED_FOR ');
} Elseif (getenv ('remote _ ADDR ') & strcasecmp (getenv ('remote _ ADDR'), 'unknown ')){
$ Onlineip = getenv ('remote _ ADDR ');
} Elseif (isset ($ _ SERVER ['remote _ ADDR ']) & $ _ SERVER ['remote _ ADDR '] & strcasecmp ($ _ SERVER ['remote _ ADDR'], 'unknown ')){
$ Onlineip = $ _ SERVER ['remote _ ADDR '];
}
Echo $ onlineip;
?> |
However, Baidu found
Instance
| The Code is as follows: |
|
|
Function real_ip (){
Static $ realip = NULL;
If ($ realip! = NULL ){
Return $ realip;
}
If (isset ($ _ SERVER )){
If (isset ($ _ SERVER ['HTTP _ X_FORWARDED_FOR ']) {
$ Arr = explode (',', $ _ SERVER ['HTTP _ X_FORWARDED_FOR ']);
/* Obtain the first non-unknown valid IP string in X-Forwarded-*/
Foreach ($ arr AS $ ip ){
$ Ip = trim ($ ip );
If ($ ip! = 'Unknown '){
$ Realip = $ ip;
Break;
}
}
} Elseif (isset ($ _ SERVER ['HTTP _ CLIENT_IP ']) {
$ Realip = $ _ SERVER ['HTTP _ CLIENT_IP '];
} Else {
If (isset ($ _ SERVER ['remote _ ADDR ']) {
$ Realip = $ _ SERVER ['remote _ ADDR '];
} Else {
$ Realip = '0. 0.0.0 ';
}
}
} Else {
If (getenv ('HTTP _ X_FORWARDED_FOR ')){
$ Realip = getenv ('HTTP _ X_FORWARDED_FOR ');
} Elseif (getenv ('HTTP _ CLIENT_IP ')){
$ Realip = getenv ('HTTP _ CLIENT_IP ');
} Else {
$ Realip = getenv ('remote _ ADDR ');
}
}
Preg_match ("/[d.] {7, 15}/", $ realip, $ onlineip );
$ Realip =! Empty ($ onlineip [0])? $ Onlineip [0]: '0. 0.0.0 ';
Return $ realip;
} |