简体   繁体   中英

Get URL query string and work with it in PHP

I'm not 100% certain where I am messing this up (most likely the check if file exists bit) but what I am trying to do is:

  • Get the query of the page eg example.com?example
  • Then use that string to work with the file path ( in this case news/example.php )
  • Then see if that file exists
  • Then if it does, include that file, if not echo an error message.

This is the code I have:

    $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>";
    }

If the query has to become example.com?news/example.php it wouldn't be the end of the world, but the shorter the better; leaving it as just the filename, without the extension, would be better.

PHP Concatenation does not support + , you have to use . .

$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>";
}

Try this, and let me know is it works for you or not.

In this case URL Rewriting would be much more relevant. Create .htaccess file with this:

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

If you are familiar with regex, you'd know that the enclosed brackets () are for capturing the match.

[^/\\.]+ is, one or more characters that isn't a forward slash or a period.

After capturing the match, it'll substitute it in the news.php?filename=

So, when you request http://example.com/news/helloworld , you will be served the http://example.com/news.php?filename=helloworld

Now, your news.php file should be like this:

$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>";
}

Now you don't have the file extension and the URL looks a lot cleaner. To read more on URL rewriting, take a look at this: http://www.workingwith.me.uk/articles/scripting/mod_rewrite

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM