简体   繁体   中英

File upload is not checking for the existing file

I have a php file uploader program. I want to add one more functionality to the program, that is checking whether the same file exists in the directory.

I want to add something like this to my code :

if (file_exists("directory_name/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }  

And Here is my php file uploader code:

<?php

$valid_formats = array("jpg", "png", "gif", "JPEG", "bmp", "JPG", "PNG", "GIF");
$max_file_size = 1024*500; //100 kb
$path = "images/$_POST[fol]/"; // Upload directory
$count = 0;

if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
    // Loop $_FILES to exeicute all files
    foreach ($_FILES['files']['name'] as $f => $name) {     
        if ($_FILES['files']['error'][$f] == 4) {
            continue; 
        }          
        if ($_FILES['files']['error'][$f] == 0) {              

            if ($_FILES['files']['size'][$f] > $max_file_size) {
                $message[] = "$name is too large!.";
                continue;
            }
            elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
                $message[] = "$name is not a valid format";
                continue; 
            }


            else{ 
                if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name))
                $count++; 
            }
        }
    }
}
?>

How to combine both? can anyone help?

Check before moving the file whether the file exists or not .. Try something like

        else{ 
                if (file_exists($path.$name)
                {
                  file already exixts
                }  
                if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name))
                $count++; 
            }

Here is the solution.

 else{ 

                if(!file_exists($path.$name))
                {
                  move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name);
                  $count++; // Number of successfully uploaded file
                } 
                else{
                    echo "File exists";
                                }


  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM