php check file name exist, rename the file

后端 未结 5 1729
忘了有多久
忘了有多久 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

    :)

    0 讨论(0)
  • 2020-12-17 04:31

    Try something like:

    $fullpath = 'images/1086_002.jpg';
    $additional = '1';
    
    while (file_exists($fullpath)) {
        $info = pathinfo($fullpath);
        $fullpath = $info['dirname'] . '/'
                  . $info['filename'] . $additional
                  . '.' . $info['extension'];
    }
    
    0 讨论(0)
  • 2020-12-17 04:32

    I feel this would be better. It will help keep track of how many times a file with the same name was uploaded. It works in the same way like Windows OS renames files if it finds one with the same name.

    How it works: If the media directory has a file named 002.jpg and you try to upload a file with the same name, it will be saved as 002(1).jpg Another attempt to upload the same file will save the new file as 002(2).jpg

    Hope it helps.

    $uploaded_filename_with_ext = $_FILES['uploaded_image']['name'];
    $fullpath = 'media/' . $uploaded_filename_with_ext;
    $file_info = pathinfo($fullpath);
    $uploaded_filename = $file_info['filename'];
    
    $count = 1;                 
    while (file_exists($fullpath)) {
      $info = pathinfo($fullpath);
      $fullpath = $info['dirname'] . '/' . $uploaded_filename
      . '(' . $count++ . ')'
      . '.' . $info['extension'];
    }
    $image->save($fullpath);
    
    0 讨论(0)
  • 2020-12-17 04:41

    You can change your if statement to a while loop:

    $newpath = $fullpath;
    while(file_exists($newpath)) {
        $newpieces = explode(".", $fullpath);
        $frontpath = str_replace('.'.end($newpieces),'',$fullpath);
        $newpath = $frontpath.'1.'.end($newpieces);
    }
    
    file_put_contents($newpath, file_get_contents($_POST['upload']));
    
    0 讨论(0)
  • 2020-12-17 04:49

    Why not just append a timestamp onto the filename? Then you won't have to worry about arbitrarily long filenames for files which have been uploaded many times.

    0 讨论(0)
提交回复
热议问题