Reputation: 832
If I visit the website https://example.com/a/abc?name=jack
, I get redirected to https://example.com/b/uuid-123
. I want only the end URL which is https://example.com/b/uuid-123
. The contents of https://example.com/b/uuid-123
is about 1mb but I am not interested in the content. I only want the redirected URL and not the content. How can I get the redirected URL without having to also load the 1mb of content which wastes my bandwidth and time.
I have seen a few questions about redirection on stackoverflow but nothing on how not to load the content.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com/a/abc?name=jack');
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
$end_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
echo('End URL is ' . $end_url);
Upvotes: 1
Views: 418
Reputation: 714
For clarity i'll add it as an answer as well.
You can tell curl to only retrieve the headers by setting the CURLOPT_NOBODY
to true
.
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_HEADER, true);
From these headers you can parse the location
part to get the redirected URL.
Edit for potential future readers: CURLOPT_HEADER
will also need to be set to true
, i had left this out as you already had it included in your code.
Upvotes: 1