PHP 实现“万能”的短网址还原

常见的短网址都是通过 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://url.cn/54VbB8h';    // 要还原的短网址
$orinalUrl = restoreUrl($shortUrl);
if($orinalUrl) {
    echo "短网址 {$shortUrl} 的还原结果:{$orinalUrl}";
} else {
    echo "短网址还原失败";
}
经过实测,该函数可以顺利实现下列短网址的还原:
https://url.cn
http://t.cn
http://uee.me
http://rrd.me
https://sohu.gg
https://dwz.cn
http://1t.click
http://dwz.win
http://qq.cn.hn
http://tb.cn.hn
http://jd.cn.hn
http://tinyurl.com
http://u6.gg
http://c7.gg
http://985.so
http://new.3qtt.cn
http://dwz1.cc
https://ml.mk
https://ml.mk
http://suo.im
https://suo.dog
http://sina.lt
http://mrw.so
不过,诸如 https://m.tb.cn/h.ew5NAEA 这种在前端使用 js 跳转的短网址就无能为力了~_~
版权声明:《 PHP 实现“万能”的短网址还原 》为作者远梦原创文章,转载请注明原文地址!
最后编辑:2020-5-5 14:05:38
分享到:
赞(0)
发表评论 / Comment

用心评论~

金玉良言 / Appraise
远梦站长已认证 SSVIP(终身)
2020-05-06 22:27
测试