Is there a way to do redirect in PHP using curl? I looked some examples but none of them works in my case. I need to login to url1, then redirect me to url2. (url_1 is the site of my IP camera, url_2 is my page which contains the iframe of url_1, in order to see the content of url_1 in my page, authentication is required)
Please check my code and tell me where I did wrong, many thanks!
<?
$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;
?>
I also print the $info here:
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 ( )
)
and the $redir is:url_1