Let me describe my code first.
View:
<?php echo form_open_multipart('question_edit/update_question'); ?>
....
<div class="form-group">
<label for="ask_q" class="">A Brief Description of your question <em>(Optional)</em></label>
<textarea name="ask_q" id="ask_q"><?php echo $uposts->question_desc; ?></textarea>
</div>
<div class="form-group">
<label for="upld" class="">Upload New Docs <em>(Optional)</em></label>
<input type="file" name="upld[]" id="upld" style="width: 100%;" multiple>
</div>
....
<?php echo form_close(); ?>
Please note that my file input field is not mandatory. It is optional.
Controller:
function update_question(){
$update_data = array(
'question_desc' => $this->input->post('ask_q')
);
$this->ask_model->update_q($update_data);
if(!empty($_FILES['upld']['name'])){
$filesCount = count($_FILES['upld']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['userFile']['name'] = $_FILES['upld']['name'][$i];
$_FILES['userFile']['type'] = $_FILES['upld']['type'][$i];
$_FILES['userFile']['tmp_name'] = $_FILES['upld']['tmp_name'][$i];
$_FILES['userFile']['error'] = $_FILES['upld']['error'][$i];
$_FILES['userFile']['size'] = $_FILES['upld']['size'][$i];
$uploadPath = './uploads/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|jpeg|png|doc|docx|xls|xlsx|ppt|pptx|csv|ods|odt|odp|pdf|rtf|txt';
$config['max_size'] = '1048576';
$this->upload->initialize($config);
if(!$this->upload->do_upload('userFile')){
$this->session->set_flashdata('q_failure', 'Something went wrong. Please try again.');
redirect('/user-qa');
} else {
$fileData = $this->upload->data();
$uploadData[$i]['uploaded_file'] = $fileData['file_name'];
}
}
if(!empty($uploadData)){
//Insert files data into the database
$insert = $this->ask_model->insert_upload($uploadData);
}
}
$this->session->set_flashdata('q_success', '<div class="alert-message success">
<i class="icon-ok"></i>
<p><span>Success</span><br>
Your question has been updated successfully.</p>
</div>');
redirect('/user-dashboard');
}
My controller code describes (?) if file upload field is not empty, then upload file.
But the problem is each time I submit the form, it updates the database because of $this->ask_model->update_q($update_data);
but giving the error message Something went wrong. Please try again.
that I used for validating the $config
.
I checked the log file. Log file states
You did not select a file to upload
It seems, my if(!empty($_FILES['upld']['name'])){
is not working.
UPDATE-1
I tried if(isset($_FILES['upld']) && $_FILES['upld']['size'] > 0){
instead of if(!empty($_FILES['upld']['name'])){
but the result is same.
My question is
- Where is the problem ?
- How to validate file size and file extension type ?
UPDATE-2
Tried if($_FILES['upld']['name']){
by seeing this stackoverflow Link but it is also not working.