我需要fopen
一个与'.txt'结尾的URL同名的文件。
我有这样的:fopen("$_SERVER[REQUEST_URI].txt", 'a+')
,但我认为在URL开头的斜杠是搞乱的东西了。
我需要fopen
一个与'.txt'结尾的URL同名的文件。
我有这样的:fopen("$_SERVER[REQUEST_URI].txt", 'a+')
,但我认为在URL开头的斜杠是搞乱的东西了。
您应该修剪URI,但是这看起来......非常不安全。
$filename = trim($_SERVER['REQUEST_URI'], "/");
$filename .= ".txt";
$handle = fopen($filename, "a+");
要澄清为什么这是不安全的,人们可以使用它来访问该目录中的任何文件。
您应该有一个人们可以访问的“允许的文件”数组,然后检查给定的文件是否在该数组中。例如:
$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;
}
为了保持其通用性,试试这个:
//Validate the filename
$filename = $_SERVER["REQUEST_URI"];
$slashes = explode("/", $filename);
$filename = $slashes[1];
$filename .= ".txt";
$handle = fopen($filename, "a+");
也许你想使用__FILE__
常数:
$fp = fopen(preg_replace('/\..+$/', '.txt', __FILE__), 'a+');
当然,你的代码必须是在正确的页面上。
当你运行这个时会发生什么?你得到什么错误信息? –