search

Home  >  Q&A  >  body text

How can I make a form resize error if the file already exists, preventing the file from being edited or overwritten?

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粉949848849P粉949848849427 days ago622

reply all(1)I'll reply

  • P粉895187266

    P粉8951872662023-09-14 15:59:48

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

    reply
    0
  • Cancelreply