php check file name exist, rename the file

后端 未结 5 1738
忘了有多久
忘了有多久 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: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);
    

提交回复
热议问题