0

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;
}
Adrian Edy Pratama
  • 3,841
  • 2
  • 9
  • 24
amit
  • 1
  • 1
  • 18
  • 28

2 Answers2

0

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 */

}
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
0

Dear Jigar as per explanation given by you I can understand that you are trying to upload a file somewhere and you are getting an undefined index error message if you are not selecting the file.

As per your code first you are trying to check if the file exist or not with below line of code:

(!file_exists($_FILES['image']['tmp_name']) || !is_uploaded_file($_FILES['image']['tmp_name'])) {
        }

and you are trying to upload with else block

In my opinion you should first

  1. define empty array to save image element in it.

    $saveArr[] = '';
    
  2. do the uploading in if block instead of else. enter code here

    if(!file_exists($_FILES['image']['tmp_name']) || 
     !is_uploaded_file($_FILES['image']['tmp_name'])){ 
    
     $filename = time() . uniqid(rand()) . $_FILES['image']['name'];
     move_uploaded_file($_FILES["image"]["tmp_name"], "vendorProfile/" . $filename);
     $saveArr['image'] = $filename;}
    
Avinash Dalvi
  • 8,551
  • 7
  • 27
  • 53