Reputation: 199
I created a back link using the PHP http_referer for my website. It works basically but I would like to enable it only if the referer is a page with my domain. I thought about comparing the strings from the refering page and the current page but I did not find out how it could work.
This is my code:
<?php // Back link to previous page.
// If current page has been called by a hyperlink.
if(isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] !='') echo '<a href="'.$_SERVER['HTTP_REFERER'].'">« Go back.</a>';
// If current page has NOT been called by a hyperlink.
else return;
?>
Can you give me any advise which PHP function I should use?
Upvotes: 3
Views: 2019
Reputation: 46620
You could parse the url from $_SERVER['HTTP_REFERER']
and get the hostname & compare it with your own. So the function your looking for is parse_url():
if(!empty($_SERVER['HTTP_REFERER']))
{
if(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) == $_SERVER['HTTP_HOST'])
{
echo '<a href="'.htmlentities($_SERVER['HTTP_REFERER']).'">« Go back.</a>';
}
}
Also as $_SERVER['HTTP_REFERER']
can be set by the user its a good idea to htmlentities to stop any XSS.
A safer idea as the PHP has handled if they entered from your domain, would be to just use some javascript in place of the link to send them back.
echo '<a href="Javascript:window.history.back();">« Go back.</a>';
Upvotes: 2