getting file name as null by using var_dump - php

I have created file uploading function using ajax and codeigniter the problem is that when I am trying to upload an image it is working fine but when I try to upload document or excel file it is giving me null can anybody help me out to fix this issue
here is what error I am getting Array ( [error] => The filetype you are attempting to upload is not allowed.)
Here is my controller
public function post_forum() {
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'gif|jpg|png|doc|docx|xls|xlsx|pdf';
$this->load->library('upload', $config);
if(!empty($_FILES['post_image']['name'])) {
if (!$this->upload->do_upload('post_image')) {
$error = array('error' => $this->upload->display_errors());
} else {
$dt = $this->upload->data();
$file = $dt['file_name'];
}
} else {
$file = '';
}
$word_dta = $this->input->post('post_dt');
$time_posted = time();
$user_id = $this->basic_model->is_login($this);
empty($this->input->post('group_id')) ? $group_id = '' : $group_id = $this->input->post('group_id');
empty($this->input->post('c_id')) ? $company_id = '' : $company_id = $this->input->post('c_id');
$data_upload = array(
'upload_document' => $file,
'discussion' => $word_dta,
'user_id' => $user_id,
'group_id' => $group_id,
'company_id' => $company_id,
'time_posted' => $time_posted,
'status' => 'Posted'
);
$post_id = $this->basic_model->insertRecord($data_upload, 'forums');
$data = array(
'file_name' => $file,
'data' => $word_dta,
'time_posted' => $time_posted,
'post_id' => $post_id,
'name' => $this->basic_model->getUserData(),
'command' => 'Submit Post'
);
$this->load->view('forum/includes/get_data', $data);
}
This is my html form which I have created in views folder
<form method="POST" action="" id="postform" enctype="multipart/form-data" onsubmit="return false;">
<input type="file" id="imageFieldId" name="post_image" />
<div id="contentbox" contenteditable="true" name="post_dt">
</div>
<input type="submit" id="sb_art" class="btn_v2" value="Start Discussion" />
</form>
This is my ajax call
$(document).ready(function(e) {
$("#postform").on('submit', (function(e) {
$("#load").show();
var form = this;
var formData = new FormData(this);
formData.append('post_dt', $("#contentbox").html());
$.ajax({
url : "http://tfsquare.com/demo/forums/post_forum",
type : "POST",
data : formData,
contentType : false,
cache : false,
processData : false,
success : function(data) {
$("#data_update").prepend($(data).fadeIn('slow'));
$("#contentbox").empty();
$('.no_st').css('display', 'none');
form.reset();
},
complete: function() {
$("#load").hide();
}
});
}));
});

$config['allowed_types'] = 'gif|jpg|png|doc|docx|xls|xlsx|pdf';
Codeigniter validate files not only with their extension but also with their MIME type. Probably Your given excel files doesn't have the mime entries in your Mimes.php which is located in config.php.
If you can find the content type add add it to the mime array in mimes.php. If not manually validate the extension by exploding the file name and Do not use codeigniter's 'allowed_types'.
Try this
if(!empty($_FILES['post_image']['name'])) {
if (!$this->upload->do_upload('post_image')) {
$error = array('error' => $this->upload->display_errors());
} else {
$ext = ['xls', 'xlsx'];
$dt = $this->upload->data();
$file = $dt['file_name'];
if( in_array($dt['file_ext'], $ext){
echo 'Valid File';
}
}
} else {
$file = '';
}

Related

trying to add upload image in my form CI MySQL

I have form for input. Input for this form is quite complicated, because one form is submitted to more than three table in database. I want to add upload image in my form, but I don't know where should I put it. here's my controller for input
function c_submit(){
$data = array(
'no_form' => $this->input->post('noform'),
'no_kon' => $this->input->post('nokon'),
'tgl_kun' => $this->input->post('tk'),
'tgl_input' => date("Y-m-d H:i:s"),
'no_lok' => $this->input->post('nolok'),
'no_obs' => $this->input->post('noobs'),
'no_koor' => $this->input->post('nokoor'),
'no_lahan' => $this->input->post('nolahan'),
't_utama' => $this->input->post('tutama'),
'pola_t' => $this->input->post('ptanam'),
'dlm_olah' => $this->input->post('kolah'),
't_tanah' => $this->input->post('ttanah'),
'no_prod' => $this->input->post('noprod'),
'np_padi' => $this->input->post('nppadi'),
'np_jagung' => $this->input->post('npjagung'),
'np_kedelai' => $this->input->post('npked'),
'np_lain' => $this->input->post('nplain'),
'catatan' => $this->input->post('cat')
);
$datakon = array(
'no_kon' => $this->input->post('nokon'),
'jabatan' => $this->input->post('jab'),
'nama' => $this->input->post('namakon'),
'telp' => $this->input->post('telp')
);
$datakoor = array(
'no_koor' => $this->input->post('nokoor'),
'utm_y' => $this->input->post('y'),
'utm_x' => $this->input->post('x')
);
$datalahan = array(
'no_lahan' => $this->input->post('nolahan'),
'jenis' => $this->input->post('jlahan'),
'penggunaan' => $this->input->post('plahan'),
'kondisi' => $this->input->post('klahan'),
'drainase' => $this->input->post('drain')
);
$dataprod = array(
'no_prod' => $this->input->post('noprod'),
'p_padi' => $this->input->post('p_padi'),
'p_jagung' => $this->input->post('p_jagung'),
'p_kedelai' => $this->input->post('p_ked'),
'pr_lain' => $this->input->post('pr_lain'),
'prod_lain' => $this->input->post('prod_lain'),
'pr_lain2' => $this->input->post('pr_lain2'),
'prod_lain2' => $this->input->post('prod_lain2')
);
$datavar = array(
'no_var' => $this->input->post('novar'),
'v_padi' => $this->input->post('v_padi'),
'v_jagung' => $this->input->post('v_jagung'),
'v_kedelai' => $this->input->post('v_ked'),
'v_lain' => $this->input->post('v_lain'),
'var_lain' => $this->input->post('var_lain'),
'v_lain2' => $this->input->post('v_lain2'),
'var_lain2' => $this->input->post('var_lain2')
);
$datalok = array(
'no_lok' => $this->input->post('nolok'),
'kabu' => $this->input->post('kabu'),
'keca' => $this->input->post('keca'),
'desa' => $this->input->post('desa'),
'desk' => $this->input->post('desk_lok')
);
$datappadi = array(
'np_padi' => $this->input->post('nppadi'),
'p_organik' => $this->input->post('padi_o'),
'p_urea' => $this->input->post('padi_u'),
'p_kcl' => $this->input->post('padi_k'),
'p_sp36' => $this->input->post('padi_s'),
'p_phonska' => $this->input->post('padi_p'),
'p_lain' => $this->input->post('pp_l'),
'pp_lain' => $this->input->post('padi_l')
);
$datapjagung = array(
'np_jagung' => $this->input->post('npjagung'),
'j_organik' => $this->input->post('jagung_o'),
'j_urea' => $this->input->post('jagung_u'),
'j_kcl' => $this->input->post('jagung_k'),
'j_sp36' => $this->input->post('jagung_s'),
'j_phonska' => $this->input->post('jagung_p'),
'j_lain' => $this->input->post('pj_l'),
'pj_lain' => $this->input->post('jagung_l')
);
$datapked = array(
'np_kedelai' => $this->input->post('npked'),
'k_organik' => $this->input->post('ked_o'),
'k_urea' => $this->input->post('ked_u'),
'k_kcl' => $this->input->post('ked_k'),
'k_sp36' => $this->input->post('ked_s'),
'k_phonska' => $this->input->post('ked_p'),
'k_lain' => $this->input->post('pk_l'),
'pk_lain' => $this->input->post('ked_l')
);
$dataplain = array(
'np_lain' => $this->input->post('nplain'),
'jenis_l' => $this->input->post('j_lain'),
'organik' => $this->input->post('lain_o'),
'urea' => $this->input->post('lain_u'),
'kcl' => $this->input->post('lain_k'),
'sp36' => $this->input->post('lain_s'),
'phonska' => $this->input->post('lain_p'),
'pupuk_lain' => $this->input->post('pl_l'),
'pem_lain' => $this->input->post('lain_l')
);
$no_obs = $this->session->userdata('no_obs');
$this->m_input->m_submit($data, $datakon, $datakoor, $datalahan, $dataprod, $datavar, $datalok, $datappadi, $datapjagung, $datapked, $dataplain);
$this->session->set_flashdata('msg', '<div class="alert alert-success"><p><b>SUKSES!</b> Data berhasil diinputkan!</p></div>');
redirect('c_read');
}
and this my model
function m_submit($data, $datakon, $datakoor, $datalahan, $dataprod, $datavar, $datalok, $datappadi, $datapjagung, $datapked, $dataplain) {
$this->db->trans_start();
$this->db->insert('koor_pen', $datakoor);
$no_koor = $this->db->insert_id();
$this->db->insert('kontak', $datakon);
$no_kon = $this->db->insert_id();
$this->db->insert('lahan', $datalahan);
$no_lahan = $this->db->insert_id();
$this->db->insert('produktivitas', $dataprod);
$no_prod = $this->db->insert_id();
$this->db->insert('varietas', $datavar);
$no_var = $this->db->insert_id();
$this->db->insert('lokasi', $datalok);
$no_lok = $this->db->insert_id();
$this->db->insert('pem_padi', $datappadi);
$np_padi = $this->db->insert_id();
$this->db->insert('pem_jagung', $datapjagung);
$np_jagung = $this->db->insert_id();
$this->db->insert('pem_kedelai', $datapked);
$np_kedelai = $this->db->insert_id();
$this->db->insert('pem_lain', $dataplain);
$np_lain = $this->db->insert_id();
$data['no_kon'] = $no_kon;
$data['no_koor'] = $no_koor;
$data['no_lahan'] = $no_lahan;
$data['no_prod'] = $no_prod;
$data['no_var'] = $no_var;
$data['no_lok'] = $no_lok;
$data['np_padi'] = $np_padi;
$data['np_jagung'] = $np_jagung;
$data['np_kedelai'] = $np_kedelai;
$data['np_lain'] = $np_lain;
$this->db->insert('input_pen', $data);
$this->db->trans_complete();
return $this->db->insert_id();
}
Link for my uploaded image should in $data array. I don't know what should I do. Can anyone give me examples?
First lets clear the code
for submit sevral forms you can easily user array in html name tag
<input name="datakon[no_kon]" >
<input name="datakon[jab]" >
<input name="datakon[namakon]" >
<input name="datakon[telp]" >
And in Controller side you insert them into database in one line
$datakon = $this->input->post('datakon');
$this->db->insert('kontak', $datakon);
$no_kon = $this->db->insert_id();
And if your database table name was same as your input fields, its done
Now lets to start uploading files
You should not Upload files in database.
instead of uploading file to database you can uplade files to a directory and save that directory address.
for uploading files you can use codeigniter upload library Codeigniter Upload File Documentation
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('no_kon'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
Hope to help
This script will upload your file in destination folder mkdir($config['upload_path'], 0777, TRUE);
Param number 3, TRUE will create recursively the directory for you.
And the corresponding line will place a name and path to database
$post_data = array(
'name' => $_FILES["__INPUT__FIELD__NAME"]['name'],
'path' => $hook
);
$this->db->insert('FILES__DB__', $post_data);
Generall usage
File_handler model
<?PHP
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class File_handler extends CI_Model {
private $base_p = "./files/";
private $ext = 'pdf|csv|doc|txt';
private $size = 5000000;
function _push_file($path, $name) {
// make sure it's a file before doing anything!
if (is_file($path)) {
// required for IE
if (ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
// get the file mime type using the file extension
$this->load->helper('file');
$mime = get_mime_by_extension($path);
// Build the headers to push out the file properly.
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
header('Cache-Control: private', false);
header('Content-Type: ' . $mime); // Add the mime type from Code igniter.
header('Content-Disposition: attachment; filename="' . basename($name) . '"'); // Add the file name
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($path)); // provide file size
header('Connection: close');
readfile($path); // push it out
exit();
}
}
public function fsize($s) {
$this->size = $s;
}
public function fext($ext) {
$this->ext = $ext;
}
public function upload_file($field, $subpath) {
if (!empty($_FILES[$field]['name'])) {
$config['upload_path'] = $this->base_p . '' . $subpath;
$config['allowed_types'] = $this->ext;
$config['max_size'] = $this->size; // 5 mb
$config['encrypt_name'] = TRUE;
if (!is_dir($config['upload_path'])) {
mkdir($config['upload_path'], 0777, TRUE);
}
$this->load->library('upload', $config);
if (!$this->upload->do_upload($field)) {
$status = 'error';
$msg = $this->upload->display_errors('', '');
return json_encode(array('result' => 'error', 'msg' => $msg));
die();
} else {
$data = $this->upload->data();
}
return $path = 'files' . $subpath . '/' . $data['file_name'];
}
}
}
Use this in your logic model
$this->load->model("File_handler", "fh");
$this->fh->fext("jpg|jpeg|pdf|png");
$hook = $this->fh->upload_file("__INPUT__FIELD__NAME", "__PATH__TO__UPLOAD");
// Errors from File_handler controller
if (isset(json_decode($hook)->result) && json_decode($hook)->result == "error") {
$message = json_decode($hook)->msg;
}
// If we got the path all is ok
if ($hook) {
$post_data = array(
'name' => $_FILES["__INPUT__FIELD__NAME"]['name'],
'path' => $hook
);
$this->db->insert('FILES__DB__', $post_data);
$fid = $this->db->insert_id();
if (!is_numeric($fid)) {
$message = "Error, file not added";
}
}
if (strlen($message) == 0) {
// No errors in the file handler
// get your upload url path with file name from $hook
}else{
echo $message;
}.
In your case :
You will need to create a table in your database use this schema
CREATE TABLE `file_uploads` (
`id` bigint(20) NOT NULL,
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`time_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`path` varchar(200) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Indexes
--
ALTER TABLE `file_uploads`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT
--
ALTER TABLE `file_uploads`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;COMMIT;
Your model
function m_submit($data, $datakon, $datakoor, $datalahan, $dataprod, $datavar, $datalok, $datappadi, $datapjagung, $datapked, $dataplain) {
$this->db->trans_start();
$this->db->insert('koor_pen', $datakoor);
$no_koor = $this->db->insert_id();
$this->db->insert('kontak', $datakon);
$no_kon = $this->db->insert_id();
$this->db->insert('lahan', $datalahan);
$no_lahan = $this->db->insert_id();
$this->db->insert('produktivitas', $dataprod);
$no_prod = $this->db->insert_id();
$this->db->insert('varietas', $datavar);
$no_var = $this->db->insert_id();
$this->db->insert('lokasi', $datalok);
$no_lok = $this->db->insert_id();
$this->db->insert('pem_padi', $datappadi);
$np_padi = $this->db->insert_id();
$this->db->insert('pem_jagung', $datapjagung);
$np_jagung = $this->db->insert_id();
$this->db->insert('pem_kedelai', $datapked);
$np_kedelai = $this->db->insert_id();
$this->db->insert('pem_lain', $dataplain);
$np_lain = $this->db->insert_id();
$data['no_kon'] = $no_kon;
$data['no_koor'] = $no_koor;
$data['no_lahan'] = $no_lahan;
$data['no_prod'] = $no_prod;
$data['no_var'] = $no_var;
$data['no_lok'] = $no_lok;
$data['np_padi'] = $np_padi;
$data['np_jagung'] = $np_jagung;
$data['np_kedelai'] = $np_kedelai;
$data['np_lain'] = $np_lain;
$this->db->insert('input_pen', $data);
/* add my image */
$this->load->model("File_handler", "fh");
$this->fh->fext("jpg|jpeg|pdf|png");
$hook = $this->fh->upload_file("__INPUT__FIELD__NAME", "__PATH__TO__UPLOAD");
// Errors from File_handler controller
if (isset(json_decode($hook)->result) && json_decode($hook)->result == "error") {
$message = json_decode($hook)->msg;
}
// If we got the path all is ok
if ($hook) {
$post_data = array(
'name' => $_FILES["foto"]['name'],
'path' => $hook
);
$this->db->insert('file_uploads', $post_data);
$fid = $this->db->insert_id();
if (!is_numeric($fid)) {
$message = "Error, file not added";
}
}
if (strlen($message) == 0) {
// No errors in the file handler
// get your upload url path with file name from $hook and do here whatever u want
} else {
echo $message;
}
$this->db->trans_complete();
return $this->db->insert_id();
}
Things to be noticed HTML
You need to have your form enctype="multipart/form-data"
<form id="FormId" name="Formname" method="post" enctype="multipart/form-data" accept-charset="utf-8">
And the input type file
<input type="file" class="form-control" name="foto" id="foto">
Code sample for jquery ajax handling
$.ajax({
url: '<?PHP echo base_url(); ?>CONTROLLER/FUNCTION',
type: "POST",
mimeType: "multipart/form-data",
contentType: false,
dataType: 'json',
cache: false,
processData: false,
data: $form.serialize(),
success: function (data) {
// Your logic
}
});

how to upload multiple image with different input file in codeigniter

I want to upload multiple image with different input file with array name.
view :
<form action="" enctype="multipart/form-data" method="post">
<input name="picture[]" class="form-control" style="padding-top: 0;" type="file"/>
<input name="picture[]" class="form-control" style="padding-top: 0;" type="file"/>
<input type='submit' value="upload" />
</form>
controller:
public function index($id=null)
{
$id = $this->input->get('id');
if ($_POST)
{
if ($this->validation())
{
$file = $this->upload_picture();
if ($file['status'] == 'success')
{
echo $this->upload->data('file_name');
}
else
{
echo $file['data'];
echo $file['status'];
$this->session->set_flashdata('alert', alert('error', $file['data']));
}
}
else
{
$this->session->set_flashdata('alert', alert('error', validation_errors()));
}
//redirect($this->agent->referrer());
}
}
private function upload_picture()
{
$config['upload_path'] = './assets/img/page/';
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['max_size'] = 125000; // 1 GB
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('picture[]'))
{
return array(
'status' => 'error',
'data' => $this->upload->display_errors()
);
}
else
{
$data = $this->upload->data();
$resize['image_library'] = 'gd2';
$resize['source_image'] = './assets/img/page/'.$data['file_name'];
$resize['maintain_ratio'] = TRUE;
// $resize['width'] = 1920;
// $resize['height'] = 1080;
$this->load->library('image_lib', $resize);
$this->image_lib->resize();
return array(
'status' => 'success',
'data' => $this->upload->data()
);
}
}
private function validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('picture[0]', 'Picture', 'trim');
$this->form_validation->set_rules('picture[1]', 'Picture', 'trim');
$this->form_validation->set_error_delimiters('', '<br>');
return $this->form_validation->run();
}
result in browser always show error that mean return status to error in upload_picture function, I want to get filename that encrypted and store to database like a4b8a0e070128b0a3dabd9e2931f7ae3.jpg not picture.jpg.
codeigniter upload class doesn't support array file name in this way. So either you have to modify upload class file (not recommended to modify core class file), or you have to modify your codes.
You can name the inputs like this: picture_1, picture_2 etc.
In that case, modify upload_picture() method like this way:
foreach($_FILES as $key=>$val){
if(!$this->upload->do_upload($key)){
$return[$key] = $this->upload->display_errors(); //store this in an array and return at the end. array structure is up to you
}else{
$return[$key] = $this->upload->data(); //store this in an array and return at the end. array structure is up to you
}
}
return $return; //
This way you are uploading files one by one using the loop. However, you have to also modify main method as now it is returning multidimensional array. I've given you just an idea...

Uploading logo using Codeigniter not working on editform

I have an editform for editing my company information. I also have a field for uploading a logo. When I click on choose file, and click Submit (the form) It stores the filename in my database as imagename.jpg for example.
I also want to add the image to the folder assets/uploads/. I tried it using the codeigniter upload class, same as I did on my other upload form, but this one does not work. I just don't know why.
Here's my editform:
<?= form_open_multipart('members/update/'.$id);?>
//other fields for editing company
<tr>
<td><?= form_label('Logo:'); ?></td>
<td><input type="file" name="logo" size="20" /></td>
</tr>
<tr>
<td><?= form_submit('submit', 'Opslaan');?> <?= form_reset('reset', 'Reset');?></td>
</tr>
</table>
<?= form_close()?>
My controller:
function update() //de update functie voor bovenstaande functie.
{
$id = $this->uri->segment(3);
$data = array(
'Bedrijfsnaam' => $this->input->post('Bedrijfsnaam'),
'Postcode' => $this->input->post('Postcode'),
'Plaats' => $this->input->post('Plaats'),
'Telefoonnummer' => $this->input->post('Telefoonnummer'),
'Email' => $this->input->post('Email'),
'Website' => $this->input->post('Website'),
'Profiel' => $this->input->post('Profiel'),
'Adres' => $this->input->post('Adres'),
);
if($this->input->post('logo')) { $data['logo'] = $this->input->post('logo'); }
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '';
$config['max_height'] = '';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
}
$this->members_model->updatebedrijf($id, $data);
$b = $this->session->userdata('idbedrijven');
redirect("members/$b");
}
function updatebedrijf($id, $data)
{
foreach($this->input->post('categorieen') as $cat){
$this->db->where('idbedrijven', $id);
$this->db->update('bedrijven', $data);
$to_bedrijfcategorieen2['idcategorieen'] = $this->input->post('categorieen');
$this->insert_bedrijfcat1($to_bedrijfcategorieen2);
};
}
My model:
function updatebedrijf($id, $data)
{
foreach($this->input->post('categorieen') as $cat){
$this->db->where('idbedrijven', $id);
$this->db->update('bedrijven', $data);
$to_bedrijfcategorieen2['idcategorieen'] = $this->input->post('categorieen');
$this->insert_bedrijfcat1($to_bedrijfcategorieen2);
};
}
It just does not upload. The path is the same as my other uploadfunction. that one works fine.
You have not set field name in the do_upload function
if ( ! $this->upload->do_upload("logo"))
{
$error = array('error' => $this->upload->display_errors());
}else{
$image_data = $this->upload->data();
}
And there is one thing wrong you have a if check for logo field and you are trying to get in post why ?? it should be
if($_FILES['logo']['name'] != '') { $data['logo'] = $_FILES['logo']['name']; }
if ( ! $this->upload->do_upload(?))
You should set file name as argument to upload function, since it is not default 'userfile'?
Not any of the solutions woked. This the way that I came up with.
if ($_FILES['userfile']['name'] != null) {
// upload configuration
$upload_config = array(
'upload_path' => './assets/uploads/',
'allowed_types' => 'jpeg|jpg|png',
'max_size' => 1048576,
'max_width' => 10240,
'max_height' => 7680,
'encrypt_name' => TRUE
);
// load upload library config
$this->load->library('upload', $upload_config);
if (!$this->upload->do_upload()) {
// assign upload errors
$data['upload_errors'] = $this->upload->display_errors();
// load page title
$page['title'] = "Edit Parent";
// fetch parent information
$this->db->select('Database Query');
// info data in row
$data['info'] = $this->db->get()->row();
// load view with page title
$this->load->view('temp/header', $page);
$this->load->view('editParents', $data);
$this->load->view('temp/footer');
} else {
$upload_photo = $this->upload->data();
// profile image
$parent_photo = $upload_photo['file_name'];
}
} else {
// profile image
$parent_photo = $this->input->post('profile_image');
}

Multiple file upload codeigniter not working

I have a form where multiple files can be uplaoded, along with a name field and a date field. The user can clone the inputs and upload as many certificates as they need. My HTML is below:
HTML:
<input type="file" name="certificate[]" />
<input type="text" name="certificate_name[]" class="right" />
<input type="text" name="expiry_date[]" />
I can upload the files one at a time but as multiple uploads it doesn't work, I get an error
A PHP Error was encountered
Severity: Warning
Message: is_uploaded_file() expects parameter 1 to be string, array given
Filename: libraries/Upload.php
Line Number: 161
PHP:
$uid = 1;
if(isset($_FILES['certificate']))
{
$this->uploadcertificate($uid, $this->input->post('certificate_name'), $this->input->post('expiry_date'));
}
function uploadcertificate($uid, $certificate, $expiry_date)
{
$status = "";
$msg = "";
$file_element_name = 'certificate';
$certificate_name = $certificate;
if ($status != "error")
{
$config['upload_path'] = './certificate_files/';
$config['allowed_types'] = 'pdf|doc|docx|txt|png|gif|jpg|jpeg|';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors();
}
else
{
$data = $this->upload->data();
$file_id = $this->saveCertificate($uid, $data['raw_name'], $data['file_ext'], $certificate_name, $expiry_date);
}
if($file_id)
{
$status = "success";
$msg = "File successfully uploaded";
}
else
{
//unlink($data['full_path']);
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
function saveCertificate($uid, $file_name, $file_ext, $certificate_name, $expiry_date)
{
for ($ix=0; $ix<count($_FILES['certificate']); $ix++)
{
$insert_certificates = array(
'user_ID' => $uid,
'certificate' => $_POST['certificate_name'][$ix],
'certificate_name' => $_POST['child_dob_additional'][$ix],
'expiry_date' => $_POST['expiry_date'][$ix]
);
$insert = $this->db->insert('certificates', $insert_certificates);
//return $insert; //you cant return here. must let the loop complete.
$insert_certificates_history = array(
'user_ID' => $uid,
'certificate' => $_POST['certificate_name'][$ix],
'certificate_name' => $_POST['child_dob_additional'][$ix],
'expiry_date' => $_POST['expiry_date'][$ix]
);
$insert = $this->db->insert('certificates_history', $insert_certificates_history);
}
}
I'm confused as to exactly where I have went wrong. Can anyone point me in the right direction. Many thanks in advance!

ajaxFileUpload used in codeigniter - success function not executed

Good day to you all,
I am using ajaxFileUpload as below
$('#upload_file').submit(function(e) {
e.preventDefault();
$.ajaxFileUpload({
url :"http://localhost/CodeIgniter_Registration/index.php/application_form/file_upload",
fileElementId :'userfile',
dataType : 'json',
data : {
'name' : $('#document_name').val()
},
success : function (data, status)
{
alert(data.msg);
}
});
return false;
});
at the controller, the file is uploaded, and the data to be returned is also present
which is returned as
echo json_encode(array('status' => $status, 'msg' => $msg));
from the controller
function file_upload() {
$status = "";
$msg = "";
$file_element_name = 'userfile';
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png|doc|docx|pdf',
'upload_path' => $this->gallery_path,
'max_size' => 2000,
'file_name' => $filename
);
$this->load->library('upload', $config);
$test_upload = $this->upload->do_upload($file_element_name);
if (!$test_upload)
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else
{
$data = $this->upload->data();
//$file_id = $this->files_model->insert_file($data['file_name'], $_POST['title']);
if(1)
{
$status = "success";
$msg = "File successfully uploaded";
}
else
{
unlink($data['full_path']);
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
#unlink($_FILES[$file_element_name]);
echo json_encode(array('status' => $status, 'msg' => $msg));
}
But, the "success" callback never seems to be called, and no alert message is generated.
I have also tried returning some plain text. still nothing. hence, i don't think it is an issue with the json.
please suggest, what the issue can be!!

Categories