Go Back via JavaScript and PHP

This quick tutorial explains how to use HTML, JavaScript, and/or PHP to enable visitors to “go back” to the previous page. You can use either method to add a simple “go back” link or form button to your web pages.

“Go back” link via HTML & JavaScript

Use this simple code as a button that will return users to the previous page:

<form>
	<input type="button" value="Return to previous page" onClick="javascript:history.go(-1)" />
</form>

Here it is as a simple text link:

<p>
	<a href="javascript:history.go(-1)" title="Return to the previous page">&laquo; Go back</a>
</p>

You can customize the text and attributes as desired.

“Go back” link via PHP, HTML, & JavaScript

You can make things easier by serving PHP and printing the link automatically. Here is the button link:

echo '<form><input type="button" value="Return to previous page" onClick="javascript:history.go(-1)"></form>';

And here is the PHP code to print a “Go back” text link:

echo '<p><a href="javascript:history.go(-1)" title="Return to previous page">&laquo; Go back</a></p>';

As before, customize the text and attributes as desired.

Advanced “go back” technique with PHP

Better yet, you can kick the accessibility factor up a notch by using PHP’s global HTTP_REFERER variable to write explicitly the previous URL, thereby eliminating the JavaScript requirement (thanks to Rick Beckman for the idea):

<?php $referer = filter_var($_SERVER['HTTP_REFERER'], FILTER_VALIDATE_URL);
	
	if (!empty($referer)) {
		
		echo '<p><a href="'. $referer .'" title="Return to the previous page">&laquo; Go back</a></p>';
		
	} else {
		
		echo '<p><a href="javascript:history.go(-1)" title="Return to the previous page">&laquo; Go back</a></p>';
		
	}
?>

The previous code will create an explicit “Go back” link when the referring URL is known. In those awkward situations where no referring URL has been recognized, the function writes a “Go back” link via JavaScript. Note that you can refine the sanitizing function, filter_var() to suit your needs by adding various filter flags.