PHP obtains the client IP address and obtains the IP address information.

Source: Internet
Author: User
This article describes how to use PHP to obtain the IP address of the client and obtain the IP address information. it is very practical. For more information, see. The code is concise and the function is very practical. here we will not talk nonsense, but we will provide it directly:

The code is as follows:


<? Php
/**
* Obtain the client IP address
* @ Param integer $ type return type 0: string, 1: long
* @ Return string | long
*/
Function getClientIp ($ type = 0 ){
$ Ip = NULL;
If (isset ($ _ SERVER ['http _ X_FORWARDED_FOR ']) {
$ Arr = explode (',', $ _ SERVER ['http _ X_FORWARDED_FOR ']);
$ Pos = array_search ('Unknown ', $ arr );
If (false! ==$ Pos) unset ($ arr [$ pos]);
$ Ip = trim ($ arr [0]);
} Elseif (isset ($ _ SERVER ['http _ CLIENT_IP ']) {
$ Ip = $ _ SERVER ['http _ CLIENT_IP '];
} Elseif (isset ($ _ SERVER ['remote _ ADDR ']) {
$ Ip = $ _ SERVER ['remote _ ADDR '];
}
$ Long = sprintf ("% u", ip2long ($ ip ));
$ Ip = $ long? Array ($ ip, $ long): array ('0. 0.0.0 ', 0 );
Return $ ip [$ type];
}
/**
* Obtain IP information
* @ Param string | long $ ip address
* @ Return array
*/
Function getIpInfo ($ ip)
{
If (is_long ($ ip )){
$ Ip = long2ip ($ ip );
}
$ Api = 'http: // ip.taobao.com/service/getipinfo.php ';
$ Ret = file_get_contents ($ api .'? Ip = '. $ ip );
$ Ret = json_decode ($ ret, true );
If ($ ret ['code'] = 0 ){
Return $ ret ['data'];
}
Return array ();
}

The above is all the content of this article. I hope you will like it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.