从URL中获取哈希值的PHP方法

4

如何在php中获取哈希变量。

我有一个页面上的变量如下:

catalog.php#album=2song=1

如何获取专辑和歌曲的值并将它们放入PHP变量中?

可能是Can PHP read the hash portion of the URL?的重复问题。 - Paul Alexander
3个回答

9

由于PHP是在服务器端处理的,而URL中的哈希值仅在客户端中存在且从不发送到服务器,因此您无法使用PHP获取此值。但是,JavaScript可以使用window.location.hash获取哈希值(并可选择调用包含此信息的PHP脚本,或将数据添加到DOM中)。


3

在@Alec的回答上补充一点。

有一个parse_url()函数:

它可以返回fragment - #后面的部分。但是,在你的情况下,它将返回hashmark之后的所有值

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

正如@NullUserException所指出的,除非您事先具有URL,否则这确实毫无意义。但是,我认为了解这一点仍然很好。


3
除非你事先拥有网址,否则这是无用的。 - NullUserException
谢谢。听起来我可以把这个想法融入到我需要的东西中。 - Andelas

1
你可以使用AJAX/PHP来实现这个功能。你可以用JavaScript获取哈希值,然后用PHP加载一些内容。 假设我们正在加载页面的主要内容,那么我们带有哈希的URL是"http://www.example.com/#main":
头部JavaScript代码:
 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);

PHP 可能会有类似以下的内容:

<?php
// very unsafe and silly code

$content_hash_name = $_GET['content'];

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

?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接