How to fix undefined index error for $_FILE in PHP with SQL

I am trying to store image in SQL database blob. I followed a tutorial but I keep getting this error.

<form action="upload.php" method="POST">
        <input type="file" name="image">
        <input type="submit" name="submit" value="upload">      
    </form>
    <?php
        if(isset($_POST['submit']))
        {
            $conn= mysqli_connect("localhost","root","");
            mysqli_select_db($conn, "namastedb");

            $imageName = mysqli_real_escape_string($conn, $_FILES["image"] ["name"]);
            $imageData = mysqli_real_escape_string($conn, file_get_contents($_FILES["image"] ["tmp_name"]));
            $imageType = mysqli_real_escape_string($conn, $_FILES["image"]["type"]);

            if(substr($imageType, 0, 5) == "image")
            {
                mysql_query("insert into 'product_details' values('','1','$imageName','$imageData') ");
                echo "Image Uploaded.";
            }
            else
                echo "Only images are allowed!";

        }


    ?>

Notice: Undefined index: image in C:\xampp\htdocs\Namaste\upload.php on line 16

Notice: Undefined index: image in C:\xampp\htdocs\Namaste\upload.php on line 17

Warning: file_get_contents(): Filename cannot be empty in C:\xampp\htdocs\Namaste\upload.php on line 17

Notice: Undefined index: image in C:\xampp\htdocs\Namaste\upload.php on line 18 Only images are allowed!

Hi, your form tag is missing the enctype="multipart/form-data" attribute.

chack1172, That has nothing to do with the errors presented.

First you need to move the processing code to the top, where the form will be processed when it is submitted, and not after the form.

Second,

if(substr($imageType, 0, 5) == "image")

Is not a reliable way to do this. Don’t know what tutorial you are following, but it shouldn’t be a tutorial.

  1. PHP file upload
  2. You should be using prepared statements, always, with everything and anything a user has input of.
  3. Your insert statement looks buggy. Is there no primary key? You should be specifying the columns you are inserting.

As far as the errors, I would say the array has been wiped when it get to that section. Do a var dump before that to see what is actually coming in.

@astonecipher are you sure about that? If it is not present $_FILES[‘image’] is not defined. And that’s why he gets the Undefined index: image error.

I stand corrected! It’s been so long since I have done a form that didn’t use ajax! I was wrong, you were right!

http://phphelp.stonecipherprojects.com/files.php

Anyway, as @astonecipher suggested should move the processing code to the top and change the code of the upload script to be more secure.

Sponsor our Newsletter | Privacy Policy | Terms of Service