Finding the Destination of a Redirect with PHP This solution for finding the destination of a redirect with PHP is easy but it assumes a single redirect.

Recently, I was working on a project that was communicating with a third-party API that, like many APIs, sends back a lot of data part of which includes a URL for the product associated with the API.

The thing about the API that was being returned was not the proper destination URL. Instead, it was a URL that ultimately redirected to another URL.

So imagine hitting, say, acme.site-info.com and having it direct to acme.com. We do this manually all the time, but I needed to get the actual – or the final – destination of the direct from the URL.

And finding the destination of a redirect with PHP is easy; however, this does assume there’s only a single redirect.

Nonetheless, here’s how to do it.

Destination of a Redirect with PHP

Note the following assumption assumes you’re familiar with cURL.

Destination of a Redirect with PHP: cURL

And if not, it’s easy enough to use the function.

curl is used in command lines or scripts to transfer data. It is also used in cars, television sets, routers, printers, audio equipment, mobile phones, tablets, settop boxes, media players and is the internet transfer backbone for thousands of software applications affecting billions of humans daily.

Further, the PHP manual has a lot of information about it that you can peruse as needed (and you’ll likely need it in the future, too).

Destination of a Redirect with PHP

Anyway, here’s the code with a bit of explanation about after the code:

The function does the following:

  1. accepts the URL as provided by the API,
  2. retrieves the headers from the request to the URL by cURL,
  3. provides the headers that we can read the grab the URL

Note also that I separate the URL based on the slash so that I can read just the domain as I’m not worried about anything after the main domain (so if a domain has an index.php extension, default.aspx extension, etc.), then I can use it as needed in my work.

Secondly, note that I don’t know if this will work for more than one hop. So if you have multiple redirects, then you may repeat this function multiple times. I don’t know, but I thought it worth mentioning.