You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中从给定路径的URL中获取token值

获取URL哈希片段中的Token值

你的目标URL里的Token位于哈希(#)之后,属于URL的hash部分,而非常规查询参数,以下是不同场景下的提取方法:

前端JavaScript场景

浏览器中可直接操作window.location获取hash并解析:

方法1:使用URLSearchParams(推荐,支持多参数场景)

// 获取包含#的hash片段
const hash = window.location.hash;
// 移除开头的#,将剩余部分当作查询字符串解析
const hashParams = new URLSearchParams(hash.slice(1));
// 提取token值
const token = hashParams.get('token');
// 输出结果:9d7813cfc4a6c8de7eghdgcf66990a064fd99796e621395b90df3723f73f03f32f49
console.log(token);

方法2:纯字符串分割(仅适用于单一参数场景)

const hash = window.location.hash;
// 按token=分割字符串,取第二部分
const token = hash.split('token=')[1];
console.log(token);

后端字符串处理场景(以Python为例)

如果是直接处理URL字符串(注意:浏览器不会把hash部分发送给服务器,后端通常无法从请求中直接获取):

url = "http://localhost/#token=9d7813cfc4a6c8de7eghdgcf66990a064fd99796e621395b90df3723f73f03f32f49"
# 分割出hash部分
hash_segment = url.split('#')[1]
# 分割token键值对
token = hash_segment.split('=')[1]
print(token)

注意事项

  • 哈希(#)后的内容仅在浏览器端可见,服务器不会收到这部分数据,若需后端使用Token,需前端主动通过接口请求传递。
  • 当hash中存在多个参数时,优先使用URLSearchParams解析,避免手动分割出现错误。

内容的提问来源于stack exchange,提问作者Ashish Mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 12:33:16