php - Using file_exists() to check for similar file names to prevent overwriting/duplicates? -
i writing application in php user submits form of data , file name chosen based off of data, so:
$filename = "./savelocation/".$name."_".$identification."_".$date.'.txt'; i trying use file_exists() function check see if file same name exists. if does, final name changed prevent overwriting submitted form data. here implementation:
$file = "./savelocation/".$name."_".$identification."_".$date.'.txt'; $file = preg_replace('/\s+/', '', $file); $filepath = "./savelocation/".$name."_".$identification."_".$date.'.txt'; if(file_exists($filepath)) { $file = "./savelocation/"."invalidfile".'.txt'; } this prevents people overwriting applications changing name single file acts 'default file' in doesn't matter if overwritten. however, know wrong. logic if statement return true, execute code inside of statement changing file name 'default file'. way prevent duplicate submissions?
try this...if there match on file name, break loop , redirect
$userfile = $name."_".$identification."_".$date.'.txt; $filearray = glob('./savelocation/*'); $arrcount = count($filearray); $i = 1; $msg = null; foreach ($filearray $fa) { $filesubstring = str_replace("\.\/savelocation\/", "", $fa); if ($i > $arrcount) { break; } else if ($userfile === $filesubstring) { $msg = 'repeat'; break; } else null; $i++; } if (isset($msg)) header('location: pagethatchastisesuser.php'); alternatively, if tweak code bit change file name, should work:
if(file_exists($file)) { $file = str_replace("\.txt", "duplicate\.txt", $file); } change file name in way identifies duplicate.
Comments
Post a Comment