Подтвердить что ты не робот

Php получить URL-адрес перенаправления из исходного URL-адреса

У меня есть эта ссылка:

http://libero-news.it.feedsportal.com/c/34068/f/618095/s/2e34796f/l/0L0Sliberoquotidiano0Bit0Cnews0C12735670CI0Esaggi0Eper0Ele0Eriforme0Ecostituzionali0EChiaccherano0Ee0Eascoltano0Bhtml/story01.htm

Если вы посетили его, это станет следующим:

http://www.liberoquotidiano.it/news/1273567/I-saggi-per-le-riforme-costituzionali-Chiaccherano-e-ascoltano.html

Как я могу получить вторую ссылку с первого?

Я пробовал это, но не работал, возвращая мне одну и ту же первую ссылку:

<?php
$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, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$a = curl_exec($ch);
print_r($a);echo"<br>";
if(preg_match('#Location: (.*)#', $a, $r)){
 $l = trim($r[1]);
 echo $l;
 }else echo "not working";
 ?>

Большое спасибо.

4b9b3361

Ответ 1

Благодаря @king-isaac был протестирован следующий код и он работает.

<?php 

$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); // Must be set to true so that PHP follows any "Location:" header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$a = curl_exec($ch); // $a will contain all headers

$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // This is what you need, it will return you the last effective URL

// Uncomment to see all headers
/*
echo "<pre>";
print_r($a);echo"<br>";
echo "</pre>";
*/

echo $url; // Voila
?>

Ответ 2

Вы можете получить окончательный URL-адрес запроса с curl_getinfo.

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

Ответ 3

Вы можете сделать это без использования CURL. Сделано просто и коротко.

<?php
$url="http://libero-news.it.feedsportal.com/c/34068/f/618095/s/2e34796f/l/0L0Sliberoquotidiano0Bit0Cnews0C12735670CI0Esaggi0Eper0Ele0Eriforme0Ecostituzionali0EChiaccherano0Ee0Eascoltano0Bhtml/story01.htm";

$headers = @get_headers($url);
$final_url = "";
foreach ($headers as $h)
{
    if (substr($h,0,10) == 'Location: ')
    {
    $final_url = trim(substr($h,10));
    break;
    }
}
echo $final_url;
?>