-1

How to troubleshoot undefined index error when trying to upload image to server? I'm trying to create an API to upload an image to server using PHP and MySQL

An error:

Notice: Undefined index: img_logo in /opt/lampp/htdocs/Carekkerje/upload.php on line 6 {"success":0,"message":"Error Upload image"}

Error in this section:

$img_logo = $_POST['img_logo'];

My code:

upload.php

<?php
    include_once "koneksi.php";

    class emp{}

    $img_logo = $_POST['img_logo'];

    $random = random_word(20);

    $path = "images/".$random.".png";

        // sesuiakan ip address laptop/pc atau URL server
    $actualpath = "http://192.168.43.193/Carekkerje/$path";

    $query = mysqli_query($con, "INSERT INTO transaksi (img_logo) VALUES ('$actualpath')");

        if ($query){
            file_put_contents($path,base64_decode($img_logo));

            $response = new emp();
            $response->success = 1;
            $response->message = "Successfully Uploaded";
            die(json_encode($response));
        } else{ 
            $response = new emp();
            $response->success = 0;
            $response->message = "Error Upload image";
            die(json_encode($response)); 
        }


    // fungsi random string pada gambar untuk menghindari nama file yang sama
    function random_word($id = 20){
        $pool = '1234567890abcdefghijkmnpqrstuvwxyz';

        $word = '';
        for ($i = 0; $i < $id; $i++){
            $word .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
        }
        return $word; 
    }

    mysqli_close($con);

?>  
Dharman
  • 30,962
  • 25
  • 85
  • 135
Kitereative Indonesia
  • 1,097
  • 6
  • 19
  • 39
  • Check if the image is received in $_FILES['img_logo']. If not, `var_dump()` the $_POST and $_FILES arrays and it should be there. – jeprubio Jan 18 '18 at 07:20
  • how to check it .. can you give an example? sorry i have little knowledge about PHP programming language – Kitereative Indonesia Jan 18 '18 at 07:30
  • Don't worry, I didn't think it was necessary but I write you the code as an answer. – jeprubio Jan 18 '18 at 07:33
  • Does this answer your question? ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – Dharman Feb 06 '20 at 12:11

1 Answers1

0

Check if the image is received in $_FILES['img_logo'].

$img_logo = $_FILES['img_logo'];

If not, var_dump($_POST) and var_dump($_FILES) arrays to see its contents and it should be there:

var_dump($_POST);
var_dump($_FILES);

With this you will get the keys and the values of each of this arrays and then you can know where is the file.

And if you still have problems print this var_dump information in the description of your question and we'll be able to help you.

You should get use to var_dump and print_r your variables to debug your code.

jeprubio
  • 17,312
  • 5
  • 45
  • 56