ahm*_*med 35 html php curl http
当HTTP状态代码为302时,如何使用cURL获取目标URL?
<?PHP
$url = "http://www.ecs.soton.ac.uk/news/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$html = curl_exec($ch);
$status_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($status_code=302 or $status_code=301){
$url = "";
// I want to to get the destination url
}
curl_close($ch);
?>
Run Code Online (Sandbox Code Playgroud)
Tam*_*iev 50
您可以使用:
echo curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
Run Code Online (Sandbox Code Playgroud)
Lek*_*sat 23
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE); // We'll parse redirect url from header.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE); // We want to just get redirect url but not to follow it.
$response = curl_exec($ch);
preg_match_all('/^Location:(.*)$/mi', $response, $matches);
curl_close($ch);
echo !empty($matches[1]) ? trim($matches[1][0]) : 'No redirect found';
Run Code Online (Sandbox Code Playgroud)
有点过时的回复,但想要展示一个完整的工作示例,其中一些解决方案是:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); //set url
curl_setopt($ch, CURLOPT_HEADER, true); //get header
curl_setopt($ch, CURLOPT_NOBODY, true); //do not include response body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //do not show in browser the response
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //follow any redirects
curl_exec($ch);
$new_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); //extract the url from the header response
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)
这适用于任何重定向,例如301或302,但是在404上它只返回请求的原始URL(因为它没有找到).这可用于更新或删除您网站的链接.无论如何,这是我的需要.
| 归档时间: |
|
| 查看次数: |
58682 次 |
| 最近记录: |