我能在我的服务器端应用程序(PHP、Ruby、Python等)中读取URL的哈希部分吗?

230

假设有如下URL:

www.example.com/?val=1#part2

PHP可以通过GET数组读取请求变量val1

哈希值part2是否也可读取?还是这只限于浏览器和JavaScript?

13个回答

0

是的,你可以:

使用这种方法来防止错误:

<script> 
query=location.hash;
document.cookie= 'anchor'+query;
</script>

当然,在PHP中,使用explode函数来分割字符串并获取其中一个值。
$split = explode('/', $_COOKIE['anchor']);
print_r($split[1]); //to test it, use print_r. this line will print the value after the anchortag

在对该页面的初始请求上没有做任何事情。 - Nico Haase

0
这里是更完整的代码,你可以从这里开始:

<script>
    sendTokenParameter();

    function sendTokenParameter() {
        if (!window.location.hash) {
            return;
        }

        const id_token = window.location.hash.split('&').filter(function(el) { if(el.match('id_token') !== null) return true; })[0].split('=')[1];
        if (!id_token) {
            console.error('No token returned');
            return;
        }

        window.location.href = `${window.location.pathname}?id_token=${id_token}`
    }
</script>

<?php

process_login();
function process_login() {
    $id_token = $_GET['id_token'];
    if (!$id_token) {
        // Let the javascript code to send the token
        return;
    }
    
    // Do stuff with the token
    
}

?>


-1

另一种解决方案是在 PHP 页面中添加一个隐藏的输入字段:

<input type="hidden" id="myHiddenLocationHash" name="myHiddenLocationHash" value="">

使用JavaScript/jQuery,您可以在页面加载或响应事件时设置此字段的值:
$('#myHiddenLocationHash').val(document.location.hash.replace('#',''));

在服务器端的 PHP 中,您可以使用 $_POST 集合读取此值:
$server_location_hash = $_POST['myHiddenLocationHash'];

在该页面的初始请求中不执行任何操作。 - Nico Haase
我同意,它适用于后续请求,而不是第一次加载。 - Matteo Conta

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