在PHP中读取已用javascript编码的网址

时间:2019-02-09 04:07:52

标签: javascript php url-encoding

在Javascript中,我对请求参数的部分进行了这样的编码

window.location.href = "search.php?qry=" + encodeURIComponent("m & l");

在我的Search.php中,我这样到达

$url = urldecode($_SERVER['REQUEST_URI']);
echo ."Full URL: " .$url ."<br>";
$parts = parse_url($url);
parse_str($parts['query'], $query);
$qry = "Just Query: " .trim($query['qry']);
echo $qry ."<br>";

打印输出:

Full Url: /Search.php?qry=m & l
Just Query: m

类似&放在'm&l'中的内容

我需要在PHP或Javascript中进行哪些更改?

1 个答案:

答案 0 :(得分:3)

只需更改:

$url = urldecode($_SERVER['REQUEST_URI']);

$url = $_SERVER['REQUEST_URI'];

您基本上是双重解码的,因为parse_url也会对其进行解码。

值得一提的是,PHP已经为您完成了此操作,因此实际上没有理由解析您自己的URL。 $_GET['qry']将包含'm & l'

如果要对多个查询变量执行此操作,则需要分别为每个查询运行encodeURIComponent

示例:

window.location.href = "search.php?qry=" + encodeURIComponent("m & l") + "&subcat="+encodeURIComponent("hello & there");

您要明确地告诉它对&进行编码。