How to check if the input file is empty or not

advertisements

Hello, I have a script for inserting multiple pictures in database and when I want to delete existing files and inserting new ones each time I make the update but I don't know how to make the delete only when the input is a file and if not just skip that part. Here is my code:

$size=$_FILES['files']['size'];
if($size > 1) {
   $query = "Delete from Imagini_Hotel where ID_Hotel='$id_hotel'";
    $result = mysql_query($query)
        or die("query failed: " . mysql_error());
} 

$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
    $file_name = $key.$_FILES['files']['name'][$key];
    $file_size =$_FILES['files']['size'][$key];
    $file_tmp =$_FILES['files']['tmp_name'][$key];
    $file_type=$_FILES['files']['type'][$key];  

    if($file_size > 9097152){
        $errors[]='File size must be less than 9 MB';
    }
    if($file_size <= 0)
    {
    }
    else
    {
    $query="Insert into Imagini_Hotel (`ID_Hotel`,`Nume_Poza`,`Prioritate`) VALUES('$id_hotel','$file_name','$key'); ";
    $desired_dir="../../../images/hotel/$id_hotel";
    if(empty($errors)==true){
        if(is_dir($desired_dir)==false){
            mkdir("$desired_dir", 0777);        // Create directory if it does not exist
        }
        if(is_dir("$desired_dir/".$file_name)==false){
            move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
        }else{                                  // rename the file if another one exist
            $new_dir="$desired_dir/".$file_name.time();
             rename($file_tmp,$new_dir) ;
        }
     mysql_query($query);
    }else{
            print_r($errors);
    }
}}
if(empty($error)){
    echo "Success";
}


There's an ['error'] parameter you can check (and should be checking anyways). Right now you're simply assuming the upload succeeded.

if ($_FILES['tmp_name']['error'][$key] === UPLOAD_ERR_OK) {
   ... file was uploaded ...
} else {
   die("Upload failed with error code " . $_FILES['tmp_name']['error'][$key]);
}

The error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php You're interested in codes 0 (success) and 4 (no file).

As well, note that your upload handling code opens your server to a complete remote compromise. You're directly using a user-provided filename in your move..() operations, allowing a malicious user to scribble on ANY file on the system. Nothing says that the user-provided filename can't contain pathing information, e.g. ['name'] = '../../../../../../../etc/passwd, which your script happily and blindly uses without any filtering/checking.