PHP获取302跳转后的真实地址

1、第一种   使用 get_headers

(PHP 5, PHP 7)

get_headers — 取得服务器响应一个 HTTP 请求所发送的所有标头

参数
url 必需。目标URL
format 可选。如果将可选的 format 参数设为 1,则 get_headers() 会解析相应的信息并设定数组的键名。

返回值

返回包含有服务器响应一个 HTTP 请求所发送标头的索引或关联数组,如果失败则返回 FALSE

详情请看考手册:get_headers

$url = "https://www.baidu.com/link?url=32j8_-sKSyO_5cpK0AQHwbD1DW3u8nXucwjWtAKmODiM5a9Z1BF2CHWqcmMBKwo5&wd=&eqid=e37d71b8000f7d15000000045f923b42";
$headers = get_headers($url, 1);
if (isset($headers['Location'])) {
    echo $headers['Location'];
}

2、第二种  使用curl

$url = "https://www.baidu.com/link?url=32j8_-sKSyO_5cpK0AQHwbD1DW3u8nXucwjWtAKmODiM5a9Z1BF2CHWqcmMBKwo5&wd=&eqid=e37d71b8000f7d15000000045f923b42";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);  //是否抓取跳转后的页面
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不从证书中检查SSL加密算法是否存在
$res = curl_exec($ch);
$info = curl_getinfo($ch);
$retURL = $info['url'];   // 跳转后的 URL 信息
curl_close($ch);

有需要的朋友拿走不谢,记得点赞收藏 关注不迷路哦

猜你喜欢

转载自blog.csdn.net/liuxl57805678/article/details/109237010