<?php
require_once 'Pinyin.php'; // 需自行引入拼音類(如 overtrue/pinyin)
// 1. 獲取 IP
function getClientIP(): string {
foreach (['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'] as $key) {
if (!empty($_SERVER[$key])) {
$ips = array_map('trim', explode(',', $_SERVER[$key]));
foreach ($ips as $ip) {
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return $ip;
}
}
}
}
return '127.0.0.1';
}
// 2. 調用新浪 API
function getLocationBySina(string $ip): ?array {
$url = "https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip={$ip}";
$ctx = stream_context_create(['http' => ['timeout' => 5]]);
$json = @file_get_contents($url, false, $ctx);
return $json ? json_decode($json, true) : null;
}
// 3. 拼音轉換(使用 overtrue/pinyin)
$pinyin = new Overtrue\Pinyin\Pinyin();
$ip = getClientIP();
$loc = getLocationBySina($ip);
$city = $loc['city'] ?? '未知';
if ($loc['ret'] ?? 0 == -1) $city = '未知';
// 4. 多音字修正映射表
$polyphoneMap = [
'重慶' => 'chongqing', '石坊' => 'shifang', '成都' => 'chengdu',
'樂山' => 'leshan', '濬縣' => 'xunxian', '廈門' => 'xiamen',
'長沙' => 'changsha', '玉里' => 'yuli', '朝陽' => 'chaoyang',
'單縣' => 'shanxian',
];
$cityPinyin = $polyphoneMap[$city] ?? strtolower($pinyin->permalink($city)); // permalink 輸出小寫無分隔
// 5. 重定向
$targetUrl = "https://{$cityPinyin}.example.com"; // 替換為實際域名規則
header("Location: {$targetUrl}");
exit;
composer require overtrue/pinyin
Pinyin::permalink() 直接生成適合 URL 的小寫拼音,無需手動 strtolower。
project/
├── composer.json
├── src/
│ └── CityRedirector.php
└── public/
└── index.php // 入口文件,僅調用 CityRedirector::run()