php - 如何使用 php header 位置删除无效的查询字符串

标签 php

我在软件中硬编码了这个无效链接,我无法修改。

http://www.16start.com/results.php?cof=GALT:#FFFFFF;GL:1;DIV:#FFFFFF;FORID:1&q=search

我想使用 php header 位置将其重定向到不包含查询字符串的有效 URL。我只想传递参数 q=。

我试过了

$q = $_GET['q'];
header ("Location: http://www.newURL.com/results.php?" . $q . ""); 

但是除了以一种奇怪的方式修改它之外,它只是将无效的查询字符串传递到新位置

这是我得到的目的位置,也是无效的

http://www.newURL.com/results.php?#FFFFFF;GL:1;DIV:#FFFFFF;FORID:1&q=search

最佳答案

那是因为 # 被视为 fragment identifier 的开始并混淆解析器。

您可以采用简单的方式作为Stretch建议,但您应该知道 q 是 URL 中的最后一个查询参数。因此,修复 URL 并以更安全的方式提取查询参数可能会更好:

<?php
$url = "http://www.16start.com/results.php?cof=GALT:#FFFFFF;GL:1;DIV:#FFFFFF;FORID:1&q=search";

// Replace # with its HTML entity:
$url = str_replace('#', "%23", $url);

// Extract the query part from the URL
$query = parse_url($url, PHP_URL_QUERY);

// From here on you could prepend the new url
$newUrl = "http://www.newURL.com/results.php?" . $query;
var_dump($newUrl);

// Or you can even go further and convert the query part into an array
parse_str($query, $params);
var_dump($params);
?>

输出

string 'http://www.newURL.com/results.php?cof=GALT:%23FFFFFF;GL:1;DIV:%23FFFFFF;FORID:1&q=search' (length=88)

array
  'cof' => string 'GALT:#FFFFFF;GL:1;DIV:#FFFFFF;FORID:1' (length=37)
  'q' => string 'search' (length=6)

更新

在您的评论之后,您的脚本中似乎无法将 URL 作为 string 提供,您希望从浏览器中获取它。

坏消息是 PHP 不会接收片段部分(# 之后的所有内容),因为它没有发送到服务器。如果您检查浏览器开发工具中的网络选项卡 F12,则可以验证这一点。

在这种情况下,您必须在 http://www.16start.com/results.php 托管一个页面,其中包含一些客户端 JavaScript,用于解析片段并重定向用户。

关于php - 如何使用 php header 位置删除无效的查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29902084/

相关文章:

php - 服务器负载均衡器算法

php - Laravel 5.5 编辑后无法删除类别

php - 一次搜索多个表以查找值

javascript - 标记不显示在谷歌地图 API 上

php - 拒绝解锁 exolnet/deprecated 因为它包含以下已安装的公式或木桶 :

PHP 数字 : assert( 1. 0 < 2.0 )

php - 我在哪里可以让 PHP 安装在 Windows 服务器 (x64) 上

PHP:回调函数

php - Laravel 模块化结构

php - Zend Framework 2 - ZFCUser 模块安装