How to do a back link with PHP/Javascript

Some users ignore the back button, maybe all of us every now and then. Sometimes a big BACK button gives you a nice "I'm not lost" feel.

The simplest way

<a href="javascript: history.back()">Go Back</a>

But that’s pretty obtrusive, won’t work if javascript is disabled and the button still sits there.

Less obtrusive method

Add the whole button with js (jQuery in this case):

  $('.back-button').html('<a href="javascript: history.back()">Go Back</a>');

Now it’s there only if the user has js on.

With PHP

Why not do it server side, works in every case. Here is a PHP solution using the HTTP_REFERER:

$go_back = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<a href='$go_back'>Go Back</a>";

The robust method

But, what if the user comes from a search engine or from a link and gets thrown of your site with the back button? We can check if the $go_back variable contains your site name:

$go_back = htmlspecialchars($_SERVER['HTTP_REFERER']);

// Has your site name in it
if (preg_match('/', $go_back)) {
    echo "<a href=" . $go_back . ">Go Back with PHP, only your site</a>";
} else {
    //Go home instead
    echo "<a href=''>Go Back home</a>";

Remember that the else is not going back, so don’t call it that. It’s good to call everything exactly what it does.

Functionify it

Here’s a nifty little function that used on WordPress site:

 * Returns a URL to the page where user was before this page
 * @param  string $domain        The sites domain name
 * @param  string $exeption_path The path to go to if not referer is not your site
 * @return string                URL string
function pps_back_href($domain, $exeption_path)
    // Get the referer, aka where user comes
    $referer = htmlspecialchars($_SERVER['HTTP_REFERER']);
    // Regex pattern
    $match_pattern = "/$domain/";
    // Has your site name in it
    if (preg_match($match_pattern, $referer)) {
        return $referer;
    } else {
        // Where to go if the referer is not from your domain
        return $domain.'/'.$exeption_path;

Then use it like:

<a href="<?php pps_back_href(get_home_url(), get_post_type()) ?>">
    &larr; Back to list

If the referrer is not your site, then it takes you back to the custom post type archive page.


Club-Mate, the beverage →