我使用php和curl来获取重定向url,我有输出,但它显示我在最后一次重定向时找不到错误302(我必须重定向两次url),这是我的php代码,< / p>
<?php
$url = 'http://www.example.com/kdjf/ksdjfk/file';
function getred($url){
$ch = curl_init($url);
curl_exec($ch);
if (!curl_errno($ch)) {
$info = curl_getinfo($ch);
return $info['redirect_url'];
}
curl_close($ch);
}
$dds=getred($url);
echo getred($dds);
?>
$ dds在example.com通过后给了我下一个重定向,然后我再次使用了重定向功能,而且我有一个错误,
<html>
<head>
<title>302 Found</title>
</head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx</center>
</body>
</html>
http://www.example.org/skdfjk/new_file.html
如何只获得http://www.example.org/skdfjk/new_file.html
而没有任何错误。或html标签。
答案 0 :(得分:0)
我使用了两个函数来做这件事,它对我有用。
function getRedirectUrlss($url){
$redirect_url = null;
$url_parts = @parse_url($url);
if (!$url_parts) return false;
if (!isset($url_parts['host'])) return false; //can't process relative URLs
if (!isset($url_parts['path'])) $url_parts['path'] = '/';
$sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80), $errno, $errstr, 30);
if (!$sock) return false;
$request = "HEAD " . $url_parts['path'] . (isset($url_parts['query']) ? '?'.$url_parts['query'] : '') . " HTTP/1.1\r\n";
$request .= 'Host: ' . $url_parts['host'] . "\r\n";
$request .= "Connection: Close\r\n\r\n";
fwrite($sock, $request);
$response = '';
while(!feof($sock)) $response .= fread($sock, 8192);
fclose($sock);
if (preg_match('/^Location: (.+?)$/m', $response, $matches)){
if ( substr($matches[1], 0, 1) == "/" )
return $url_parts['scheme'] . "://" . $url_parts['host'] . trim($matches[1]);
else
return trim($matches[1]);
} else {
return false;
}
}
function getred($url){
$ch = curl_init($url);
curl_exec($ch);
if (!curl_errno($ch)) {
$info = curl_getinfo($ch);
return $info['redirect_url'];
}
curl_close($ch);
}
$dds=getred($url);
$urls= getRedirectUrlss($dds);
echo $urls;
答案 1 :(得分:0)
使用ob_clean(),ob_end_clean()和ob_get_clean()。在回显输出之前的功能