Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file upload php $_FILES undefined index error

<?php

$name = $_FILES["file"]["name"];
//$size = $_FILES['file']['size']
//$type = $_FILES['file']['type']


$tmp_name = $_FILES['file']['tmp_name'];

$error = $_FILES['file']['error'];

if (isset ($name)) {
    if (!empty($name)) {

    $location = 'uploads/';

    if  (move_uploaded_file($tmp_name, $location.$name)){
        echo 'Uploaded';    
        }

        } else {
          echo 'please choose a file';
          }
    }
?>

<form action="upload.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="file"><br><br>
    <input type="submit" value="Submit">
</form>

i get an 'Notice: Undefined index' error message. The enctype is included in the form tag so i can't figure out what it is.. can anyone help me out??

like image 461
michAmir Avatar asked Jan 21 '14 23:01

michAmir


1 Answers

If you're using your entire code as one file (which I suspect you are), then you need to do the following using a conditional statement, which I tested (and working) before posting.

Plus, make sure that your uploads folder has proper write permissions set and it exists.

<?php

if(isset($_POST['submit'])){
$name = $_FILES["file"]["name"];
//$size = $_FILES['file']['size']
//$type = $_FILES['file']['type']

$tmp_name = $_FILES['file']['tmp_name'];
$error = $_FILES['file']['error'];

if (isset ($name)) {
    if (!empty($name)) {

    $location = 'uploads/';

    if  (move_uploaded_file($tmp_name, $location.$name)){
        echo 'Uploaded';    
        }

        } else {
          echo 'please choose a file';
          }
    }
}
?>

<form action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="file"><br><br>
    <input type="submit" name="submit" value="Submit">
</form>

Footnotes:

I added a conditional statement:

if(isset($_POST['submit']))

and I named the submit button: (to work in conjunction with the isset() conditional statement)

<input type="submit" name="submit" value="Submit">

N.B.: If you are in fact using your posted code as two seperate files, then you can simply copy the PHP in this answer, along with naming your present submit button set in a seperate HTML form as name="submit" (calling your form upload_form.htm for example) as I did shown above, yet retaining the action="upload.php" and naming the PHP upload handler file accordingly.

like image 90
Funk Forty Niner Avatar answered Sep 21 '22 17:09

Funk Forty Niner