Upload does not work $_FILES Undefined index error

Asked

Viewed 11,862 times

10

While uploading a file I’m getting the following error:

Notice: Undefined index: file in Z: web upload.php on line 3

upload.php:

<?php
$location = 'uploads/';
$arquivo = $_FILES['file'];

if ($arquivo) {
    $name = $arquivo['name'];
    $tmp_name = $arquivo['tmp_name'];

    $error = $_FILES['file']['error'];
    if ($error !== UPLOAD_ERR_OK) {
        echo 'Erro ao fazer o upload:', $error;
    } elseif (move_uploaded_file($tmp_name, $location . $name)) {
        echo 'Uploaded';    
    }
}

Form:

<form action="upload.php" method="POST">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>
  • Mr Downvoter please read: http://answall.com/help/self-answer and http://blog.stackoverflow.com/2012/05/encyclopedia-stack-exchange and if you have any other pro downvote reason please justify.

1 answer

23


To upload files it is necessary to set the enctype for multipart/form-data on the tag <form>

Example:

<form enctype="multipart/form-data" action="upload.php" method="POST">

In addition it is recommended to use isset to make the error treatments:

if (isset($_FILES['file'])) {
    $arquivo = $_FILES['file'];
    $tmp_name = $_FILES['file']['tmp_name'];

The code should look like this:

upload.php

<?php
$location = 'uploads/';

if (isset($_FILES['file'])) {
    $name = $_FILES['file']['name'];
    $tmp_name = $_FILES['file']['tmp_name'];

    $error = $_FILES['file']['error'];
    if ($error !== UPLOAD_ERR_OK) {
        echo 'Erro ao fazer o upload:', $error;
    } elseif (move_uploaded_file($tmp_name, $location . $name)) {
        echo 'Uploaded';    
    }
} else {
    echo 'Selecione um arquivo para fazer upload';
}

Form:

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

What is enctype?

The attribute enctype defines how the form data will be encoded when sending the data to the server, there are 3 types of values for this attribute:

  • application/x-www-form-urlencoded this is the default value. In it all characters are encoded before being sent, for example spaces are exchanged by + and special characters are converted to ASCII HEX values.

  • multipart/form-data It uncoded the data, you must use this value when uploading.

  • text/plain spaces are converted into signs of + but other characters will not be encoded.

  • 1

    Excellent answer because it highlights the processing of images before the processing of the form as a whole.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.