Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined Index while uploading file

Tags:

php

This is my error:

Notice: Undefined index: file in C:\xampp\htdocs\Project\Template1\users\index.php on line 21 Notice: Undefined index: file in C:\xampp\htdocs\Project\Template1\users\index.php on line 23 please uploaded

How to get rid of it?

Html Code:

<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file"><br><br>
<input type="submit" value="submit" name="submit">
</form>

Php Code:

<?php

    $name = $_FILES['file']['name'];
    $temp_name = $_FILES['file']['temp_name'];

    if (isset($name)) {

        if (!empty($name)) {
            $location = '../uploads/';
        }

        if (move_uploaded_file($temp_name, $location.$name)) {
            echo 'uploaded';
        }

    } else {
        echo 'please uploaded';
    }
?>
like image 948
Ashish Singh Avatar asked Sep 26 '13 12:09

Ashish Singh


People also ask

How do you fix Undefined index?

To resolve undefined index error, we make use of a function called isset() function in PHP. To ignore the undefined index error, we update the option error_reporting to ~E_NOTICE to disable the notice reporting.

What is an undefined index?

Undefined Index is the usual error that comes up when we try to access the variable which does not persist. For instance, an array we are trying to access the index does not really exist in that, so in this scenario, we will get an Undefined Index in PHP.

What is $_ files in PHP?

PHP $_FILES The global predefined variable $_FILES is an associative array containing items uploaded via HTTP POST method. Uploading a file requires HTTP POST method form with enctype attribute set to multipart/form-data.


2 Answers

Make sure you have set form attribute enctype="multipart/form-data".

This attribute help you to get files from user.

<form action="PATH" method="post" enctype="multipart/form-data"></form>
like image 171
Nishit Zinzuvadiya Avatar answered Oct 05 '22 00:10

Nishit Zinzuvadiya


Change your PHP script as below and try

<?php 
    if(isset($_POST['submit'])){
        $name       = $_FILES['file']['name'];  
        $temp_name  = $_FILES['file']['tmp_name'];  
        if(isset($name) and !empty($name)){
            $location = '../uploads/';      
            if(move_uploaded_file($temp_name, $location.$name)){
                echo 'File uploaded successfully';
            }
        } else {
            echo 'You should select a file to upload !!';
        }
    }
?>
like image 41
Sherin Jose Avatar answered Oct 05 '22 00:10

Sherin Jose