简体   繁体   English

fopen $_SERVER[REQUEST_URI]

[英]fopen $_SERVER[REQUEST_URI]

I need to fopen a file with the same name as the url with '.txt' at the end.我需要fopen一个与 url 同名的文件,末尾带有“.txt”。

I have this: fopen("$_SERVER[REQUEST_URI].txt", 'a+')我有这个: fopen("$_SERVER[REQUEST_URI].txt", 'a+')

but I think the forward slash at the beginning of the url is messing things up.但我认为 url 开头的正斜杠把事情搞砸了。

You should probably trim the URI, however this looks ... highly insecure.您可能应该修剪 URI,但这看起来......非常不安全。

$filename = trim($_SERVER['REQUEST_URI'], "/");
$filename .= ".txt";

$handle = fopen($filename, "a+");

To clarify why this is insecure, people could use this to access, potentially, any file in that directory.为了澄清为什么这是不安全的,人们可以使用它来访问该目录中的任何文件。

You should probably have an array of "allowed files" that people may access, and then check to see if the given file is in that array.您可能应该拥有一组人们可以访问的“允许的文件”,然后检查给定的文件是否在该数组中。 For example:例如:

$allowed_files = array(
    "file1.txt",
    "file2.txt",
);

$filename = trim($_SERVER['REQUEST_URI'], "/");
$filename .= ".txt";

if(in_array($filename, $allowed_files)){
    //Success, so they may view the file
    $handle = fopen($filename, "a+");
}else{
    //Failure, they may not
    return false;
}

To keep it generic, try this:为了保持通用,试试这个:

//Validate the filename
$filename = $_SERVER["REQUEST_URI"];
$slashes = explode("/", $filename);
$filename = $slashes[1];
$filename .= ".txt";

$handle = fopen($filename, "a+");

Maybe you want to use the __FILE__ constant:也许你想使用__FILE__常量:

$fp = fopen(preg_replace('/\..+$/', '.txt', __FILE__), 'a+');

Of course, your code would have to be on the correct page.当然,您的代码必须在正确的页面上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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