This article mainly introduces how to obtain IP addresses and share geographic locations in PHP. In this article, location uses the common interface of SINA. For more information, see
This article mainly introduces how to obtain IP addresses and share geographic locations in PHP. In this article, location uses the common interface of SINA. For more information, see
I found that a script was not written before, and I simply expanded it.
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