-3

Before you say this is a duplicate, i will say that i tryed everything i could find on the internet but nothing works. I am trying to upload an image and it gives me this error :

Undefined index: image

<?php 


$target_dir = "images/";
    $target_file = $target_dir . basename($_FILES["image"]["name"]);

    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    if(isset($_POST["submit"])) {


        $check = getimagesize($_FILES["image"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }

    if (file_exists($target_file)) {

        echo "Sorry, file already exists.";
        $uploadOk = 0;

    }

    if ($uploadOk == 0) {
      die(mysqli_error($dbc));
    echo "Sorry, your file was not uploaded.";
} else {
    if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["image"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
  }

 ?>
 <form action="SchimbareImagine.blade.php" method="POST" enctype="multipart/form-data">
<div class="form-group">
      <label>Poster:</label>
      <div class="col-lg-10">
          <input id="input-5" type="file" name = "image" >
        </div>
    </div>
</div>

<button name = "submit" type="submit" id = "submit" >Submit</button>
</form>

Does anyone know how can i fix this ?

Urarii
  • 67
  • 2
  • 13

1 Answers1

1

You are getting this error, because the $_FILES["image"] variable/array was not set yet.

As you are already using the die() method, you could prevent the code to continue executing by something like this:

if(!isset($_FILES["image"])){
    echo "ERROR: no image revived";
    die();
}

Try it like this:

if(isset($_FILES["image"])){
$target_dir = "images/";
    $target_file = $target_dir . basename($_FILES["image"]["name"]);

    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    if(isset($_POST["submit"])) {


        $check = getimagesize($_FILES["image"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }

    if (file_exists($target_file)) {

        echo "Sorry, file already exists.";
        $uploadOk = 0;

    }

    if ($uploadOk == 0) {
      die(mysqli_error($dbc));
    echo "Sorry, your file was not uploaded.";
    } else {
    if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["image"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
  }
}
Jo Smo
  • 6,923
  • 9
  • 47
  • 67