Grow your CSS skills. Land your dream job.

Last updated on:

“Go Back” Button

Browsers already have "back" buttons, so you'd better have a darn good reason for needing to put one on your page!

Input button with inline JavaScript

<input type="button" value="Go Back From Whence You Came!" onclick="history.back(-1)" />

This is totally obtrusive, but you could fix that by only appending this button through JavaScript.

PHP

If JavaScript isn't a possibility, you could use the HTTP_REFERER, sanitize it, and echo it out via PHP.

<?php
  $url = htmlspecialchars($_SERVER['HTTP_REFERER']);
  echo "<a href='$url'>back</a>"; 
?>

Reference URL

Comments

  1. Permalink to comment#

    1. Many users aren’t aware of their browser back button.
    2. Users filling forms often make errors. Therefore, they complete the form, it goes through edit checks on the server, then it displays their input and asks if it is correct. If not, they need to return to correct it. A return button, front-and-center, becomes applicable.
    3. The browser back button and the scripted back button do not always behave in the same manner. If you’re looking for a specific behavior, then, it needs to be created.

    • James
      Permalink to comment#

      The rest of your point may be valid, but point 1, “Many users aren’t aware of their browser back button.” is utterly false. The back button is a key tool in average joe’s toolbox – EVERY user knows about the back button – it’s one of the few things you can assume during a usability test.

  2. Permalink to comment#

    Oh. The javascript:history.go(-1) and its derivatives returns an Expired Page in IE8

    • CatGuyTX
      Permalink to comment#

      In my opinion, IE* just needs to go away or get with the program. I am new to web design and all I here is IE this and IE that. I didn’t go into web design to learn to code for IE anything. All web browsers need to meet with standards, period. I know that is a lot to say but it’s always a problem with IE something!

    • Nicklas

      @CatGuyTX You might as well get used to it, because it’s not going to get better for a couple of years. IE10+ now has auto update built in, meaning it’s a so called “evergreen” browser. The problem is the old versions which people can’t or won’t update.

    • Dave
      Permalink to comment#

      @CatGutTX: At the moment MSIE 11 is the most compliant browser out there. You’re new to web design. I’m sure you’re checked the CSS of various websites. Did you notice all the -webkit statements for rounded corners and box shadows? Those elements are part of the CSS3 standard and the -webkit, -moz or -o prefixed for those attributes should no longer be used.

      Why do designers will use the -webkit prefix you migth ask. It’s very simple. Every (active) specification is an living organism and browser vendors are constantly adding new features which they than propose the the appropriate commission (W3C in case of HTML and CSS). Until that feature is part of the official specification, you can only use those features using the vendor prefixes like -webkit.

      Why does give MSIE so much trouble? Well, it’s older than webkit and chrome combined and between 1999 and 2004 MSIE is basically the only browser (until Firebird – later renamed to Firefox) entered the stage. As a result a lot of developers got lazy and started using MSIE specific features because it was available to 95+ percent of the users on the web. The other 5 percent did go to browsers Opera, Konqueror (the base for webkit which inherits khtml and netscape.

      You’re new, so I assume you only design mobile first websites, but there are a lot of websites outthere that have different code for desktop and mobile browsers. A few years before that had chtml, wap and even before that we had different versions for desktop developers (MSIE vs Netscape)..

      Technology is constantly changing and so does the web. However you can’t ignore it’s legacy, because that is the reason we got here in the first place. I started in 1993 with web development when the Netscape browser became popular. Back then as a commercial (payware) browser. In 1995 we started clientside development with livescript (later renamed to javascript), but serverside development was done with CGI file in the defacto ‘writeonly’ language perl..

      Like Nicklas already pointed out, the main problem with MSIE is that not everybody is running the latest version. For instance Windows XP users are still stuck with MSIE8..

      As a developer I have a love/hate relationship with Microsoft. I absolutely love the Microsoft development tools like Visual Studio, WPF, Sql Server, IIS. Recently I switched back from Chrome to MSIE. I constantly evaluate the top browser to see which has the best standards support. Currently that’s MSIE, so that is now my primary development browser. However there are a lot of webkit favorite websites out there. A significant number of those will never be updated and over 5 years we’re complaining about those annoying webkit websites.. That’s simply how the tech world works. It has so in the past and will continue to do so in the future..

  3. simple HREF=”javascript:history.go(-1)”>Back

    • Permalink to comment#

      That’s a bad bad bad practice.

      The href attribute isn’t intended to hold javascript.

  4. Just wanna say thanks for the ‘Back’ button/link… working perfectly :) I used the one in php with one of my projects.

    Thanks a bunch!

  5. shin
    Permalink to comment#

    hey
    thanks for php version, it works great.

    may be you can help me in customize it… i need conditional construct with check about count of previous pages. i want to hide this button if user looks his first page. sometimes it’s not the main page.

    tia.

    • <?php
      if(basename($_SERVER['PHP_SELF']) == 'index.php'){
      $GoBack = " ";
      } else {
      $GoBack = htmlspecialchars($_SERVER['HTTP_REFERER']);
      }

  6. Been looking for this for ages, thanks . Will come in very useful at the bottom of an article ,but is there a way to change the button for a image.

  7. Ben Smalley

    David if you really need to ask that i’m not sure your in the right place, but here you are bud,

    Good luck!

    • Code Cooker
      Permalink to comment#

      ..
      I just checked Ben’s source code to see what you were implying.
      Don’t judge dude… Everybody had to start somewhere, even if it was Netscape. ha!
      How about a simple <a href=”history.go(-1)” rel=nofollow”>

      OR… you could do an onclick event:

      Cheers! :D

  8. jacob

    the php code works, but there’s an issue and I need some help fixing it.

    Example:
    I go to page A
    then I go to Page B, and click to go to Page C,
    When I click the back button on Page C, I get to Page B.
    When I click the back button on Page B, I get to Page C.

    How can I fix this?

    • saman shaikh
      Permalink to comment#

      Did you fix your problem?Toggling into 2 pages only??

    • Permalink to comment#

      Isn’t that what it is supposed to do, as you click the back button on C to go to B. When you click the back button on B, you go back to the last page viewed, which would be C

    • Baffour
      Permalink to comment#

      No it shouldn’t…You would expect a back button to keep going back through the History, independent of the pages visited when pressing the button itself (i.e. how the built in browser back button does it). Obviously because of how the code works it will never do that, so is pointless if you want to go back more than one page.

  9. I love this button its had great use on my site, thank you for taking your time to share :).

  10. Other than what was said in the first post, is there any reason for it to be like that?

  11. Charlie
    Permalink to comment#

    I reach a page with an update form on it which uses Dreamweavers PHP/MySQL Update Record function. I come to this from vatious source pages and want to go back to the page that sent me there once I hit the submit button. Given all the PHP code it is not a simple matter of chaning or creating a button with a link on it.

    Any ideas on having the submit button go back to whatever page send it there in the first place?

  12. Permalink to comment#

    I’ve got a new BibleRhymes site in the final stages of creation and I think your JS code will be a part of it. Thank youu!

  13. Epi
    Permalink to comment#

    Wow nice tutorial..thanks

  14. PHP trick works gr8 for me… thx

  15. Hi All,

    On Page A I am having few image link(each direct to 2nd page) and some data on data table.
    When I goes to Page B and click on back button, all the Image links are not getting displayed.
    But in HTML sourse , The code for all links present.I am suspecting it is some CSS setting,but don’t know which property.
    Kindly Advice,If anyone knows.

  16. Jen
    Permalink to comment#

    @Ben Smalley,
    Did you share code that would show how to put an image here in place of the text? I could really use help with that, obviously new to php and I’ve been searching the internets with no success :( Hope you’re still here!
    Thanks a ton,
    Jen

  17. F4LLCON
    Permalink to comment#

    Thank you so much for this little easy but useful script! Tested the PHP script, works great!

    Thank you,
    F4LLCON

  18. Permalink to comment#

    Excellent code.

    Thank you
    Mike
    ZeePoints.com

  19. Keith
    Permalink to comment#

    Oh mate !! that one little line of js code is absolutely brilliant. I have been working on going back a page to edit a form entry and retaining the information entered for days. Tried some really complicated approaches, but your tiny little one line script is the perfect solution. Just wanted say THANK YOU SO VERY MUCH
    Definitely 5*****star from me

  20. iamds
    Permalink to comment#

    Can we add a little condition to hide script if the visitor is coming from somwhere else and not our site.

  21. Thanks it works perfect, but is it possible to make the button go to the homepage if visitors have just landed on your website or even remove the button if visitors have just landed on your website.

  22. Robert

    I am using this in PHP, when I click the back button, it takes me to a blank page, any ideas why?

  23. Thanks so much for the sanitized php version. It fixed a vulnerability that was coming up.

  24. BJM
    Permalink to comment#

    My site is structured on one html page through CSS, how can I make a browser go back to the previous page without clicking one of the navigation links? Any ideas?
    Thanks

  25. My solution for how to show a backlink if the users is “from my site” and a link to / if the users found this page from an external source.

    $findme = 'skolresurser.se';
                $pos = strpos($url, $findme);
                
                //var_dump($pos);
                if($pos === false){ ?>
                    <a href="/" rel="nofollow">← Visa fler resurser</a>
                
                    <a href="' + document.referrer + '" rel="nofollow">← Tillbaka</a>
                <?php }
  26. Nice code and I think every coder has different ideas to a common goal. Anyway it’s your idea on coming up this useful code.

  27. amir jelodari
    Permalink to comment#

    I Always use
    onClick=”hisory.back()”

  28. ahamed
    Permalink to comment#

    Hi coyier, You are providing helpful articles to the beginner/intermiddiate/expert its very nice about you, thanks thanks thanks thanks…………………………………………………….

  29. Dan
    Permalink to comment#

    I have the bellow section of code I need a back button in there

        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
        echo "These errors appear below.<br /><br />";
        echo $error."<br /><br />";
        echo "Please go back and fix these errors. <br /><br />";
        die();
    }
    

    I have tried many options but then when I put it on the web site I get “Parse error: syntax error, unexpected ‘<‘ in /home/newbussc/public_html/send_form_email.php on line 16″

    can someone please help me other wise they just get a page that tells them they have to go back and need to use the actual Explorer Back button how can I add a back button in to this code that will not give the error message

  30. James White
    Permalink to comment#

    I’m only really posting this to vent some frustration. I am a web designer. EVERY TIME! every time I create a website…
    Client: “How do I go back to the previous page?”
    Me:dies a little inside

    The general public are blind to the browser..or “the internet” as they call it; can’t use the address bar and don’t expect to use the back/forward buttons. PART of the responsibility lies with those goddamn awful web programmers who BREAK the back button and in doing so have trained users that you click the browser back button for errors.

    Guys, if the browser’s back button doesn’t work with your website, Your site is fundamentally badly designed. EDUCATE YOURSELF an FIX IT.

    until then, sadly, this CSS-TRICKS page is a necessary evil…but I agree with the author. You need a darned good reason to use it, and to anyone in the business, an on-page back button means you’re on the wrong track with your web design.

    • Dan
      Permalink to comment#

      no this is not true at all because if data is set to expire as is on my form then back button will not work as the page would of expired which is why a different type of button is needed and that is to go to home page instead.

  31. Call me Tony

    I found this to work best as it works for all browsers which have js activated and goes to the referer page for browsers of the “smart” people who disable js.

      
    $back_loc="previous.php";
    if(array_key_exists("HTTP_REFERER",$_SERVER)){$back_loc = $_SERVER["HTTP_REFERER"];}
    
    href="$back_loc" onClick="history.back();return false;"
    
    
  32. Chumonky
    Permalink to comment#

    Hi I need to fix this problem in vs 2010 using asp.net & c# code. Can someone please tell me how to use this php in a webpage?
    I am new to php.

  33. I put this on my mobile version wordpress theme. work best using php. thank you

  34. Mike Wax
    Permalink to comment#

    I am a little bit of a newbie to PHP, so I apologize if this is a dumb question….

    I am trying to make this PHP back button work outside of a website. I am creating a widget, that can submit a form through PHP. But if there is an error in the form, it redirects to an Error page, and I need a back button in the error page to get back to the form. Since this is not in a web browser, there is no back button. And since I am not technically using the internet, the javascript:history.go(-1); code doesn’t work either, becasue there is no stored history in a widget. Basically, I have a local HTML file, that links to a PHP file on a server, and I need to get back to the HTML file (original page or the form).

    <button type='button' onclick='history.go();return false;;'>Return to the Previous Page</button>
    

    That is what i have now in my PHP code, and can’t figure out how to get it to work. And I don’t really understand the PHP code given above.

    Any help is greatly appreciated. Thank you!

  35. Viishnuu
    Permalink to comment#

    For Chrome use below code:

    <a href="#" onclick="javascript:history.go(-1);return false;" style="text-decoration:underline;">Back</a>
    

    Only this code will work..

    I hope it will help…
    Happy coding.. :)

  36. Permalink to comment#

    For wordpress I found this one really useful, if a user lands on a the page from an external URL that it will go to the parent page URL.

    <?php
        $parent_Url = get_permalink($post->post_parent);
        $parent_title = get_the_title($post->post_parent);
        $current_post = get_the_title();
        if ($parent_title == $current_post) { $parent_Url = '/'; };
    ?>
    <a href="<?php echo $parent_Url ?>" class="back-btn">Go back</a>
    
  37. Shubham Mathur
    Permalink to comment#

    Thanks for sharing the JavaScript way, I was using PHP one previously but the JavaScript version is Better :)

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

```
<div>Example code</div>
```

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

*May or may not contain any actual "CSS" or "Tricks".