英文:
How can I make the form retune an error if the file already exists to prevent the file being edited or overwritten?
问题
我理解了,以下是您要翻译的内容:
如何使表单在文件已经存在时返回错误,以防止文件被编辑或覆盖?
我不确定如何编辑这段代码,以在文件已经存在时返回错误,以防止文件被编辑或覆盖。
<?php
if ($_POST["potus"] || $_POST["data"]) {
$name = $_POST['potus'];
$data = $_POST['data'];
static $ext = ".php";
if (file_exists($name)) { //rename exist file with random string
$n = rand();
$filename = $name . $n . $ext;
} else {
$filename = $name . $ext; // Creates file if it doesn't exist
}
file_put_contents($filename, $data);
} else {
echo "successfully posted";
exit();
}
?>
英文:
How can I make the form retune an error if the file already exists to prevent the file being edited or overwritten?
I am not sure how to edit this code to retune an error if the file already exists to prevent the file being edited or overwritten.
<?php if( $_POST["potus"] || $_POST["data"] ){
$name = $_POST['potus'];
$data = $_POST['data'];
static $ext = ".php";
if(file_exists($name)){ //rename exist file with random string
$n = rand();
$filename = $name.$n.$ext;
}
else
{
$filename = $name.$ext ; // Creates file if it doesn't exist
}
file_put_contents($filename , $data);
}
else
{
echo "successfully posted";
exit();
}
?>
答案1
得分: 1
-
目前,您的代码会在 $name 已存在时使用重命名的目标文件名来保存数据,只需更改此部分以显示错误并通过 exit(); 终止执行。
-
另一方面,为什么您的代码在 else 块中回显 "successfully posted"?您应该告诉用户没有输入所有必需的数据,并要求他/她重新提交。
-
顺便说一下,您允许用户输入内容然后保存为 xxxx.php,这可能是一个严重的安全威胁!请再次考虑是否要这样做(或不要这样做)。
对于上述的问题 (1) 和 (2),请将代码修改为以下内容:
英文:
-
Currently your code will use a renamed target filename to save the data when $name already exists , just change this part so that it will display an error and end the execution by exit();
-
On the other hand, why will your code echo "successfully posted" in the else block ? You should instead tell the user that not all the required data are entered and ask him/her to re-submit them.
-
By the way, you are allowing user to enter something and then save as xxxx.php, it can be a serious security threat !!! Please think again whether you want to do it (or not)
For (1) and (2) above , please revise the code to something like:
<?php
if( $_POST["potus"] || $_POST["data"] ){
$name = $_POST['potus'];
$data = $_POST['data'];
static $ext = ".php";
// Checking the file exists with extn .php
if(file_exists($name.$ext)){
echo "<script>alert('Filename already exists ! Cannot proceed !');history.go(-1);</script>";
exit();
//$n = rand();
//$filename = $name.$n.$ext;
} else {
$filename = $name.$ext ; // Creates file if it doesn't exist
}
file_put_contents($filename , $data);
} else {
//echo "successfully posted";
echo "You have not entered all the required data ! Please re-submit the data";
exit();
}
?>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论