Smart "Back" Button for Wordpress posts/pages

While coding a Wordpress site, I wanted to add a back button for posts and pages.
Hierarchical pages should obviously point back to their parents, but what of non hierarchical pages?

If a user navigated from the "Gallery" page to the "About" page - I would like the sites "back" button to return him to the "Gallery" page. This could be easily implemented using JavaScript but why use user-side scripting when you can generate the code on the server side?

The obvious solution would be to use the referring URL as a target for our "back" button. We must now avoid two special cases:

  1. The page is a sub-page and the back button should point to its parent.
  2. The previous URL was an off-site URL, and the back button should not appear at all.
This code snippet solves both problems: if the post is non-hierarchical, the referring URL is checked - if no URL is provided, or if the URL is off-site, no "back" button is displayed.
$ref_url = wp_get_referer();
$ref_parse = parse_url($ref_url);
$my_parse = parse_url(get_permalink());
if (($ref_url==get_permalink() || empty($ref_url)) && $post->post_parent) {
 $show_back_to_parent=true;
 $ref_url = get_permalink($post->post_parent);
}
if ($ref_parse[host]==$my_parse[host] || $show_back_to_parent) { 
 echo $ref_url;
}