Retrieving Redirect URL from Source URL in PHP
Obtaining the redirect URL from a source URL is a common task encountered in web scraping and automation. In this context, it involves extracting the ultimate destination URL after any redirects.
Problem Statement:
Given a source URL that redirects to another location, how can we retrieve the redirected URL using PHP? For instance, consider the following scenario:
Source URL:
http://libero-news.it.feedsportal.com/c/34068/f/618095/s/2e34796f/l/0L0Sliberoquotidiano0Bit0Cnews0C12735670CI0Esaggi0Eper0Ele0Eriforme0Ecostituzionali0EChiaccherano0Ee0Eascoltano0Bhtml/story01.htm
Redirected URL:
http://www.liberoquotidiano.it/news/1273567/I-saggi-per-le-riforme-costituzionali-Chiaccherano-e-ascoltano.html
Solution:
To obtain the redirected URL, we can utilize PHP's cURL extension along with its capabilities for following redirects and retrieving HTTP headers:
$url = "http://libero-news.it.feedsportal.com/c/34068/f/618095/s/2e34796f/l/0L0Sliberoquotidiano0Bit0Cnews0C12735670CI0Esaggi0Eper0Ele0Eriforme0Ecostituzionali0EChiaccherano0Ee0Eascoltano0Bhtml/story01.htm";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$a = curl_exec($ch);
$finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
echo $finalUrl; // Output: http://www.liberoquotidiano.it/news/1273567/I-saggi-per-le-riforme-costituzionali-Chiaccherano-e-ascoltano.html
In this code, we:
By following these steps, we can successfully retrieve the redirect URL from the given source URL.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3