有没有办法在 PHP 中使用 curl 进行重定向?我看了一些例子,但在我的情况下它们都不起作用。我需要登录到 url1,然后将我重定向到 url2。(url_1是我的IP摄像头的站点,url_2是我的页面,其中包含url_1的iframe,为了在我的页面中看到url_1的内容,需要认证)
请检查我的代码并告诉我哪里做错了,非常感谢!
<?
$url = 'url_1';
$username = 'admin';
$password = '888888';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
curl_setopt($ch, CURLOPT_REFERER, "url_2");
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type:application/x-www-form-urlencoded"));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$a = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
print_r($info);
$headers = explode("\n",$a);
$redir = $url;
// loop through the headers and check for a Location: str
$j = count($headers);
for($i = 0; $i < $j; $i++){
// if we find the Location header strip it and fill the redir var
if(strpos($headers[$i],"Location:") !== false){
$redir = trim(str_replace("Location:","",$headers[$i]));
break;
}
}
// do whatever you want with the result
echo $redir;
?>
我还在这里打印 $info:
Array (
[url] => url_1
[content_type] => text/html
[http_code] => 200
[header_size] => 180
[request_size] => 288
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.016
[namelookup_time] => 0
[connect_time] => 0
[pretransfer_time] => 0
[size_upload] => 0
[size_download] => 6379
[speed_download] => 398687
[speed_upload] => 0
[download_content_length] => 6379
[upload_content_length] => 0
[starttransfer_time] => 0.016
[redirect_time] => 0
[certinfo] => Array ( )
)
$redir 是:url_1