"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Retrieve Redirect URL from Source URL in PHP?

How to Retrieve Redirect URL from Source URL in PHP?

Posted on 2025-02-06
Browse:614

How to Retrieve Redirect URL from Source URL in PHP?

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:

  • Initialize a cURL handle and set the source URL as the request destination.
  • Enable the inclusion of the HTTP header in the output by setting CURLOPT_HEADER to true.
  • Allow following redirects by setting CURLOPT_FOLLOWLOCATION to true.
  • Return the response as a string through CURLOPT_RETURNTRANSFER.
  • Extract the final redirected URL using curl_getinfo($ch, CURLINFO_EFFECTIVE_URL).

By following these steps, we can successfully retrieve the redirect URL from the given source URL.

Release Statement This article is reproduced on: 1729138341 If there is any infringement, please contact [email protected] to delete it.
Latest tutorial More>

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