最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Php to get value of hash from URL - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Apr 26, 2014 at 16:37 Quentin 944k132 gold badges1.3k silver badges1.4k bronze badges asked Oct 2, 2010 at 23:11 AndelasAndelas 2,0527 gold badges37 silver badges45 bronze badges 1
  • possible duplicate of Can PHP read the hash portion of the URL? – Paul Alexander Commented Dec 7, 2011 at 18:00
Add a ment  | 

3 Answers 3

Reset to default 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).

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.

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./#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 "Wele 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 "Wele to our Main Page";
endif;

?>
发布评论

评论列表(0)

  1. 暂无评论