4

How can I get a variable of a hash in php.

I have a variable on page like this

catalog.php#album=2song=1

How can i get the album and song values and put them into PHP variables?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Andelas
  • 2,022
  • 7
  • 36
  • 45
  • possible duplicate of [Can PHP read the hash portion of the URL?](http://stackoverflow.com/questions/940905/can-php-read-the-hash-portion-of-the-url) – Paul Alexander Dec 07 '11 at 18:00

3 Answers3

9

You can't get this value with PHP because PHP processes things server-side, and the hash in the URL is client-side only and never gets sent to the server. JavaScript can get the hash though, using window.location.hash (and optionally call on a PHP script including this information, or add the data to the DOM).

Alec
  • 9,000
  • 9
  • 39
  • 43
3

Just adding onto @Alec's answer.

There is a parse_url() function:

Which can return fragment - after the hashmark #. However, in your case it will return all values after the hashmark:

Array
(
    [path] => catalog.php
    [fragment] => album=2song=1
)

As @NullUserException pointed out, unless you have the url beforehand this really is pointless. But, I feel its good to know nonetheless.

animuson
  • 53,861
  • 28
  • 137
  • 147
Russell Dias
  • 70,980
  • 5
  • 54
  • 71
1

You can use AJAX/PHP for this. You can get the hash with javaScript and load some contents with PHP. Let's suppose we're loading the main content of a page, so our URL with hash is "http://www.example.com/#main":

JavaScript in our head:

 function getContentByHashName(hash) { // "main"
    // some very simplified AJAX (in this example with jQuery)
    $.ajax({
      url: '/ajax/get_content.php?content='+hash, // "main"
      success: function(content){
        $('div#container').html(content); // will put "Welcome to our Main Page" into the <div> with id="container"
      }
    });
 }

 var hash=parent.location.hash; // #main
 hash=hash.substring(1,hash.length); // take out the #

 getContentByHashName(hash);

The PHP could have something like:

<?php
// very unsafe and silly code

$content_hash_name = $_GET['content'];

if($content_hash_name == 'main'):
  echo "Welcome to our Main Page";
endif;

?>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
aesede
  • 5,541
  • 2
  • 35
  • 33