I am working on a cms for properties/ads in oop php for learning purposes. I am trying to upload multiple photos that are connected through pivot table with specific property but I am having trouble inserting those photos. I need when I insert property with two or more photos that those photos have diiferent ids in pivot table but the same id for property. I succeeded with one photo at the time, but with multiple I get errors:
Warning: explode() expects parameter 2 to be string, array given in
C:\xampp\htdocs\App\Models\Ad.php on line 177 when I var dump $tmp
variable I get null and
Warning: end() expects parameter 1 to be array, null given in
C:\xampp\htdocs\App\Models\Ad.php on line 179 when I var dump
$file_ext variable I get empty string
I am using three tables to do that. photos (name, extension, created_at, updated_at), property_photo (property_id, photo_id), properties (title, description, type_of_property, use_of_the_property, quadrature, location...). Here is my code:
Ad Model:
public function createAd($data, $pht)
{
if (isset($data['photoExtension'])) {
$this->photoExtension = preg_replace('~(?<=a)\w~', "", $data['photoExtension']);
}
$this->photoExtension = strtolower(strrchr( $pht, '.' ));
$this->db->query("INSERT INTO properties (title, description, type_of_property, use_of_the_property, quadrature, location, price, sales_clerk_info, booked, type_of_market, type_of_payment, status) VALUES (:title, :description, :type_of_property, :use_of_the_property, :quadrature, :location, :price, :sales_clerk_info, :booked, :type_of_market, :type_of_payment, :status) ");
$this->db->bind(':title', $data['title']);
$this->db->bind(':description', $data['description']);
$this->db->bind(':type_of_property', $data['type_of_property']);
$this->db->bind(':use_of_the_property', $data['use_of_the_property']);
$this->db->bind(':quadrature', $data['quadrature']);
$this->db->bind(':location', $data['location']);
$this->db->bind(':price', $data['price']);
$this->db->bind(':sales_clerk_info', $data['sales_clerk_info']);
$this->db->bind(':booked', $data['booked']);
$this->db->bind(':type_of_market', $data['type_of_market']);
$this->db->bind(':type_of_payment', $data['type_of_payment']);
$this->db->bind(':status','1');
$this->db->execute();
$property_last_id = $this->db->lastId();
$this->db->query('INSERT INTO photos (name, extension) VALUES (:name, :extension)');
$this->db->bind(':name', $pht);
$this->db->bind(':extension', $this->photoExtension, PDO::PARAM_STR );
$this->db->execute();
$photo_last_id = $this->db->lastId();
$this->db->query('INSERT INTO property_photo (property_id, photo_id) VALUES (:property_id, :photo_id)');
$this->db->bind(':property_id', $property_last_id);
$this->db->bind(':photo_id', $photo_last_id);
$this->db->execute();
return true;
}
public function photoValidate($file)
{
if (!empty($file['name'])) {
$file_name = $file['name'];
$file_size = $file['size'];
$file_tmp = $file['tmp_name'];
$file_type = $file['type'];
$file_error = $file['error'];
$random = sha1(microtime());
$tmp = explode('.', $file_name);
$new_photo_name = $random . '.' . $tmp[1];
$file_ext = strtolower(end($tmp));
//var_dump($tmp); null
//var_dump($file_ext); empty string
$photo_validate = '';
$extensions = ["jpeg", "jpg", "png"];
if (in_array($file_ext, $extensions) === false) {
return 'extension not allowed, please choose a JPEG or PNG file.';
} else {
if ($file_size > 2097152 || $file_error === 1) {
return 'File size must be less than 2 MB';
} else {
$value = true;
return $data = [$value, $file_tmp, $new_photo_name];
}
}
} else {
return false;
}
}
Ads Controller:
public function createAction()
{
$userinfo = $this->Auth->Auth(array('admin', 'moderator'));
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$data = [
'title' => trim($_POST['title']),
'description' => trim($_POST['description']),
'type_of_property' => trim($_POST['type_of_property']),
'use_of_the_property' => trim($_POST['use_of_the_property']),
'quadrature' => trim($_POST['quadrature']),
'location' => trim($_POST['location']),
'price' => trim($_POST['price']),
'sales_clerk_info' => trim($_POST['sales_clerk_info']),
'booked' => trim($_POST['booked']),
'type_of_market' => trim($_POST['type_of_market']),
'type_of_payment' => trim($_POST['type_of_payment']),
'title_err' => '',
'description_err' => '',
'type_of_property_err' => '',
'use_of_the_property_err' => '',
'quadrature_err' => '',
'location_err' => '',
'price_err' => '',
'sales_clerk_info_err' => '',
'booked_err' => '',
'type_of_market_err' => '',
'type_of_payment_err' => ''
];
if (empty($data['title'])) {
$data['title_err'] = 'Please enter your title!!!';
}
if (empty($data['description'])) {
$data['description_err'] = 'Please enter your description!!!';
}
if (empty($data['type_of_property'])) {
$data['type_of_property_err'] = 'Please select your type!!!';
}
if (empty($data['use_of_the_property'])) {
$data['use_of_the_property_err'] = 'Please enter use of the property!!!';
}
if (empty($data['quadrature'])) {
$data['quadrature_err'] = 'Please enter your quadrature!!!';
}
if (empty($data['location'])) {
$data['location_err'] = 'Please enter your location!!!';
}
if (empty($data['price'])) {
$data['price_err'] = 'Please enter your price!!!';
}
if (empty($data['sales_clerk_info'])) {
$data['sales_clerk_info_err'] = 'Please enter your info!!!';
}
if (empty($data['booked'])) {
$data['booked_err'] = 'Please select!!!';
}
if (empty($data['type_of_market'])) {
$data['type_of_market_err'] = 'Please select your type of market!!!';
}
if (empty($data['type_of_payment'])) {
$data['type_of_payment_err'] = 'Please select your type of payment!!!';
}
$photo_validate = $this->AdModel->photoValidate($_FILES['photo']);
if (empty($data['title_err']) && empty($data['description_err']) && empty($data['type_of_property_err']) && empty($data['use_of_the_property_err']) && empty($data['quadrature_err']) && empty($data['location_err']) && empty($data['price_err']) && empty($data['sales_clerk_info_err']) && empty($data['booked_err']) && empty($data['type_of_market_err']) && empty($data['type_of_payment_err']) && $photo_validate[0] === true) {
move_uploaded_file($photo_validate[1],"public/photos/".$photo_validate[2]);
if ($this->AdModel->createAd($data, $photo_validate[2])) {
redirect('ads/index');
} else {
if ($photo_validate === false) {
$photo_validate='Please select image';
} else {
if ($photo_validate[0] === true) {
$photo_validate='';
}
}
$data=[
'photo_validate'=>$photo_validate
];
die('Something went wrong!');
}
} else {
$this->view->render('ads/create', $data, $userinfo);
}
} else {
$data = [
'photo_validate'=>'',
'title' => '',
'description' => '',
'type_of_property' => '',
'use_of_the_property' => '',
'quadrature' => '',
'location' => '',
'price' => '',
'sales_clerk_info' => '',
'booked' => '',
'type_of_market_id' => '',
'type_of_payment' => '',
'title_err' => '',
'description_err' => '',
'type_of_property_err' => '',
'use_of_the_property_err' => '',
'quadrature_err' => '',
'location_err' => '',
'price_err' => '',
'sales_clerk_info_err' => '',
'booked_err' => '',
'type_of_market_err' => '',
'type_of_payment_err' => ''
];
$this->view->render('ads/create', $data, $userinfo);
}
}
create.php
<form action="/ads/create" method="POST" enctype="multipart/form-data">
<div class="form-group row">
<div class="col-sm-12">
<h5>Upload property image</h6>
<input type="file" name="photo[]" multiple class="form-control form-control-lg"/>
</div>
/div>
<div class="form-group">
<button type="submit" name="submit" class="form-control btn btn-primary">Submit</button>
</div>
</form>
Any help would be greatly appreciated.
Take a look at array format of $_FILES for multiple files inserting. This answer and this php documentation page will be useful for you.
You expected string in photoValidate() $file['name'] but there was an array, so you got an error.
The best and the simplest way is to use something like symfony http-foundation component.
Controller:
public function createAction()
{
$request = Request::createFromGlobals();
//...
$photo_validate = $this->AdModel->photoValidate($request->files->get('photo'));
//...
}
Also, this kind of validation is pretty messy. You can also use symfony validator component.
Related
When I update the database, it uploads a single image. How do I upload multiple?
$id = $this->request->getPost('id');
$model = new UrunModel();
$file = $this->request->getFile('resim');
$resim_eski = $model->find($id);
if($file->isValid() && !$file->hasMoved()){
$eski_resim = $resim_eski['resim'];
if(file_exists("dosyalar/uploads".$eski_resim)){
unlink("dosyalar/uploads".$eski_resim);
}
$imagename = $file->getRandomName();
$file->move("dosyalar/uploads", $imagename);
}else{
$imagename = $resim_eski['resim'];
}
if ($this->request->getFileMultiple('images')) {
foreach($this->request->getFileMultiple('images') as $res)
{
$res->move(WRITEPATH . 'dosyalar/uploads');
$data=[
'baslik' => $this->request->getPost('baslik'),
'slug' => mb_url_title($this->request->getPost('baslik'), '-', TRUE),
'kisa_aciklama' => $this->request->getPost('kisa_aciklama'),
'kategori' => $this->request->getPost('kategori'),
'query_kategori' => $this->request->getPost('query_kategori'),
'aciklama' => $this->request->getPost('aciklama'),
'fiyat' => $this->request->getPost('fiyat'),
'indirimli_fiyat' => $this->request->getPost('indirimli_fiyat'),
'resim' => $imagename,
'resimler' => $res->getClientName(),
'type' => $res->getClientMimeType()
];
$model -> update($id,$data);
}
}
return redirect()->to(base_url('yonetim/urunler'));
}
Controller code above, I've been struggling for 2 days, I couldn't manage it somehow.
When I run the code, it just adds 1 image to each product. I want to add more than one image to 1 product for the gallery part. Any suggestions for this code or a different solution?
function add()
{
$length = count($_FILES['image']['name']);
$filename = $_FILES['image']['name'];
$tempname = $_FILES['image']['tmp_name'];
$allimage = array();
foreach($filename as $key =>$value)
{
move_uploaded_file($tempname[$key],'media/uploads/mobile_product/'.$filename[$key]);
$allimage[] = $filename[$key];
}
if(!empty($allimage))
{
$allimage = json_encode($allimage);
}
else
{
$allimage = '';
}
$data['image'] = $allimage;
$this->db->insert('table',$data);
}
CI4 Controller:
if($this->request->getFileMultiple('image_files')) {
$files = $this->request->getFileMultiple('image_files');
foreach ($files as $file) {
if ($file->isValid() && ! $file->hasMoved())
{
$newNames = $file->getRandomName();
$imageFiles = array(
'filename' => $newNames
);
$modelName->insert($imageFiles );
$file->move('uploads/', $newNames);
}
}
}
HTML
<input type="file" name="image_files[]">
This is the shortest way to do that
I have a simple question that needs to get an element when selecting that reference ID by an input form. I used the following code to do that.
$id2=$locationProducts[0]->inventory_update_stock_details_id;
But this code outs only the first element always. AS an exmple inventory_update_stock_details_id=36, inventory_update_stock_details_id=36, inventory_update_stock_details_id=36 and so on.
But I needs to select as inventory_update_stock_details_id=35, inventory_update_stock_details_id=345, inventory_update_stock_details_id=2 like that.
inventory_update_stock_details_id included ids as 1,2,3,4,5,......1000
The model as follows :
function getInventoryLocationProducts()
{
$this->db->select("*");
$this->db->from('store_inventory_update_stock_details');
$this->db->join('store_inventory_item', 'store_inventory_item.inventory_item_id=store_inventory_update_stock_details.inventory','left');
$this->db->join('store_inventory_location_update', 'store_inventory_location_update.inventory_update_stock_id=store_inventory_update_stock_details.inventory_update_stock_id','left');
$this->db->join('store_inventory_update_stock', 'store_inventory_update_stock.inventory_update_stock_id=store_inventory_location_update.inventory_update_stock_id','left');
$this->db->where('store_inventory_item.status=1');
$this->db->where('store_inventory_update_stock_details.serial_no NOT IN (select serial_no from store_inventory_location_update)');
$q = $this->db->get_where();
if ($q->num_rows() > 0) {
return $q->result();
}
return FALSE;
}
Controller
public function addInventoryLocation()
{
$this->checkPermissions('add', 'inventoryLocation');
$bc = array(array('link' => '#', 'page' => 'Inventory Locations'));
$meta = array('page_title' => 'Inventory Locations', 'bc' => $bc);
$this->data['branch'] = $this->Item_model->getBranch();
$this->data['office'] = $this->Item_model->getOffice();
$locationProducts = $this->Item_model->getInventoryLocationProducts();
$this->data['locationProducts'] = $locationProducts;
$this->data['auto_loc_no'] = $this->Item_model->generate_inv_loc_ref();
$count = $this->input->post('i');
$str = $this->input->post('auto_loc_no');
$auto_loc = preg_replace("/[^0-9]{1,4}/", '', $str);
$this->form_validation->set_rules('branch', 'Branch', 'required');
if ($this->form_validation->run() == true) {
$stock = array(
'office_id' => $this->input->post('office'),
'branch' => $this->input->post('branch'),
'l_date' => $this->input->post('l_date'),
'is_order_no' => $this->input->post('is_order_no'),
'loc_no' => $this->input->post('auto_loc_no'),
'auto_loc_no' => $auto_loc,
'user' => ucfirst($this->session->userdata('name')),
'order_status' => 'locate',
'status' => 1
);
$id = $this->Item_model->addInventoryLocation($stock);
}
$id2=$locationProducts[0]->inventory_update_stock_details_id;
dd($id2);
if ($this->form_validation->run() == true && $id2 != 0) {
$count = $this->input->post('i');
for ($x = 0; $x <= $count; $x++) {
$details[$x]['inventory_update_stock_id'] = $id2;
$details[$x]['inventory'] = $this->input->post('inventory' . $x);
$details[$x]['serial_no'] = $this->input->post('serial_no' . $x);
$details[$x]['item_code'] = $this->input->post('item_code' . $x);
$details[$x]['officer'] = $this->input->post('officer' . $x);
$details[$x]['qty'] = 1;
$details[$x]['status'] = 1;
$details[$x]['branch'] = $this->input->post('branch');
}
if ($this->Item_model->addInventoryLocationDetails($details)) {
echo("<meta http-equiv='refresh' content='1'>");
$this->session->set_flashdata('message', 'Successfully Added ..!!');
redirect('item/addInventoryLocation');
}
} else {
$this->session->set_flashdata('error', validation_errors());
$this->render('item/addInventoryLocation', $meta, $this->data);
}
}
View
<td style="width: 30%">
<input type="hidden" name="i" id="i" value="0">
<select name="inventory0" id="inventory0" class="form-control select2 inventory-select" required>
<option value=""></option>
<?php
if (!empty($locationProducts)) {
foreach ($locationProducts as $row) {
echo "<option value='".$row->inventory_update_stock_details_id."'> $row->inventory_update_stock_details_id - $row->inventory_item_name</option>";
?>
<?php
}
}
?>
</select>
</td>
What can modify my code line to do that. Can anyone help me ?
I'm not entirely sure what the intended logic is, but I think what you want is to add the InventoryLocationDetails to all InventoryLocationProducts.
If that is correct, you could perhaps do something like this:
if ($this->form_validation->run() == true) {
$details = [];
foreach ($locationProducts as $locationProduct) {
$id2 = $locationProduct->inventory_update_stock_details_id;
$count = $this->input->post('i');
for ($x = 0; $x <= $count; $x++) {
$details[] = [
'inventory_update_stock_id' => $id2,
'inventory' => $this->input->post('inventory' . $x),
'serial_no' => $this->input->post('serial_no' . $x),
'item_code' => $this->input->post('item_code' . $x),
'officer' => $this->input->post('officer' . $x);
'qty' => 1,
'status' => 1,
'branch' => $this->input->post('branch'),
];
}
}
if ($this->Item_model->addInventoryLocationDetails($details)) {
echo("<meta http-equiv='refresh' content='1'>");
$this->session->set_flashdata('message', 'Successfully Added ..!!');
redirect('item/addInventoryLocation');
}
}
This assumes that $locationProducts contains only those products that actually need to be updated. If you need to only update some of them, you can add the logic to determine which product to update inside the foreach loop.
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
}
});
I need help in fixing an issue in which I am using laravel 'in' validator to match a given input against multiple comma separated string of values. Now the issue is when there is a number in the input and it does not matches with any of the comma separated values then it gives an exception:
preg_match() expects parameter 2 to be string, array given
However it should simply give error message in validator object that input field does not match. instead it gives above mentioned exception. Following is my code:
if (!empty($program)) {
$institution_id = $program->InstitutionId;
$roster_users = $program->usersRosters()->where('ProfileType', 'Student')->get();
if (!empty($roster_users)) {
$rostered_users_ids = implode(',', $roster_users->lists('id'));
}
if (!empty($roster_users)) {
$rostered_users_usernames = implode(',', $roster_users->lists('UserName'));
}
$teacher_roster_users = $program->usersRosters()->where('ProfileType', 'External Staff')->get();
if (!empty($teacher_roster_users)) {
$teacher_rostered_users_usernames = implode(',', $teacher_roster_users->lists('UserName'));
}
if (!empty($teacher_roster_users)) {
$teacher_rostered_users_data = $teacher_roster_users->lists('id', 'UserName');
}
}
$rules = [
'aasectionname.required' => '501 – AA section does not exist',
'aaid' => 'numeric|exists:users,id|in:' . $rostered_users_ids . '|aaidinstitutionmismatch:' . $institution_id,
'institutionid' => 'numeric|in:' . $institution_id,
'username' => 'exists:users,UserName|in:' . $rostered_users_usernames . '|usernameinstitutionmismatch:' . $institution_id,
'schoolid' => 'numeric',
'groupowner' => 'in:'.$teacher_rostered_users_usernames,
'remove' => 'in:0,1'
];
$messages = [
// InstitutionId
'institutionid.numeric' => '101 – Invalid Institution ID',
'institutionid.in' => '102 – Institution ID does not match Program',
// Usernames
'username.exists' => '201 – UserName does not exist',
'username.in' => '202 – UserName is not rostered to this program',
'username.usernameinstitutionmismatch' => '203 – User/Institution Mismatch - UserName is not assigned to this Institution',
// AAId
'aaid.numeric' => '301 – AA ID does not exist',
'aaid.exists' => '301 – AA ID does not exist',
'aaid.in' => '302 – AA ID is not rostered to this program',
'aaid.aaidinstitutionmismatch' => '303 – AA ID/Institution Mismatch – AAID is not assigned to this Institution',
// Mismatch
'bothmismatch' => '401 – AAID/UserName/SchoolID do not match (This is a combination of at least 2 of these items)',
// Teacher
'groupowner.in' => '501 – GroupOwner does not exist',
// Remove
'remove' => '601 – No Student record match to remove',
];
Excel::load($file, function($excel) use($program, $rules, $messages, $errors, &$errors_data, $teacher_rostered_users_data) {
global $totalmismatch;
$results = $excel->get();
$program_group_model = new ProgramGroup;
$option_model = new Option;
$group_default_status_id = key($option_model->getProgramsStatus(['Active']));
$groupVisibilityStatusId = $group_type = $option_model->getVisibilityOptions('Question Visibility','Private');
$data = [];
$lastSecId = null;
$groupSectionPreviousName = null;
$groupname = null;
$data['status'] = $group_default_status_id;
$data['program_id'] = $program->Id;
$groupname_lists = $program_group_model->with(['programs' => function ($query) use ($program){
$query->where('ProgramId','=',$program->Id);
}])->get()->lists('Name','Id');
foreach ($results as $key => $row) {
$inputs = $row->toArray();
$groupname = trim($inputs['usergroup']);
$errors = [];
// Stop reading the excel when aasectionname is empty
if (empty($groupname) || $groupname == null) {
$errors['remove'] = $messages['aasectionname.required'];
}
$validator = Validator::make($inputs, $rules, $messages);
if ($validator->fails()) {
$errors = $validator->messages()->toArray();
foreach ($errors as $error) {
foreach ($error as $e) {
$errors_data[] = [$key + 2, $e];
}
}
} else {
$aaid = intval($inputs['aaid']);
$groupowner_name = $inputs['groupowner'];
if (!empty($teacher_rostered_users_data[$groupowner_name])) {
$groupowner_id = $teacher_rostered_users_data[$groupowner_name];
$data['owner'] = $groupowner_id;
}
$remove = intval($inputs['remove']);
// Remove existing Student Roster
if (!empty($remove)) {
$removed = false;
$user_ids = is_array($aaid) ? $aaid : [$aaid];
$program_group = $program->programGroups()->where('Name', $groupname);
if (!empty($program_group)) {
$program_group = $program_group->first();
}
if (!empty($program_group)) {
$program_group = $program_group->users();
}
if (!empty($program_group) && !empty($user_ids)) {
$removed = $program_group->detach($user_ids);
}
if (!$removed) {
$errors['remove'] = $messages['remove'];
}
} else {
if (!in_array($groupname, $groupname_lists) || $groupSectionPreviousName != $groupname) {
$data['name'] = $groupname;
$data['group_id'] = array_search($groupname, $groupname_lists);
$data['group_type'] = $groupVisibilityStatusId;
$sectionId = $program_group_model->saveProgramGroup($data);
$data[$sectionId]['selected'][] = $aaid;
$groupname_lists[$sectionId] = $groupname;
} else {
$temp = array_flip($groupname_lists);
$data[$temp[$groupname]]['selected'][] = $aaid;
}
}
if ($totalmismatch === 2) {
$errors['bothmismatch'] = $messages['bothmismatch'];
}
foreach ($errors as $error) {
$errors_data[] = [$key + 2, $error];
}
}
$groupSectionPreviousName = $groupname;
}
$programAASectionModelForSectionUsers = new ProgramSectionUser();
$programAASectionModelForSectionUsers->saveProgramGroupUsers($data);
});
$rules
array:7 [
"aasectionname.required" => "501 – AA section does not exist"
"aaid" => "numeric|exists:users,id|in:28,29,32,33,25,24,27|aaidinstitutionmismatch:42"
"institutionid" => "numeric|in:42"
"username" => "exists:users,UserName|in:Kabeer,Ayaz,fddesaaweqq,fdawerascvdfc,haseeb,kamran,shahid|usernameinstitutionmismatch:42"
"schoolid" => "numeric"
"groupowner" => "in:externalstaff,rahat,uzma,sahar,haseebahmad,saimariaz,fredrick"
"remove" => "in:0,1"
]
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!