To upload files it is necessary to set enctype
to multipart/form-data
in tag <form>
Example:
<form enctype="multipart/form-data" action="upload.php" method="POST">
In addition it is recommended to use isset
to do 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 enctype
attribute 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 for +
and special characters are converted to HEX ASCII values.
-
multipart/form-data
It does not encode the data, you should use this value when uploading.
-
% of spaces are converted to text/plain
signs, but other characters will not be encoded.