Reputation: 53
I'm using curl to make php send an http request to some website somewhere and have set CURLOPT_FOLLOWLOCATION to 1 so that it follows redirects. How then, can I find out where it was eventually redirected?
Upvotes: 5
Views: 976
Reputation: 5919
test this snippets of code. It works fine for me :
$urls = array(
'http://www.apple.com/imac',
'http://www.google.com/'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
foreach($urls as $url) {
curl_setopt($ch, CURLOPT_URL, $url);
$out = curl_exec($ch);
// line endings is the wonkiest piece of this whole thing
$out = str_replace("\r", "", $out);
// only look at the headers
$headers_end = strpos($out, "\n\n");
if( $headers_end !== false ) {
$out = substr($out, 0, $headers_end);
}
$headers = explode("\n", $out);
foreach($headers as $header) {
if( substr($header, 0, 10) == "Location: " ) {
$target = substr($header, 10);
echo "[$url] redirects to [$target]<br>";
continue 2;
}
}
echo "[$url] does not redirect<br>";
}
Upvotes: 0
Reputation: 9196
If you do not need the final body you can do it this way:
Set CURLOPT_HEADER
and CURLOPT_NOBODY
. The header "Location" should be returned and will contain the new url. Then perform the request with the new url if necessary.
Upvotes: -1
Reputation: 714
$ch = curl_init( "http://websitethatredirects.com" );
$curlParams = array(
CURLOPT_FOLLOWLOCATION => true,
);
curl_setopt_array( $ch, $curlParams );
$ret = curl_exec( $ch );
$info = curl_getinfo( $ch );
print $info['url'];
This will show you the URL that you were ultimately redirected to.
Upvotes: 2
Reputation: 154543
You can do something like:
curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // returns the last effective URL
Upvotes: 6