$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 返回结果而不直接输出
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 设置最大延迟为3秒
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略https证书验证
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 忽略https主机名验证
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // 设置不自动跳转
curl_setopt($ch, CURLOPT_HTTPHEADER, getHeaders4You());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // 告诉cURL不要跟随重定向
curl_setopt($ch, CURLOPT_HEADER, true); // 将响应头包含在输出中
//curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt"); // 设置 cookie 文件的读取路径
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies2.txt"); // 设置 cookie 文件的保存路径
$data = curl_exec($ch);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
echo "cURL Error: " . $error_msg . brStr();
$data = ''; // 如果发生错误,则返回空字符
} else {
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // 获取 HTTP 响应码 302
echo "HTTP Status Code: " . $httpCode . "\n";
}
echo "HTTP Status Code: " . $httpCode . "\n";
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); // 获取响应头部大小
$headers = substr($data, 0, $header_size); // 获取响应头部
$body = substr($data, $header_size); // 获取响应正文(html)
// 分割头部和正文,以便单独处理
$headers_array = explode("\r\n", $headers);
// 循环遍历头部,找到 Set-Cookie 行
foreach ($headers_array as $header) {
if (strpos($header, 'Set-Cookie:') === 0) {
echo $header . "\n"; // 打印出 Set-Cookie 头部的值
}
}
// 从响应头部中提取 Location 字段
if (preg_match('/Location:(.*?)\n/', $headers, $matches)) {
$redirectUrl = trim($matches[1]);
echo "Redirect URL is: $redirectUrl\n";
} else {
echo "Location header not found.\n";
}
function getHeaders4You()
{
$headers = [
"accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
"accept-language: zh-CN,zh;q=0.9",
"cache-control: no-cache",
"pragma: no-cache",
"sec-ch-ua: \"Chromium\";v=\"124\", \"Google Chrome\";v=\"124\", \"Not-A.Brand\";v=\"99\"",
"sec-ch-ua-mobile: ?0",
"sec-ch-ua-platform: \"Windows\"",
"sec-fetch-dest: document",
"sec-fetch-mode: navigate",
"sec-fetch-site: none",
"sec-fetch-user: ?1",
"upgrade-insecure-requests: 1",
#"Referer:https://www.baidu.com/",
];
return $headers;
}