How can I make a form resize error if the file already exists, preventing the file from being edited or overwritten?
P粉949848849
P粉949848849 2023-09-13 22:06:46
0
1
495

How to make a form resize error to prevent the file from being edited or overwritten if the file already exists?

I'm not sure how to edit this code to readjust the error to prevent the file from being edited or overwritten if the file already exists.

<?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();     
} 
?>

P粉949848849
P粉949848849

reply all(1)
P粉895187266
  1. Currently, when $name already exists, your code will use the renamed target file name to save the data, just change this part so that it displays an error and ends execution with exit();

  2. On the other hand, why does your code echo "published successfully" in the else block? You should tell the user that not all required data was entered and ask him/her to resubmit.

  3. By the way, you allow the user to enter something and then save it as xxxx.php, which could be a serious security threat! ! ! Please think again if you want to do it (or not)

For the above (1) and (2), please modify the code to:

<?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();     
} 
?>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!