How to Send a URL Fragment Anchor to PHP

The URL fragment anchor (or accelerator, ID link or jump point) can be used to relocate the visitor to a specific part of a page. This is done by giving an element an ID then linking to it with a hash symbol (# or number/pound sign) like so:

http://example.com/page.php#content

The “content” part of this URL however never gets passed to PHP since it is only used client-side. However, with a little bit of help from JavaScript we can do exactly that.


JavaScript can be used to grab all of the URL data since it runs client-side, which makes it ideal. In the below example we collect the URL, check for the hash tag, and refresh the page replacing the fragment anchor data with a PHP parameter.

1
2
3
4
5
6
7
8
9
10
11
12
13
<script type="text/javascript">
var parts = location.href.split('#');
if(parts.length > 1)
{
    var params = parts[0].split('?');
    var mark = '?';
    if(params.length > 1)
    {
        mark = '&';
    }
    location.href = parts[0] + mark + 'fragment=' + parts[1];
}
</script>

Line 2: If the URL has a fragment anchor, this will contain more than one element.
Lines 5-10: Quick check for any existing PHP parameters, adding an ampersand (&) instead if true.
Line 11: Combine the URL data and redirect.

We will then be sent to a page like this:

http://example.com/page.php?fragment=content

A quick check in PHP then prints the parameter to the page.

1
2
3
4
5
6
<?php
if(isset($_GET['fragment']))
{
    echo $_GET['fragment'];
}
?>

Add this just below the JavaScript content from earlier.

For examples of this script being used in large websites, look for any Facebook URLs that have a “#!” in them, and paste that into another tab (try Photo pages). You will then notice that the browser redirects you to a page with a nicer URL but with the same content as you had before.

This is a very neat little trick that is particularly useful in photo galleries with JavaScript support, but has uses for a wide range of projects that control most of their page data client-side.