检查URL的最佳方法是在PHP中包含String和QueryString

时间:2018-09-21 18:06:18

标签: php query-string

我正在尝试检测url是否包含字符串或包含查询字符串的字符串,然后为其提供其他功能。

下面的代码是我能想到的,它是行不通的。

检查此问题的最佳方法是什么?

url 1 = http://example.com/index.php

url 2 = http://example.com/index.php?some-test-page

if (stripos($_SERVER['REQUEST_URI'], 'index')){
    $xurl="http://example2.com/photos/";
} else {
    $req_url = $_SERVER['QUERY_STRING'];
    $xurl=('http://example2.com/photos/'   . $req_url . '');
}

3 个答案:

答案 0 :(得分:1)

如果有查询字符串,它将填充the $_GET superglobal。只需检查该内容,然后在需要时使用http_build_query()将其添加回去(这将确保避免所有转义。)

$xurl = "http://example2.com/photos/";
if (!empty($_GET)) {
    $xurl .= "?" . http_build_query($_GET);
}

答案 1 :(得分:0)

您应该检查'?'在requesturi中而不是索引中。

url 1 = http://example.com/index.php
url 2 = http://example.com/index.php?some-test-page

if (stripos($_SERVER['REQUEST_URI'], '?') === false ){

  $xurl="http://example2.com/photos/";

    }
else{
    $req_url = $_SERVER['QUERY_STRING'];

    $xurl=('http://example2.com/photos/'   . $req_url . '');
    }

答案 2 :(得分:0)

使用parse_url将URL分成多个部分,然后仔细检查您需要的内容... http://php.net/manual/de/function.parse-url.php