当使用$ _POST属性文件名时,如何告诉PHP将文件保存在特定文件夹中?
I'm having some trouble getting my script to save a file in a particular folder, normally the syntax would call for quotes around the entire path but because I'm using $_POST to name the file it just doesn't work out that way. So far this is what I have.
<?php ini_set('display_errors','on'); ?><?php
$fileName= fopen("Submissions/".$_POST['first_name'],'w');
$data= "";
foreach ($_POST as $key => $value) {
$data.= str_replace("_"," ",$key).":
". $value."
"; preg_replace("/[^ 0-9a-zA-Z]/", "_", $value);
}
fwrite($fileName, $data);
fclose($fileName);
?>
我在将脚本保存到特定文件夹时遇到一些问题,通常语法会调用 引用整个路径,但因为我使用$ _POST来命名文件,所以它不会那么成功。 到目前为止,这就是我所拥有的。 p>
&lt;?php ini_set('display_errors','on'); ?&gt;&lt;?php
$ fileName = fopen(“Submissions /".$_ POST ['first_name'],'w');
$ data =”“;
foreach($ _POST as $ key =&gt; $ value){
$ data。= str_replace(“_”,“”,$ key)。“:
”。 $值 “
”。 preg_replace(“/ [^ 0-9a-zA-Z] /”,“_”,$ value);
}
fwrite($ fileName,$ data);
nclclose($ fileName);
\ n
?&gt;
code> pre>
div>
You have several problems. First, you have syntax errors. Second, you have serious security vulnerabilities.
Let's start with the first syntax errors. This line:
$fileName= fopen(Submissions/$_POST['first_name'],'w');
Is invalid. You want to use string concatenation, like this:
$fileName= fopen("Submissions/" . $_POST['first_name'],'w');
But that's a huge security vulnerability. If $_POST['first_name']
is something bad like ../../../etc/passwd
, you could be in for a world of hurt.
Then there's this:
fwrite(Submissions/$fileName, $data);
That's invalid syntax (again, string concatenation) and, again, insecure. It's also just wrong. You need a file resource, not a path name, as the first parameter.
In both of these places, you must validate the data before using it this way. Otherwise, expect to get hacked repeatedly.