php - 加号登录GET查询并比较URL

标签 php .htaccess

我想检查页面的当前 URL,如果在查询中包含 + 号,如果没有 + 号,我将重写 URL 并 301 重定向到一个新的 URL。例如

www.sitename.com/search?q=123 456

这应该是

www.sitename.com/search?q=123+456

首先我想用 PHP 来做这个,首先,$_GET['q'] 和干净的字符串,用 + 替换空格并与当前的 $_GET[' 进行比较q'] 在 URL 中,但问题是因为我无法在 $_GET 中获取 + 号,而且简单,我无法检查 URL 是否包含 + 号 .

另一种选择是使用 .htaccess 实现此目的

RewriteCond %{QUERY_STRING} ^q=(.*)$
RewriteRule ^search$ test.php?mode=search&q=%1 [L]

但我相信使用 PHP 可以更好地完成此操作,因为有更多查询参数而不仅仅是 q

一些想法

    $q1 = cleanq($_GET['q']) //This query include +,cleanq is function to clean string and replace space with +
    $q2 = $_GET['q'] //This is current one
    if(strcmp($q1, $q2) != 0){
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: www.sitename.com/search?q=".$q1);
        exit();
    }

看起来很简单,但无法比较登录查询,知道如何实现吗?

最佳答案

由于 URL 规范,URL 中的字符 + 必须解释为空格,因为 URL 中不允许使用纯空格。

您不必担心将 www.sitename.com/search?q=123 456 重定向到 www.sitename.com/search?q=123+456 code>,这是同一个链接。

您可以在 PHP 文件中进行简单的测试:

test.php?search1=aaa bbb&search2=aaa+bbb

if ($_GET['search1'] == $_GET['search2']) {
    print 'Same string!';
}

您将得到相同的字符串!


如果您想更新当前 URL,您可以使用 javascript 来完成此操作,方法是将编码的 url 空格 %20 替换为 +

<script>
    const url = window.location.href.replace(/%20/, "+");
    window.history.replaceState(null, null, url)
</script>

使用 $_SERVER['REQUEST_URI'] 进行 PHP 重定向

if (stripos($_SERVER['REQUEST_URI'], '%20') !== false) {
    $request_uri = str_replace('%20', '+', $_SERVER['REQUEST_URI']);
    $request_uri = preg_replace('/([+])\1+/', '$1', $request_uri);

    if ($request_uri != $_SERVER['REQUEST_URI']) {
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: " . $request_uri);
    }
}

关于php - 加号登录GET查询并比较URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74423643/

相关文章:

php - Doctrine2 多级继承

php - 与自定义永久链接一起使用时 Wordpress 站点地图 XML 错误

php - Opencart 2.2.x ssl 用于所有请求

apache - htaccess 将 https 流量重定向到特定文件夹?

apache - 漂亮的 jekyll 页面 url

javascript - 如何在javascript中声明php数组变量并在数据表上查看

php - 获取PHP中动态选择的类常量的值

javascript - Codeigniter AJAX 数据返回空

apache - htaccess : Redirect to https not working with out www

apache - 在htaccess中使用Mod访问阻止多个IP范围