This article mainly introduces how to obtain IP addresses and share geographic locations in PHP. in this article, the general interface of SINA is used for geographic location, if you need a script, you can refer to it and find that the script has not been written.
The classic logic is used to obtain IP addresses, and the common interface of SINA is used for geographic location.
For details about the usage method, see the source code:
The code is as follows:
<? Php
/*
* GET LOCATION BY SINA IP INTERFACE
*
* @ SOULTEARY 2013.04.14
*/
ClassIP
{
Private $ args = array ();
Function _ construct ()
{
$ This-> args = self: init_args (func_get_args ());
$ Ip = self: GetIP ();
$ Ret = preg_match_all ('/(\ d + \.) {3} \ d +/I', $ ip, $ result );
If (! $ Ret ){
Returnfalse;
} Else {
$ Result = $ result [0];
}
If (isset ($ this-> args ['onlyip']) & $ this-> args ['onlyip'] = true ){
If (isset ($ this-> args ['format']) & $ this-> args ['format'] = 'json '){
$ Result = json_encode ($ result );
} Else {
$ Result = implode (',', $ result );
}
If (isset ($ this-> args ['echo ']) & $ this-> args ['echo'] = true ){
Echo $ result;
Returntrue;
} Else {
Return $ result;
}
} Else {
$ ApiURL = 'http: // int.dpool.sina.com.cn/iplookup/iplookup.php? Ip = '. $ result [0];
If (isset ($ this-> args ['format']) & $ this-> args ['format'] = 'json '){
$ ApiURL. = '& format = json ';
$ Return = $ this-> ipCURL ($ apiURL );
} Else {
$ Return = $ this-> ipCURL ($ apiURL );
$ Return = iconv ("GBK // IGNORE", "UTF-8", $ return );
}
If (isset ($ this-> args ['echo ']) & $ this-> args ['echo'] = true ){
Echo $ return;
Returntrue;
} Else {
Return $ return;
}
}
}
Public functioninit_args ($ args)
{
$ Result = array ();
For ($ I = 0, $ n = count ($ args); $ I <$ n; $ I ++ ){
$ Result = self: associative_push ($ args [$ I], $ result );
}
Return $ result;
}
Public functionassociative_push ($ arr, $ tmp)
{
If (is_array ($ tmp )){
Foreach ($ tmpas $ key => $ value ){
$ Arr [$ key] = $ value;
}
Return $ arr;
}
Returnfalse;
}
Public functionGetIP ()
{
If (isset ($ _ SERVER ['http _ X_FORWARDED_FOR ']) & $ _ SERVER ['http _ X_FORWARDED_FOR '] & strcasecmp ($ _ SERVER ['http _ X_FORWARDED_FOR'], 'Unknown ')){
Return $ _ SERVER ['http _ X_FORWARDED_FOR '];
} Elseif (isset ($ _ SERVER ['remote _ ADDR ']) & $ _ SERVER ['remote _ ADDR '] & strcasecmp ($ _ SERVER ['remote _ ADDR'], 'Unknown ')){
Return $ _ SERVER ['remote _ ADDR '];
}
}
Private functionipCURL ($ url)
{
$ Ch = curl_init ();
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_HEADER, 0 );
Ob_start ();
Curl_exec ($ ch );
Curl_close ($ ch );
$ Result = ob_get_contents ();
Ob_end_clean ();
Return $ result;
}
}
?>
Demo