php check file name exist, rename the file

后端 未结 5 1749
忘了有多久
忘了有多久 2020-12-17 04:07

How do I check if file name exists, rename the file?

for example, I upload a image 1086_002.jpg if the file exists, rename the file as 1086_0021.

5条回答
  •  忘掉有多难
    2020-12-17 04:26

    I hope this helps

    $fullPath = "images/1086_002.jpg" ;
    $fileInfo = pathinfo($fullPath);
    list($prifix, $surfix) = explode("_",$fileInfo['filename']);
    $x = intval($surfix);
    $newFile = $fileInfo['dirname'] . DIRECTORY_SEPARATOR . $prifix. "_" . str_pad($x, 2,"0",STR_PAD_LEFT)  . $fileInfo['extension'];
    while(file_exists($newFile)) {
        $x++;
        $newFile = $fileInfo['dirname'] . DIRECTORY_SEPARATOR . $prifix. "_" . str_pad($x, 2,"0",STR_PAD_LEFT)  . $fileInfo['extension'];
    }
    
    file_put_contents($newFile, file_get_contents($_POST['upload']));
    

    I hope this Helps

    Thanks

    :)

提交回复
热议问题