Monogot
Monogot

Reputation: 191

How can i check if input array filed type file empty doesn't upload

How can i check array input type file is empty before upload data in database. if have one empty show anything that user understand and don't updata data.

This is example code html

 <h3>Extra profile information</h3>
 <table class="form-table">
     <tr>
     <th><label for="Upload">Upload</label></th>
     <td>
        <form action="" method="post">
        <input name="profile_photo[]" type="file"  value="" />
        <input name="profile_photo[]" type="file"  value="" />
        <input name="profile_photo[]" type="file"  value="" />
        <br/>
    </form>
     </td>
 </table>

I used to use $x=$_GET['profile_photo']; and echo $x; before upload to database and it return empty or null.

Upvotes: 0

Views: 2997

Answers (5)

Ram Chander
Ram Chander

Reputation: 1522

in javascript/jquery

var file = $(".profile_photo").map(function(){return $(this).val();}).get();


for(var i=0; i<file.length; i++){
   if( file[i] == ""){
     alert("Please select file");
     return false;
   }
}

in PHP

if( $_FILES['profile_photo']['error'] != 0 ){
   // code to handle if there is no file selected
}

Upvotes: 0

paulitto
paulitto

Reputation: 4673

You can also validate inputs by javascript before submission

html:

<form action="" method="post" onsubmit="return validateInputs();">
    <input name="profile_photo[]" type="file"  value="" />
    <input name="profile_photo[]" type="file"  value="" />
    <input name="profile_photo[]" type="file"  value="" />
    <input type="submit" />
</form>

javascript:

validateInputs = function() {    
    inputs = document.getElementsByName('profile_photo[]');
    for (var ind in inputs){
        if (inputs[ind].value=="") {
            alert("validation failed");
            return false;
        }
    }         
}

Upvotes: 0

chandresh_cool
chandresh_cool

Reputation: 11830

Just run a for loop on the post data and verify

$error = "";
$emptyFiles="";
$i=0;
foreach ($_FILES['profile_photo'] as $name) {
   if (isset($name['name']) && $name['name']!="") {
       $error.="";
   } else {
       $error.= "yes";
       $emptyFiles.=$_FILES['profile_photo'][$i];
   }
    $i++;
}

Then use

$error and $emptyFiles string to get which are empty fields and which are not.

Upvotes: 0

ankit
ankit

Reputation: 455

$x=$_FILES['profile_photo']['name']; 

USE THIS CODE

Upvotes: 2

Dino Babu
Dino Babu

Reputation: 5809

if (!empty($_FILES) && is_array($_FILES)) {

  // you have files
}

Upvotes: 2

Related Questions