dongzhijing8202 2014-09-10 02:23
浏览 92
已采纳

使用file_exists()检查类似的文件名以防止覆盖/重复?

I am writing an application in PHP where the user submits a form of data and a file name is chosen based off of the data, like so:

$filename = "./savelocation/".$name."_".$identification."_".$date.'.txt';

I am trying to use the file_exists() function to check to see if a file with the same name exists. If it does, the final name is changed to prevent overwriting the submitted form data. Here is my 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 from overwriting applications by changing the name to a single file which acts as the 'default file' in which it doesn't matter if it is overwritten. However, I know this is wrong. My logic was that the if statement would return true, which would execute the code inside of the statement changing the file name to the 'default file'. Is this even a good way to prevent duplicate submissions?

  • 写回答

2条回答 默认 最新

  • dpkrh2444 2014-09-10 02:49
    关注

    Try this...if there is a match on the file name, break from the loop and redirect

    $userFile = $name."_".$identification."_".$date.'.txt;
    $fileArray = glob('./savelocation/*');
    $arrCount = count($fileArray);
    $i = 1;
    $msg = null;
    
    foreach ($fileArray as $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 you tweak your code a bit to change your file name, this should work:

    if(file_exists($file)) {
        $file = str_replace("\.txt", "duplicate\.txt", $file); 
    }
    

    Change the file name in a way that identifies itself to you as a duplicate.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题