PHP Rename File name if Exists Append Number to End

前端 未结 3 1782
逝去的感伤
逝去的感伤 2021-01-30 23:40

I\'m trying to rename the file name of an image when it\'s uploaded if it exists, say if my file name is test.jpg and it already exists I want to rename it as

3条回答
  •  [愿得一人]
    2021-01-31 00:14

    There are several ways for renaming image in PHP before uploading to the server. appending timestamp, unique id, image dimensions plus random number etc.You can see them all here

    First, Check if the image filename exists in the hosted image folder otherwise upload it. The while loop checks if the image file name exists and appends a unique id as shown below ...

    function rename_appending_unique_id($source, $tempfile){
    
        $target_path ='uploads-unique-id/'.$source;
         while(file_exists($target_path)){
            $fileName = uniqid().'-'.$source;
            $target_path = ('uploads-unique-id/'.$fileName);
        }
    
        move_uploaded_file($tempfile, $target_path);
    
    }
    
    if(isset($_FILES['upload']['name'])){
    
        $sourcefile= $_FILES['upload']['name'];
        tempfile= $_FILES['upload']['tmp_name'];
    
        rename_appending_unique_id($sourcefile, $tempfile);
    
    }
    

    Check more image renaming tactics

提交回复
热议问题