获取URL查询字符串并在PHP

时间:2016-04-03 11:31:34

标签: php

我并不是100%肯定我搞砸了这个(最有可能检查文件是否存在位),但我想做的是:

  • 获取页面查询,例如example.com?example
  • 然后使用该字符串处理文件路径(in this case news/example.php
  • 然后查看该文件是否存在
  • 如果是,请包含该文件,如果没有回显错误消息。

这是我的代码:

    $getPage = $_SERVER['QUERY_STRING'];
    $page = "news/"+$getPage+".php";
    if (file_exists($page)) {
    include $page;
    } else {
    echo "The page you are looking for cannot be found. To return back to the main page click <a href='example.com'>here</a>";
    }

如果查询必须成为example.com?news/example.php,那么它就不会成为世界末日,但越短越好;将它留作文件名,没有扩展名,会更好。

2 个答案:

答案 0 :(得分:0)

  

PHP连接不支持+,您必须使用.

$getPage = $_SERVER['QUERY_STRING'];
$page = "news/".$getPage.".php";
if (file_exists($page)) {
    include $page;
} else {
    echo "The page you are looking for cannot be found. To return back to the main page click <a href='example.com'>here</a>";
}

试试这个,让我知道它是否适合你。

答案 1 :(得分:0)

在这种情况下,URL重写将更加相关。 使用以下命令创建.htaccess文件:

RewriteEngine on
RewriteRule ^news/([^/\.]+)/?$ news.php?filename=$1 [L]

如果您熟悉正则表达式,您会知道所附的括号()用于捕获匹配项。

[^/\.]+是一个或多个不是正斜杠或句号的字符。

在捕获匹配后,它将在news.php?filename =

中替换它

因此,当您请求http://example.com/news/helloworld时, 您将获得http://example.com/news.php?filename=helloworld

现在,你的news.php文件应该是这样的:

$getPage = $_SERVER['QUERY_STRING'];
$page = "news/".$getPage.".php";
if (file_exists($page)) {
    include $page;
} else {
    echo "The page you are looking for cannot be found. To return back to the main page click <a href='example.com'>here</a>";
}

现在您没有文件扩展名,而且URL看起来更清晰。 要阅读有关URL重写的更多信息,请查看以下内容:http://www.workingwith.me.uk/articles/scripting/mod_rewrite