legolas1211 legolas1211 - 2 months ago 8
PHP Question

'Undefined index' When trying to upload photo?

I am trying to upload an image from a form, however I keep getting the error: Undefined index: file

<form action ="upload.php" method="post">
<label for="name">Image</label>
<input type="file" id="title" name="file" />
<input type="submit" value="Submit" name="submit" />
</form>


And then in upload.php

if (isset($_POST['submit'])) {
$file_name = $_FILES['image']['name'];
$file_type = $_FILES['image']['type'];
$file_size = $_FILES['image']['size'];
$file_tmp_name = $_FILES['image']['tmp_name'];

if($file_name){
move_uploaded_files(file_tmp_name,"uploads/$file_name");
}
}


$_POST['submit'] to $_POST['file'] however I get the same error. Thanks

Answer

first add enctype in your form

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

and then In your PHP code use name instead of image with $_FILES.

if (isset($_POST['submit'])) {
$file_name = $_FILES['file']['name'];
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
$file_tmp_name = $_FILES['file']['tmp_name'];

if($file_name){
move_uploaded_files(file_tmp_name,"uploads/$file_name");
}
}