这篇文章将为大家详细讲解有关PHP获取重定向URL的几种方法是什么,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
PHP 获取重定向 URL 的方法
1. get_headers()
函数
get_headers()
函数可以获取指定 URL 的响应头信息,其中包括重定向 URL。
语法:
$headers = get_headers($url, true);
示例:
$url = "https://example.com";
$headers = get_headers($url, true);
if (isset($headers["Location"])) {
$redirect_url = $headers["Location"];
}
2. stream_context_create()
和 file_get_contents()
函数
stream_context_create()
函数允许我们创建一个流上下文,其中可以指定重定向的选项。然后,我们可以使用 file_get_contents()
函数读取 URL 的内容,并获取重定向 URL。
语法:
$context = stream_context_create(["http" => ["follow_location" => true]]);
$content = file_get_contents($url, false, $context);
示例:
$url = "https://example.com";
$context = stream_context_create(["http" => ["follow_location" => true]]);
$content = file_get_contents($url, false, $context);
// 使用正则表达式匹配重定向 URL
$redirect_url = preg_match("/Location: (.*)
/", $http_response_header[0], $matches) ? $matches[1] : null;
3. curl
函数
curl
函数是 PHP 中一个强大的网络库,它也支持重定向。我们可以在 cURL 请求中设置 CURLOPT_FOLLOWLOCATION
选项来启用重定向。
语法:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
示例:
$url = "https://example.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
// 使用正则表达式匹配重定向 URL
$redirect_url = preg_match("/Location: (.*)
/", $http_response_header[0], $matches) ? $matches[1] : null;
4. HTTP 响应代码
某些 HTTP 响应代码(例如 301、302)表示重定向。我们可以检查响应代码以确定是否发生了重定向,然后使用 Location
头来获取重定向 URL。
语法:
$response = get_headers($url);
$status_code = $response[0];
if ($status_code == "HTTP/1.1 301 Moved Permanently" || $status_code == "HTTP/1.1 302 Found") {
$redirect_url = $response["Location"];
}
示例:
$url = "https://example.com";
$response = get_headers($url);
$status_code = $response[0];
if ($status_code == "HTTP/1.1 301 Moved Permanently" || $status_code == "HTTP/1.1 302 Found") {
$redirect_url = $response["Location"];
}
以上就是PHP获取重定向URL的几种方法是什么的详细内容,更多请关注编程学习网其它相关文章!