首頁  >  問答  >  主體

如果檔案已存在,如何使表單重新調整出錯,以防止檔案被編輯或覆寫?

如果檔案已存在,如何使表單重新調整出錯以防止檔案被編輯或覆寫?

如果文件已存在,我不確定如何編輯此程式碼以重新調整錯誤,以防止文件被編輯或覆蓋。

<?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粉949848849372 天前536

全部回覆(1)我來回復

  • P粉895187266

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

    1. 目前,當$name 已經存在時,你的程式碼將使用重命名的目標檔案名稱來保存數據,只需更改這部分,使其顯示錯誤並透過exit() 結束執行;

    2. 另一方面,為什麼您的程式碼會在 else 區塊中回顯「成功發布」?您應該告訴使用者並未輸入所有必需的數據,並要求他/她重新提交。

    3. 順便說一句,您允許使用者輸入一些內容,然後另存為 xxxx.php,這可能是一個嚴重的安全威脅! ! ! 請再考慮一下是否要這樣做它(或不是)

    對於上面的(1)和(2),請將程式碼修改為:

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

    回覆
    0
  • 取消回覆