How can one access the redirected URL when it is not included in the header response in a cURL request?
When the redirected URL is not included in the header response of a cURL request, you can access it by setting the CURLOPT_FOLLOWLOCATION option to true in your cURL request. This will automatically follow any redirections and return the final URL in the response. Additionally, you can use the CURLOPT_RETURNTRANSFER option to return the response as a string, which you can then parse to extract the final URL.
$url = 'http://example.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if($response === false){
echo 'cURL error: ' . curl_error($ch);
} else {
$final_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
echo 'Final URL: ' . $final_url;
}
curl_close($ch);
Related Questions
- How can the PHP configuration settings in php.ini impact the ability to upload multiple files?
- How can PHP sessions be effectively managed in larger projects to avoid overreliance on the $_SESSION superglobal?
- What are best practices for handling long-running shell commands in PHP to prevent page timeouts or user confusion?