http55 http55 - 1 month ago 15
PHP Question

isset() Returns false on file

I'm trying to make a simple page that has a upload button, which I changed the name of to be "Upload" instead of "Choose file", I also just wanted to have one button, not "choose" file and a "submit" buttons.

<!DOCTYPE html>
<html>
<head>
<style>
input[type="file"] {
display: none;
}
.custom-file-upload {
background-color: #0fffff;
}
</style>
</head>
<body>
<form action="" name="file" method="post" enctype="multipart/form-data">
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i> Upload
</label>
<input id="file-upload" type="file" />
</div>
</form>

<?php
if(isset($_FILES['file'])) {
echo"file exists";
}
else {
echo"file doesn't exist";
}

?>
</body>
</html>


The line:

if(isset($_FILES['file']))


Always returns false, I also tried:

Using
!empty()

I have to use a form of
type="file"
, as I only want to have one button, the "Upload" button, which uploads and submits at the same time.

I'm not sure where I've gone wrong here, any help would be much appreciated!

Answer

You need to use Javascript to submit the form when the user selects a file.

And you need to give a name to the file input, to match the key in $_FILES.

document.getElementById("file-upload").addEventListener("change", function() {
  this.form.submit();
});
<form action="" method="post" enctype="multipart/form-data">
  <label for="file-upload" class="custom-file-upload">
    <i class="fa fa-cloud-upload"></i> Upload
  </label>
  <input id="file-upload" type="file" name="file" />
  </div>
</form>

Comments