How to get the final redirected url using php?

by aniya.jaskolski , in category: Third Party Scripts , 24 days ago

How to get the final redirected url using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , 23 days ago

@aniya.jaskolski 

You can get the final redirected URL using the following code in PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
$url = 'http://example.com';

function getFinalUrl($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_exec($ch);
    $finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);
    return $finalUrl;
}

$finalUrl = getFinalUrl($url);
echo $finalUrl;


In this code snippet, the getFinalUrl() function uses cURL to follow redirections and get the final URL. You can pass any URL to this function, and it will return the final redirected URL.