Php obtains the code of the region based on the ip address. Use php to obtain the ip address of the local machine, and use the php curl function to obtain the detailed region of the user. next let's take a look at the code. the code is as follows ** This function is used to get the client and IP * functionGetIP () first use php to get the ip address of the local machine, and then use the php curl function to get the detailed region of the user. let's take a look at the code below;
The code is as follows: |
|
/* * This function is used to obtain the client and IP address. */ Function GetIP () { If (! Empty ($ _ SERVER ["HTTP_CLIENT_IP"]) { $ Cip = $ _ SERVER ["HTTP_CLIENT_IP"]; } Else if (! Empty ($ _ SERVER ["HTTP_X_FORWARDED_FOR"]) { $ Cip = $ _ SERVER ["HTTP_X_FORWARDED_FOR"]; } Else if (! Empty ($ _ SERVER ["REMOTE_ADDR"]) { $ Cip = $ _ SERVER ["REMOTE_ADDR"]; } Else { $ Cip = ''; } Preg_match ("/[d.] {7, 15}/", $ cip, $ cips ); $ Cip = isset ($ cips [0])? $ Cips [0]: 'Unknown '; Unset ($ cips ); Return $ cip; } |
Method 1: Using the QQWry. Dat IP library, we are only fat
Use a simple method.
Example
Example 1:
The code is as follows: |
|
$ IpLocation = new IpLocation (); $ Client = $ IpLocation-> getlocation (); Print_r ($ client ); |
Example 2:
The code is as follows: |
|
$ IpLocation = new IpLocation ('../qqwry/QQWry. Dat '); $ Client = $ IpLocation-> getlocation ('192. 148.101.72 '); Print_r ($ client ); |
The specific IP library and Iplocation files are not described here.
Method 2: use the api
Example 1,
The code is as follows: |
|
/** * Obtain the IP region * Enter description here... * @ Param unknown_type $ ip */ Function GetArea ($ ip ){ $ Url = "http://ip168.com/ip? Ip = ". $ ip; $ Contents = file_get_contents ($ url ); // Preg_match_all ('/preg_match_all (' | Main site data :.* | ', $ Contents, $ rsR ); $ RsR [0] [0] = str_replace ("Main site data: "," ", $ rsR [0] [0]); $ RsR [0] [0] = str_replace (" "," ", $ RsR [0] [0]); Return $ rsR [0] [0]; } |
Example 2,
The following function uses the php curl function to obtain detailed regions from the network.
The code is as follows: |
|
Function lazdf ($ ip ){ $ Curl = curl_init (); Curl_setopt ($ curl, CURLOPT_URL, "http://www.ip138.com/ips138.asp? Ip = ". $ ip ); Curl_setopt ($ curl, CURLOPT_RETURNTRANSFER, 1 ); $ Ipdz = curl_exec ($ curl ); Curl_close ($ curl ); Preg_match ("/
- (.*?)
/I ", $ ipdz, $ jgarray );
Preg_match ("/Main site data of www.111cn.net: (. *)/I", $ jgarray [1], $ ipp );
Return"
Welcome from". $ Ipp [1]."Friends! ";
}
Echo lazdf (GetIP (); // output ip address
|
The handler code is as follows/** This function is used to obtain the client and IP */function GetIP ()...