Reputation: 127
i'm trying to create a form that lets the visitor upload image files. I have been using the code below but keep receiving the "not set
" error as if $_FILES['image']
isn't picking up the image file.
Can anyone see any errors here?
Form code:
<h1>Contact form test</h1>
<form action="php/form.php" method="post">
First name:<br>
<input type="text" name="firstname" required><br>
Last name:<br>
<input type="text" name="lastname" required><br>
<p>
<input type="file" name="image" id="image" enctype="multipart/form-data"><br>
</p>
<input type="submit" value="Submit">
</form>
php code:
// Set variables
$firstname = secure($_POST['firstname']);
$lastname = secure($_POST['lastname']);
// Form Security
function secure($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// File upload
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$extensions= array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be exactly 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}else{
echo "not set";
}
Upvotes: 0
Views: 326
Reputation: 3091
use enctype="multipart/form-data"
in form tag
<form action="php/form.php" method="post" enctype="multipart/form-data">
First name:<br>
<input type="text" name="firstname" required><br>
Last name:<br>
<input type="text" name="lastname" required><br>
<p>
<input type="file" name="image" id="image" enctype="multipart/form-data">
<br>
</p>
<input type="submit" value="Submit">
</form>
Reference : http://php.net/manual/en/features.file-upload.post-method.php
Upvotes: 3
Reputation: 9974
Just adds a multipart attribute for form tag
, which is necessary if you would like to use the form to upload files with. The enctype attribute
specifies how the form-data should be encoded when submitting it to the server.
<form action="demo_post_enctype.asp" method="post" enctype="multipart/form-data">
//you code here
</form>
Also ,the enctype attribute
can be used only if method="post"
.
Upvotes: 1