1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| <?php
header('Access-Control-Allow-Origin:*'); header('Content-type: application/json');
define('SINA_APPKEY', '1335371408');
$url = $_GET['url'] ?? null; if (!$url) { sendResponse(201, 'URL参数错误'); exit; }
$url = filterUrl($url); if (!$url) { sendResponse(201, '过滤后的URL无效'); exit; }
$short = sinaShortenUrl($url); if (!$short) { sendResponse(201, '无法获取短网址'); exit; }
$long = sinaExpandUrl($short); sendResponse(200, '成功', ['short' => $short, 'long' => $long]);
function curlQuery($url, $headers = ["Content-type: application/json"]) { $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => $url, CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_TIMEOUT => 15 ]); $result = curl_exec($curl); curl_close($curl); return $result; }
function filterUrl($url) { $url = trim(strtolower($url)); if (strpos($url, 'http://') !== 0 && strpos($url, 'https://') !== 0) { $url = 'http://' . $url; } return urlencode($url); }
function sinaShortenUrl($url) { $requestUrl = 'http://api.t.sina.com.cn/short_url/shorten.json?source=' . SINA_APPKEY . '&url_long=' . $url; $result = curlQuery($requestUrl); $json = json_decode($result, true); return $json[0]['url_short'] ?? false; }
function sinaExpandUrl($url) { $requestUrl = 'http://api.t.sina.com.cn/short_url/expand.json?source=' . SINA_APPKEY . '&url_short=' . $url; $result = curlQuery($requestUrl); $json = json_decode($result, true); return $json[0]['url_long'] ?? false; }
function sendResponse($code, $msg, $data = null) { echo json_encode([ 'code' => $code, 'msg' => $msg, 'data' => $data ], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE); exit; }
|