I have a link like the one in the title in a custom 404 error page, which allows the user to go to the previous page just like with the browser's go back button. I just wanna ask if this method of linking is safe or not. I guess it is safe, but I am not sure. Thanks in regards!
One use case I can say that will not be "safe" is if the user has JavaScript disabled. In that case, you would have to create the link dynamically with server-side code using the HTTP referer
header field's value as your href
value on the anchor element.
Another thing to consider is the never-ending back and forth loop users would get stuck in, if they came from a page with an HTTP redirect.
Edit:
As you said above, you can use $_SERVER['HTTP_REFERER']
but the documentation says
.. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
In reality, most browsers do set it correctly though, and seeing how this is not mission critical I think it's safe if you use it. You could also account for browsers that don't set it as follows:
if(isset($_SERVER['HTTP_REFERER']))
{
// Show a Back button link, if the referrer is available
echo "<a href=\"".$_SERVER['HTTP_REFERER']."\">« Back</a>";
}
else
{
// If not, show a link to your homepage instead
echo "<a href=\"". "//www.yoursite.com" ."\">Home</a>";
}