Quantcast
Viewing all articles
Browse latest Browse all 5

Read HTML5 Multiple File Input from PHP

Ok, so you have a HTML 5 file input markup on your view and you have enabled multiple attribute to true. You may also be using widgets based on HTML5 input like \kartik\widgets\FileInput. But when you read a file in PHP Server code using $_FILES you do not see an array of files. Similarly, when using a PHP framework like Yii, in the controller using CUploadedFile (Yii1) or
UploadedFile (Yii2), you do not see a list of multiple files that you selected in your view, but only one row.

File Input Markup

Your HTML markup in your view is something like this and you don’t know why this is not working?

<input name="uploadFile" type="file" multiple="multiple">

Solution

  1. You must set your form’s encoding type to multipart/form data (enctype="multipart/form-data") for file uploads.
  2. You must configure the attribute name for HTML5 file input in ARRAY FORMAT for PHP to recognize it as an array of files.

So here is how you achieve this as shown below (note the square brackets in the attribute naming):

Your Form Layout

For Generic PHP/HTML

<form enctype="multipart/form-data" action="file-upload.php" method="POST">
<input name="uploadFile[]" type="file" class="file" multiple="multiple">
</form>

For Yii 1.1

$form = $this->beginWidget('CActiveForm', array(
    'options'=>['encytype'=>'multipart/form-data']
));
echo $form->fileInput($model, 'uploadFile[]', array('multiple' => true));
$this->endWidget();

For Yii 2

use \yii\widgets\ActiveForm;
$form = ActiveForm::begin([
    'options'=>['encytype'=>'multipart/form-data']
]);
echo $form->field($model, 'uploadFile[]')->fileInput(['multiple' => true]);
ActiveForm::end;

For \kartik\widgets\FileInput (Yii 2)

use \yii\widgets\ActiveForm;
$form = ActiveForm::begin([
    'options'=>['encytype'=>'multipart/form-data']
]);
echo $form->field($model, 'uploadFile[]')->widget(FileInput::classname(), [
    'options'=>['multiple' => true]
]);
ActiveForm::end;

Now when you fetch your uploaded files after form submission using $_FILES['uploadFile'], you should receive an array of files for processing.

// PHP Server Code to process submitted form
$numUploadedfiles = count($_FILES['uploadFile']);
for($i = 0; $i < $numUploadedfiles; $i++)
{
    echo "<br>filename " . $i . " is: " . $_FILES['uploadFile'][$i];
    // or do whatever
}

The post Read HTML5 Multiple File Input from PHP appeared first on Krajee Web Tips.


Viewing all articles
Browse latest Browse all 5

Trending Articles