将$ _GET ['']与字符串混合? [关闭]

Alright, so i am trying to do the following:

<?php include('pages/{$_GET["page"]}.txt'); ?>

Wich doesnt work. It is placed in a working site inside a , so it just leaves the div blank.

If i do this:

<?php include('pages/index.txt'); ?>

it works.

I am connecting to mydomain.com/?page=index Can anyone give me some tips here?

I tried searching, but without luck.

Edit: As many have said, doing what you want this way is unsafe. Here's an easy way to make it better:

<?php 
    $valid_pages = array('index', 'contact', 'faq');
    $page = $_GET["page"];

    if (!in_array($page, $valid_pages)) {
        $page = $valid_pages[0];
    }

    include("pages/{$page}.txt"); 
?>

This will check if the page the user wants is within the allowed pages, if not, it will use the first one in the $valid_pages array.

Try this:

<?php include('pages/' . $_GET["page"] . '.txt'); ?>

First, DO NOT DO THIS! It's so insecure! I can access any file on your site if you do this. SO BAD.

Now, the actual problem with what you have is that your string is in single quotes. If you change it to double quotes, it'll work. But you still should NOT DO THIS.

$foo = "QQQ";

echo "asfd{$foo}asdf";
> asfdQQQasdf
echo 'asfd{$foo}asdf';
> asdf{$foo}asdf

One way to fix your vulnerability is to have a white list. Here's a simple example:

$file = "foo";

switch ($file) {
    case "foo":
        include ("pages/foo.txt");
        break;
    case "bar":
        include ("pages/bar.php");
        break;
    default:
        echo "YOU CANNOT ACCESS THIS FILE!";
        break;
}

Another way is to have an array of acceptable file names and check if the requested files is in that array.

If you must do this then

<?php include('pages/' . {$_GET["page"]} . '.txt'); ?>

But as others have mentioned, this does expose a security vulnerability. At least do some checking on the page parameter to ensure it doesn't link you to files outside of the web server.

$_GET['page'] = "index";
$allowed_page = array("index", "about", "contact");
$page = htmlentities($_GET['page']);
if((isset($_GET['page']) && $_GET['page'] != "")  && in_array($page, $allowed_page)){
$page = $_GET['page'];
}
$final_page =  'pages/' . $_GET["page"].'.txt';
include($final_page);