多数短网址都是通过 301 或 302 跳转到目标网站的,我们可以使用 PHP 的 curl_getinfo
来取得 header 中的重定向地址,即短网址的原网址。此思路来自孟坤博客。
/*** * 短网址还原函数 * @param $shortUrl 短网址 * @return 原始网址 | 空(还原失败或非短网址) */ function restoreUrl($shortUrl) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $shortUrl); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0'); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_NOBODY, false); curl_setopt($curl, CURLOPT_TIMEOUT, 15); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($curl, CURLOPT_ENCODING, 'gzip'); $data = curl_exec($curl); $curlInfo = curl_getinfo($curl); curl_close($curl); if($curlInfo['http_code'] == 301 || $curlInfo['http_code'] == 302) { return $curlInfo['redirect_url']; } return ''; }
$shortUrl = 'https://4m.cn/UkZOq'; // 要还原的短网址 $orinalUrl = restoreUrl($shortUrl); if($orinalUrl) { echo "短网址 {$shortUrl} 的还原结果:{$orinalUrl}"; } else { echo "短网址还原失败"; }
我把此功能做成一个api,供大家调用:https://api.jishusongshu.com/longurl.php?url=
api文档:https://api.jishusongshu.com/longurl.html
源码如下:
参考资料:孟坤博客-PHP 实现“万能”的短网址还原
测试回复查看内容