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):

jQuery(document).ready(function(){
  $('.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('/clubmate.fi/', $go_back)) {
    echo "<a href=" . $go_back . ">Go Back with PHP, only your site</a>";
} else {
    //Go home instead
    echo "<a href='http://clubmate.fi'>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
</a>

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

Comments

  • Anonymous says:

    vxcvxc

  • Anonymous says:

    vxcv

  • Webrunner says:

    Thanks, useful and nice article.

  • Observar videos porno disponível cá vai ser sua atividade favorita,
    só os mais inéditos de novinhas que caiu na net. http://www.bartholomaeus-gs.de/index.php/gaestebuch

  • かに本舗 says:

    実際に手に取って、ずっしりと重みを感じるものを選びましょう

  • Useful information. Lucky me I found your web site by
    chance, and I’m shocked why this coincidence
    did not took place earlier! I bookmarked it.

  • 湖北随州鑫国石业有限公司供应黄金麻石材
    湖北黄金麻,
    随州黄金麻,黄金麻,
    黄金麻石材, 黄金麻加工厂,
    黄金麻火烧面
    黄金麻荔枝面,黄金麻路沿石,
    黄金麻自然面,黄金麻厂家
    黄金麻光板,黄金麻自然面,
    随州黄金麻,
    是一家集矿山开采、石材加工、异型制作、产品销售为一体的专业化黄金麻石材公司。

  • Birthday messages may be romantic, humorous or straightforward,
    or you will even make-up a poem that expresses your feelings.
    If you enjoy its subtle humor, then Napoleon Dynamite is often a film you will discover utterly hilarious.
    As you can see, even a beginner photographer as if you will
    be capable of take professional looking pictures.

  • If Superman would have been to face off against Doomsday, as he did inside
    the Death of Superman story from the early 90s, we’d
    use a massive film brimming with action and drama which could tie in the larger DC movie universe
    that so sorely has to be designed for the DC movies to live and
    grow past the blinkered view that everything must be like The Dark Knight now.

    A SLR photographic camera, computer, printing device, online, photography software packages and ads must
    be properly secured. Out of this Verdi’s work also a film
    adaptation starring Sophia Loren, who was dubbed during the
    sung parts by singer Renata Tebaldi, may be made.

  • malibu photo says:

    Fantastic blog! Do you have any recommendations for aspiring writers?
    I’m hoping to start my own site soon but I’m a little lost on everything.
    Would you advise starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m completely overwhelmed ..

    Any recommendations? Kudos!

  • It’s truly very difficult in this full of activity life to
    listen news on Television, so I simply use web for that reason, and obtain the latest information.

  • I believe that is one of the so much vital information for me.
    And i am satisfied reading your article. But wanna observation on some common issues,
    The site style is wonderful, the articles is actually great : D.
    Good job, cheers

  • van cleave says:

    Hello there I am so excited I found your site,
    I really found you by error, while I was searching on Bing for something else, Anyways I am here now and would just like to say thank you for
    a remarkable post and a all round interesting blog (I also love the theme/design), I
    don’t have time to read it all at the minute but I have book-marked it and also included your RSS feeds,
    so when I have time I will be back to read more, Please do keep
    up the superb jo.

  • kanaflex says:

    「今日は何となく、だらだらしとこうかな?」カナフレックス2chさんを昼食に連れ出すつもりで連絡をしたら、一言目がこれでした。

    なので、今日、まさしくに久々にカナフレックス2chさんにお目にかかりました。

  • Hello to all, for the reason that I am in fact eager of reading
    this blog’s post to be updated on a regular basis.
    It includes good stuff.

  • 高知県の性病郵送検査高知県の性病郵送検査

Club-Mate, the beverage → club-mate.fi