简体   繁体   中英

php include a file with a variable name?

I am trying to include a file from a cookie

say my cookie has a value

$file = $_COOKIE['PageValue'];

I want to include this file like this

include '$file';

is there a way of achieving this?

cheers

if( file_exists($_SERVER['DOCUMENT_ROOT'].$file){
    include $_SERVER['DOCUMENT_ROOT'].$file; 
}

!! A VERY BIG WARNING !! This example is TOO simple. ALWAYS validate userinput, especially when including files.

Good practice would be checking if $file is in an array with allowed $files, or maybe check in a database.

This is a fragile part, XSS is just arround the corner.

You might want to read this: http://en.wikipedia.org/wiki/File_inclusion_vulnerability

See this link: from the manual

 include $_COOKIE['PageValue'];

You may want to add null checks and constraints if you're not sure if the value would always return valid values

Yes, you wrote the answer:

include $file; // No quotes!

But, you should sanitize your input, best do a whitelisting of files possible to include. For further help, post example of your code, or give us further info what you're trying to accomplish.

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