PHP Snippets – Where You Were

I’m about to comment on a blog post, but I need to be logged in. There’s a handy log in button that takes me to a new page where I fill out the log in form and click submit. It takes me to a Thank You page, and now I expect to get back to where I originally was, so I can leave a comment like I originally wanted to.

/ -> /blog-post-247 -> /login -> /thank-you -> /blog-post-247

I wrote an itty bitty snippet to handle this situation.

function addWhereYouAre() {
  return '?whereiwas='.urlencode('http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);
}
function setWhereYouWere() {
  if (!empty($_GET['whereiwas'])) {
    $_SESSION['whereiwas'] = urldecode($_GET['whereiwas']);
  }
}
function getWhereYouWere() {
  if (!empty($_SESSION['whereiwas'])) {
    return $_SESSION['whereiwas'];
  }
  return false;
}

On the /blog-post-247 page, your link to log in should look like this:

<a href='/login<?php echo addWhereYouAre(); ?>'>log in</a>

At the top of the /login page (or somewhere where it always runs on page load), you add this:

<?php setWhereYouWere(); ?>

And whenever you want to finally get back to where you were, such as on the /thank-you page, you add this:

<?php $address = getWhereYouWere();
if ($address) {
  <a href='<?php echo $address ?>'>Go back to where you were</a>
}

It’ll keep the query string too, so if you were at /blog-post-235#comment, you’ll go right back there.

I can imagine an AJAX way of doing this which would take it down to 2 steps instead of 3, but I’d say it’s overkill and you’d lose any scriptless people.

…Just taking a break from coding :)

Leave a Comment

Your email address will not be published. Required fields are marked *