Search code examples
phpimage-uploading

Message: Undefined index: image on updating image PHP


I want to update my image but I want if I am not updating any image then the previous image should not be removed But right now if I am not passing "image" parameter then I am getting the following error "Message: Undefined index: image", I just want that if I do not pass "image" parameter then the error should not display, How can I resolve this error? Here is my code

if (!file_exists($_FILES['image']['tmp_name']) || !is_uploaded_file($_FILES['image']['tmp_name'])) {
} else {
    $filename = time() . uniqid(rand()) . $_FILES['image']['name'];
    move_uploaded_file($_FILES["image"]["tmp_name"], "vendorProfile/" . $filename);
    $saveArr['image'] = $filename;
}

Solution

  • Using file_exists($_FILES['image']['tmp_name'] where there has been no image upload causes the undefined index error because you assume that $_FILES['image'] does exist at that point so you should test initially for whether or not image exists in the $_FILES array - using isset for example. I had not intended this to be an answer as I felt the comment should have been enough but perhaps it will help.

    if( isset( $_FILES['image'] ) ){
        /* an image was uploaded */
        $obj=(object)$_FILES['image'];
        $tmp=$obj->tmp_name;
        $name=$obj->name;
    
        if( is_uploaded_file( $tmp ) ){
            $filename = time() . uniqid( rand() ) . $name;
            move_uploaded_file( $tmp, "vendorProfile/{$filename}" );
            $saveArr['image'] = $filename;  
        }
    
    } else {
        /* no image uploaded - do something else */
    
    }