Saoud ElTelawy
Saoud ElTelawy

Reputation: 190

PHP: Form Validation "Upload many files"

I am facing an issue with the below code, I can upload multiple files but still need that the if condition not be executed till user chooses a file as it is not good to see Unique ID and the echo message run however no files chosen!

PHP

<?php 
$path = "Uploads/Files/";

if( (isset($_POST['submit'])) && (!empty ($_FILES['myFile']['name'])) ){

 $countfiles = count($_FILES['myFile']['name']);

 for($i=0;$i<$countfiles;$i++){
  $filename = uniqid(). $_FILES['myFile']['name'][$i];
    // Upload file
  move_uploaded_file($_FILES['myFile']['tmp_name'][$i], $path.$filename);
  echo "<h3> $filename has been uploaded Successfully!</h3>";
 }
} 

?>

So I want the && part above to be valid as well and not below message to appear till files be chosen.

HTML

<form method='post'  enctype='multipart/form-data'>
    <input type="file" name="myFile[]" id="file" multiple>
    <input type='submit' name='submit' value='Upload'>
</form>

Error: Once I pressed upload and no files it tuns the IF and echo <h3> tag

Upvotes: 1

Views: 38

Answers (1)

there are two parts:

  1. add validation for required field <input type="file" name="myFile[]" id="file" multiple required>
  2. render whatever you want instead of echo "<h3> $filename has been uploaded Successfully!</h3>";

Upvotes: 1

Related Questions