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.
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.
– Guilherme Nascimento