Patrick
Patrick

Reputation: 15

Uploading File Annoying Error

I have been trying to research why this issue continues to come up. I am getting the error:

Notice: Undefined index: file in C:\xampp2\htdocs\Onboarding\OnBoarding\test.php on line 7
Notice: Undefined index: file in C:\xampp2\htdocs\Onboarding\OnBoarding\test.php on line 9

Now I know what these mean...basically the array is empty and it is Undefined. How do I prevent this from showing? Here is my very simple code:

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

<?php
$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];

if(isset($name)){
    if(!empty($name)){
        $location = "files/application_other/";

        if (move_uploaded_file($tmp_name, $location.$name));
        echo "Uploaded!";
    } else {
        echo "Please choose a file";
    }
}
?>

The file does upload properly, I just cant figure out how to remove the error messages.

Thank you for the help in advance.

Upvotes: 0

Views: 32

Answers (1)

user229044
user229044

Reputation: 239301

You must check whether the array contains the given key, before accessing it.

if (array_key_exists('file', $_FILES)) {
  $name = $_FILES['file']['name'];
}

Upvotes: 1

Related Questions