0
$url = htmlspecialchars($_SERVER['HTTP_REFERER']); 
echo "<a href='$url'>Back to $url</a>"; 

So these two lines of PHP will output the URL of the previous (referring) page and a (clickable) link back to it. My question is? Is it possible to get the title of the previous page?

EDIT: See @ http://wp-staging.de/reiseziele/urlaub-mit-dem-hund If you click on the link in the first column and go to that post, you will see ← Back to http://wp-staging.de/reiseziele/urlaub-mit-dem-hund/ (= the previous page).

But I want the title of the previous page, not the URL

2 Answers2

2

I'm not sure this is the best solution for this case. But it's worked for me.

<?php
function get_title($url){
  $str = file_get_contents($url);
  if(strlen($str)>0){
    $str = trim(preg_replace('/\s+/', ' ', $str)); // supports line breaks inside <title>
    preg_match("/\<title\>(.*?)\<\/title\>/i",$str,$title); // ignore case
    return $title[1];
  }
}

$url = @$_SERVER[HTTP_REFERER];
echo "<a href='$url'>Back to ".get_title($url)."</a>";
?>

Result

enter image description here

Quynh Nguyen
  • 2,959
  • 2
  • 13
  • 27
1

You could try like this:

$html = file_get_contents($url);
preg_match_all('/<title>(.*?)<\/title>/s', $html, $matches);
print_r($matches[1]);
mister martin
  • 6,197
  • 4
  • 30
  • 63
  • 2
    It should be noted that doing this any time a referrer comes in will be **extremely** heavy on your server. It also exposes you to denial of service attacks (both on your server, and on someone else *via* your server) – ceejayoz Jul 26 '16 at 18:07
  • @ceejayoz good point. `$_SERVER['HTTP_REFERER']` should never be trusted as it can be changed / manipulated by the end user. – mister martin Jul 26 '16 at 18:09
  • @mister martin Instead of a link back, I am getting this: Array ( [0] => Urlaub mit dem Hund – Traum-Ferienwohnungen.de [1] => Facebook [2] => pinterest [3] => Instagram ) – user3350511 Jul 26 '16 at 18:56
  • @user3350511 It works perfectly on my end. Would be helpful to see what your actual target website is. Perhaps the HTML is broken. – mister martin Jul 26 '16 at 23:28