In the provided PHP code snippet, what modifications can be made to accurately retrieve and display redirected URLs using cURL?
The issue with the provided code snippet is that it does not follow the redirects when making a cURL request, resulting in the final redirected URL not being retrieved and displayed. To solve this issue, we can set the CURLOPT_FOLLOWLOCATION option to true in the cURL request, which will automatically follow any redirects and retrieve the final URL.
<?php
$url = 'https://example.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects
$output = curl_exec($ch);
$finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
echo "Final URL: " . $finalUrl;
?>
Keywords
Related Questions
- How can PHP developers troubleshoot and resolve issues related to file permissions affecting file reading operations in PHP scripts?
- What are the requirements for running a PHP cron job on a server that supports MySQL and PHP?
- What are some best practices for handling dynamic CSS class changes in PHP?