封裝常用訪客屬性獲取,支援鏈式調用,內建 User-Agent 解析與多 IP 來源兼容。
<?php
class GuestInfo {
private $ua;
private $ip;
public function __construct() {
$this->ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
$this->ip = $this->detectIP();
}
/** 解析瀏覽器語言 */
public function getLang(): string {
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '', 0, 4);
if (preg_match('/zh-c/i', $lang)) return '簡體中文';
if (preg_match('/zh/i', $lang)) return '繁體中文';
return 'English';
}
/** 解析瀏覽器類型 */
public function getBrowser(): string {
foreach (['MSIE', 'Firefox', 'Chrome', 'Safari', 'Opera', 'Edge'] as $b) {
if (stripos($this->ua, $b) !== false) return $b;
}
return 'Other';
}
/** 解析作業系統 */
public function getOS(): string {
foreach (['Windows', 'Mac', 'Linux', 'Unix', 'BSD', 'Android', 'iOS'] as $os) {
if (stripos($this->ua, $os) !== false) return $os;
}
return 'Other';
}
/** 獲取客戶端 IP(支援代理鏈) */
public function getIP(): string {
return $this->ip;
}
/** 使用新浪 IP 接口查詢地理位置 */
public function getLocationSina(): string {
$url = "https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip={$this->ip}";
$json = @file_get_contents($url);
if (!$json) return '查詢失敗';
$data = json_decode($json, true);
return $data['desc'] ?? ($data['province'].$data['city'].$data['district'].$data['isp']);
}
/** 使用騰訊 IP 接口查詢地理位置 */
public function getLocationQQ(): string {
$url = "https://ip.qq.com/cgi-bin/searchip?searchip1={$this->ip}";
$html = @file_get_contents($url);
if (!$html) return '查詢失敗';
$html = mb_convert_encoding($html, 'UTF-8', 'GB2312');
if (preg_match('@(.+?)@i', $html, $m)) return $m[1];
return '解析失敗';
}
private function detectIP(): string {
foreach (['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'] as $key) {
if (!empty($_SERVER[$key])) {
$ips = explode(',', $_SERVER[$key]);
return trim($ips[0]);
}
}
return 'Unknown';
}
}
// 使用示例
$guest = new GuestInfo();
echo "語言:{$guest->getLang()}
";
echo "瀏覽器:{$guest->getBrowser()}
";
echo "系統:{$guest->getOS()}
";
echo "IP:{$guest->getIP()}
";
echo "地理位置(新浪):{$guest->getLocationSina()}
";
echo "地理位置(騰訊):{$guest->getLocationQQ()}
";
?>
int.dpool.sina.com.cn 與騰訊 ip.qq.com 老接口已不穩定或停止服務。收集 IP 屬個人敏感信息,請在隱私政策說明用途、保留期限,並遵循 GDPR/《個人信息保護法》最小化原則:僅存儲脫敏後的地級市,不落庫完整 IP。