Multiple file upload codeigniter not working - php

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!

Related

I want stored image delete when Updated with new image

I am new to codeigniter and I am having problem in edit item image, not that it don't get update as it do but there are too many images in the upload folder directory.
What I want to do is I want the previously stored image to be deleted in the upload directory when I update new image.
Here is my controller:
function edit($shop_id = null){
if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin())
{
redirect('auth', 'refresh');
}
/* Breadcrumbs */
$this->data['breadcrumb'] = $this->breadcrumbs->show();
/* Variables */
$tables = $this->config->item('tables', 'ion_auth');
$this->data['shop_id'] = $shop_id;
/* Get all category */
$this->data['shopInfo'] = $this->shop_model->getShopInfo($shop_id);
//echo "<pre>";print_r( $this->data['shopInfo']);echo "</pre>";exit;
/* Validate form input */
$this->form_validation->set_rules('shop_name', 'Shop Name', 'trim|required');
$this->form_validation->set_rules('shop_latidude', 'Shop Latidude', 'trim|required');
$this->form_validation->set_rules('shop_longitude', 'Shop Longitude', 'trim|required');
if($this->form_validation->run() == true) {
$config['upload_path'] = './assets/uploads/shop/';
//die(var_dump(is_dir($config['upload_path'])));
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$img = "logo";
$img_upload = $this->upload->do_upload($img);
$data = $this->upload->data();
$file = array('file_name' => $data['file_name'] );
$data = array('upload_data' => $this->upload->data());
$photo = base_url().'assets/uploads/shop/'.$file['file_name'];
if($img_upload == 1 ) $post_photo = $photo;
else $post_photo = $this->input->post('hidden_photo');
if($this->input->post('status')){
$status = 1;
}else{
$status = 0;
}
$shopInfo = array(
'shop_name' => $this->input->post('shop_name'),
'merchant_id' => $this->input->post('merchant_id'),
'photo' => $post_photo,
'description' => $this->input->post('shop_desc'),
'registered_date'=> date('Y-m-d H:i:s'),
'is_active' => 1,
'shop_location' => $this->input->post('shop_loc'),
'shop_address' => $this->input->post('shop_add'),
'shop_phone' => $this->input->post('shop_ph'),
'shop_latitude' => $this->input->post('shop_latidude'),
'shop_longitude'=> $this->input->post('shop_longitude'),
'open_hour' => $this->input->post('open_hour'),
'close_hour' => $this->input->post('close_hour'),
'remark' => $this->input->post('remark'),
'approved' => $status
);
$this->shop_model->shopUpdate($shop_id, $shopInfo);
redirect(base_url() . 'admin/shop', 'refresh');
} else {
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
/* Load Template */
$this->data['merchant'] = $this->merchant_model->getAllMerchants();
$this->template->admin_render("admin/shop/edit", $this->data);
}
}
Here is my Model:
function shopUpdate($shop_id, $shopInfo) {
$this->db->where('shop_id', $shop_id);
if($shopInfo) {
$query = $this->db->update('shop', $shopInfo);
if ($query) {
return true;
} else {
return false;
}
} else {
return false;
}
}
function shopUpdate($shop_id, $shopInfo) {
$q = $this->db->select('photo')->where('shop_id', $shop_id)->get('shop');
if ($q->num_rows() > 0) {
$imgName = $q->row();
// image path must be './admin/shop'
unlink("./{image pathe}/".$imgName);
}
$this->db->where('shop_id', $shop_id);
if($shopInfo) {
$query = $this->db->update('shop', $shopInfo);
if ($query) {
return true;
} else {
return false;
}
} else {
return false;
}
}
you got file name when image got uploaded so get the file name where you are going to update and delete file first. Use unlink to delete file. run update query.
you just need to change in model for updating and deleting at same time.
First, check if new image uploading or not
$new_image = $_FILES['userfile']['name'] ? $_FILES['userfile']['name'] : '';
if($new_image != ''){
$old_image = $this->shop_model->getOlgImage($shop_id);
if(isset($old_image) && file_exists('image-path/photo.jpg')){
unlink('image-path/image');
}
}
Old image is now deleted. Upload new
$config['upload_path'] = './assets/uploads/shop/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$img = "logo";
Give name of your input type file name to $this->upload->do_upload() not variable
No need to add $this->upload->data() twice
if($this->upload->do_upload('userfile')){
$data = $this->upload->data();
$photo = base_url().'assets/uploads/shop/'.$data['file_name'];
$post_photo = $photo;
} else $post_photo = $this->input->post('hidden_photo');
if($this->input->post('status')){
$status = 1;
}else{
$status = 0;
}
Get old image
public function getOldImage($shop_id){
return $this->db->get_where('shop', ['shop_id' => $shop_id])->row()->photo;
}
First, you need to get image name from the database by ID then update record. Once the record is updated then you can delete that image the folder directory.
function shopUpdate($shop_id, $shopInfo) {
//fetch image name from the database by shop_id
$imageName = $this->db->select('photo')->where('shop_id', $shop_id)->get('shop');
$this->db->where('shop_id', $shop_id);
if($shopInfo) {
$query = $this->db->update('shop', $shopInfo);
if ($query) {
//record is updated successfully now delete that image from folder
if ($imageName->num_rows() > 0) {
unlink("./{image pathe}/".$imageName->row());
}
return true;
} else {
return false;
}
} else {
return false;
}
}
unlink()

How to remove this error: The filetype you are attempting to upload is not allowed

public function addAppdetails()
{ $dev_id = $this->sessionStart();
$this->load->library('form_validation');
$this->form_validation->set_rules('appname', 'App Name', 'required');
$this->form_validation->set_rules('platform', 'Platform', 'required');
//$this->form_validation->set_rules('category','App Category','required');
$this->form_validation->set_rules('description', 'App Description', 'required');
//$this->form_validation->set_rules('app_pic','App Pic','required');
//$this->form_validation->set_rules('file','App File','required');
if ($this->form_validation->run())
{
$appname = $this->input->post('appname');
$platform = $this->input->post('platform');
$category1 = $this->input->post('category');
$descripton = $this->input->post('description');
$category = implode(",", $category1);
echo "l";
$data1=$this->appFileupload();
echo "Break";
$data2=$this->appImageupload();
die;
foreach ($data1 as $dataArray)
{
$fileName=$dataArray['file_name'];
}
foreach ($data2 as $dataArray)
{
$imageName=$dataArray['file_name'];
}
$data = array('name' => $appname, 'platform' => $platform, 'description' => $descripton, 'category' => $category,'file_name'=>$fileName,'image_name'=>$imageName,'dev_id'=>$dev_id);
$this->Dev_model->addApp($data);
//$this->appImageupload();
echo "yolo";
}
else
{
$data['dataArray'] = $this->sessionStart();
$category = $this->input->post('category');
print_r($category);
$this->load->view('dev/addApp', $data);
}
}
public function appFileupload()
{
$config1['upload_path'] = './uploads/files';
$config1['allowed_types'] = 'apk|exe';
$this->load->library('upload', $config1);
if ( ! $this->upload->appFileUpload('file'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
public function appImageupload()
{
$config2['upload_path'] = './uploads/appImages';
$config2['allowed_types'] = 'gif|jpg|png';
$config2['max_size'] = 1000000000;
$config2['max_width'] = 10240000;
$config2['max_height'] = 76800000;
$this->load->library('upload', $config2);
if ( ! $this->upload->appImageUpload('app_pic'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
The output is as follows:
lBreak
Array ( [error] =>
The filetype you are attempting to upload is not allowed.
)
So, if I exchange the positions of appFileupload() and appImageupload() then it will give the same error for 'apk|exe' file and right now it is giving the error for appImageupload(). If you will ask how do I know about this? Then the answer is, I have checked their folder one gets uploaded but not the other.
CodeIgniter version is: 3.x
Add * in place of another type.
$config['allowed_types'] = '*';
I am just suggesting this for test purpose
Edit:
I am not sure but this will be helpful.
You could try looking at system/libraries/Upload.php line 199:
$this->_file_mime_type($_FILES[$field]);
Change that line to:
$this->_file_mime_type($_FILES[$field]); var_dump($this->file_type); die();
Well Lol, I'm answering my own question.
First, loading the library again with $config2 won't work because the library is already loaded once and $config1 will stay loaded. To load a new config use:
$this->upload->initialize($config2);

CodeIgniter - resizing images causes "out of memory"

I wrote a utility (w/CodeIgniter 3.0.5) for a client that allows him to upload photos, and they're resized for the web. The script has been working fine for several months, but all of a sudden he's getting out-of-memory errors, along the lines of this:
FILE NAME: IMG_0047.JPG test
Resizing image...
New image: /homepages/20/d153810528/htdocs/toolbox/stuff/images/tool_photos/IMG_0047_resized.JPG
New filename: IMG_0047_resized.JPG
Fatal error: Out of memory (allocated 35389440) (tried to allocate
4032 bytes) in
/homepages/20/d153810528/htdocs/toolbox/cat/libraries/Image_lib.php on
line 1455
The "resized" images aren't actually saved.
I know the first choice solution is to allocate more memory with php_ini, but it appears that the hosting provider -- 1and1 . com -- doesn't allow that; it's set at a hard 120M; I'm guessing they don't want customers screwing with their shared servers.
Any thoughts?
Here's the code that handles the resizing:
public function uploadapicture() {
$status = '';
$msg = '';
$file_element_name = 'picture';
if ($status !== 'error') {
$config['upload_path'] = 'stuff/images/tool_photos/';
$config['allowed_types'] = 'gif|jpeg|png|jpg';
$config['max_size'] = 1024 * 50;
$config['encrypt_name'] = FALSE;
$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();
$image_path = $data['full_path'];
if (file_exists($image_path)) {
$status = 'success';
$msg = 'Main picture "' . $_FILES[$file_element_name]['name'] . '" successfully uploaded';
} else {
$status = 'error';
$msg = 'There was a problem saving the main picture.';
}
}
#unlink($_FILES[$file_element_name]);
$file_element_name = 'thumbnail';
if ((strlen($_FILES[$file_element_name]['name']) > 0) && !$this->upload->do_upload($file_element_name)) {
$status = 'error';
$msg .= $this->upload->display_errors('','');
} else if (strlen($_FILES[$file_element_name]['name']) > 0) {
$data = $this->upload->data();
$image_path = $data['full_path'];
if (file_exists($image_path)) {
$status = 'success';
$msg .= 'Thumbnail successfully uploaded';
} else {
$status = 'error';
$msg .= 'There was a problem saving the thumbnail.';
}
}
if ($status === 'success') {
echo "<br><pre>Post stuff:" . print_r($_POST,1);
$toolToInsert = array(
'picture_filename' => $_FILES['picture']['name'],
'name' => $this->input->post('name'),
'purchase_price' => $this->input->post('purchase_price'),
'public_notes' => $this->input->post('public_notes'),
'public_misc' => $this->input->post('public_misc'),
'purchased_from' => $this->input->post('purchased_from'),
'private_purchase_date' => $this->input->post('private_purchase_date'),
'private_purchase_price' => $this->input->post('private_purchase_price'),
'purchase_location' => $this->input->post('purchase_location'),
'sold_by' => $this->input->post('sold_by'),
'date_sold' => $this->input->post('date_sold'),
'sale_price' => $this->input->post('sale_price'),
'sold_to_name' => $this->input->post('sold_to_name'),
'sold_to_phone' => $this->input->post('sold_to_phone'),
'sold_to_email' => $this->input->post('sold_to_email'),
'private_notes' => $this->input->post('private_notes'),
'private_misc' => $this->input->post('private_notes'),
'entered_this_year' => $this->input->post('entered_this_year'),
'year_entered' => date('Y')
);
if (isset($_FILES['thumbnail']['name'])) {
$toolToInsert['thumbnail_filename'] = $_FILES['thumbnail']['name'];
}
foreach($_POST as $pKey => $pVal) {
if (substr($pKey,0,9) === 'category_') {
error_log("Found a category: ".print_r($pVal,1)." for key of ".print_r($pKey,1));
$post_category[] = substr($pKey,9);
}
}
if (isset($post_category)) {
$toolToInsert['category'] = implode(',',$post_category);
}
if (isset($_POST['active'])) {
$toolToInsert['active'] = 1;
}
$this->load->model('Letme_model');
$result = $this->Letme_model->insertTool('tool_db',$toolToInsert);
echo "Result: \n";
echo print_r($result,1);
}
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
one way to increase memory in php 5.x for uploading images is in your .htaccess
just add this lines:
## I need more memory to upload large image
<IfModule mod_php5.c>
php_value memory_limit 256M ## or whatever you need
</IfModule>

Cannot modify header information in CI

I'm working on CodeIgniter using XAMPP. When I upload my files on my subdomain, it give me an error but its working on my local machine.
here is my controller
if ($this->session->userdata('admin_email') && $this->session->userdata('admin_id')) {
$data['title'] = $this->session->userdata('admin_name');
$this->load->view('admin/header',$data);
$this->load->view('admin/topbar');
$this->load->view('admin/sidebar');
//$this->load->view('admin/home');
$this->load->view('admin/footer');
}
else
{
$this->session->set_flashdata('adminlogin','please login first..');
redirect('admin/login');
}
here is my error:
A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by
(output started at
/home/shakzeec/public_html/demo/application/controllers/admin.php:2)
Filename: libraries/Session.php
Line Number: 688 A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by
(output started at
/home/shakzeec/public_html/demo/application/controllers/admin.php:2)
Filename: libraries/Session.php
Line Number: 688 A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by
(output started at
/home/shakzeec/public_html/demo/application/controllers/admin.php:2)
Filename: helpers/url_helper.php
Line Number: 542
PHP does not allow you to modify headers once output is already started. Redirecting requires a change to the header. If you want to redirect, do only a redirect and nothing else.
if (!$this->session->userdata('admin_email') && !$this->session->userdata('admin_id')) {
$this->session->set_flashdata('adminlogin','please login first..');
redirect('admin/login');
}
else{
$data['title'] = $this->session->userdata('admin_name');
$this->load->view('admin/header',$data);
$this->load->view('admin/topbar');
$this->load->view('admin/sidebar');
//$this->load->view('admin/home');
$this->load->view('admin/footer');
}
Also, make sure there is nothing else in your controller which could be sending output before you modify the headers.
Here is the controllers/employers.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Employers extends CI_Controller {
public function __construct() {
parent::__construct();
date_default_timezone_set("Asia/Manila");
$this->load->model('_user');
}
public function index()
{
$data['userlist'] = $this->_user->get_user_list();
$this->load->view('employers/index', $data);
$this->template->render();
}
public function registration()
{
$data['userToken'] =$this->scriptor->userToken();
$data['userlist'] = $this->_user->get_user_list();
if(!isset($_REQUEST['msg'])){ $_REQUEST['msg'] = ''; }
$this->load->view('employers/registration', $data);
$this->template->render();
}
public function newregister()
{
$dr = strlen($_SERVER['PHP_SELF']) - 9;
$path = $_SERVER["DOCUMENT_ROOT"] .substr($_SERVER['PHP_SELF'], 0, $dr) .'image/source/employer/' . strtolower($this->input->post('Username'));
if(!is_dir($path)){
//Make Directory
if (!mkdir($path, 0777, true)) {
die('Failed to create folders...');
}
}
$config['upload_path'] = $path;
$config['file_name'] = url_title(strtolower($this->input->post('Username'))) . $this->upload->data('file_ext');
$config['allowed_types'] = 'gif|jpg|png|';
$config['max_size'] = '';
$config['max_width'] = '';
$config['max_height'] = '';
$this->upload->initialize($config);
$err = 'failed_reg';
$ok = true;
if(strlen($this->input->post('Username')) == 0){
$ok = false;
$err = 'err_username';
}
if(strlen($this->input->post('Lastname')) == 0 && $ok){
$ok = false;
$err = 'err_lastname';
}
if(strlen($this->input->post('Firstname')) == 0 && $ok){
$ok = false;
$err = 'err_firstname';
}
if(strlen($this->input->post('Email')) == 0 && $ok){
$ok = false;
$err = 'err_email';
}
if(strlen($this->input->post('Cellphone')) == 0 && $ok){
$ok = false;
$err = 'err_cellphone';
}
if(strlen($this->input->post('Telephone')) == 0 && $ok){
$ok = false;
$err = 'err_telephone';
}
if(strlen($this->input->post('Address')) == 0 && $ok){
$ok = false;
$err = 'err_address';
}
if(strlen($this->input->post('City')) == 0 && $ok){
$ok = false;
$err = 'err_city';
}
if(!$this->upload->do_upload('EmpPic') && $ok){
$ok = false;
if(is_dir($path)){
array_map('unlink', glob($path."/*"));
rmdir($path);
}
$err = 'err_image';
}
if($_FILES['EmpGovID']['size'] > 0){
if(!$this->upload->do_upload('EmpGovID') && $ok){
$ok = false;
if(is_dir($path)){
array_map('unlink', glob($path."/*"));
rmdir($path);
}
$err = 'err_image2';
}
}
if($ok){
$i = array(
'Firstname' => $this->scriptor->_enc($this->input->post('Firstname'))
, 'Middlename' => $this->scriptor->_enc($this->input->post('Middlename'))
, 'Lastname' => $this->scriptor->_enc($this->input->post('Lastname'))
, 'Telephone' => $this->scriptor->_enc($this->input->post('Telephone'))
, 'Cellphone' => $this->scriptor->_enc($this->input->post('Cellphone'))
, 'Email' => $this->scriptor->_enc($this->input->post('Email'))
, 'Address' => $this->scriptor->_enc($this->input->post('Address'))
, 'City' => $this->scriptor->_enc($this->input->post('City'))
, 'EPicture' => base_url('image/employer') . '/'.$config['file_name']
, 'Username' => $this->scriptor->_enc($this->input->post('Username'))
, 'Password' => $this->scriptor->_enc($this->input->post('Password'))
, 'Token' => $this->scriptor->userToken()
, 'Level' => 'user'
, 'Yatype' => $this->scriptor->_enc($this->input->post('Yatype'))
, 'GovID' => base_url('image/employer') . '/'.$config['file_name']
, 'q1' => $this->scriptor->_enc($this->input->post('q1'))
, 'q2' => $this->scriptor->_enc($this->input->post('q2'))
, 'q3' => $this->scriptor->_enc($this->input->post('q3'))
, 'aq1' => $this->scriptor->_enc($this->input->post('aq1'))
, 'aq2' => $this->scriptor->_enc($this->input->post('aq2'))
, 'salary' => $this->scriptor->_enc($this->input->post('salary'))
, 'registeredDate' => date('Y-m-d h:i:s')
, 'Message' => $this->scriptor->_enc($this->input->post('Message'))
);
$this->_user->add($i);
redirect('employers/registration?msg=success_reg');
} else {
redirect('employers/registration?msg='. $err);
}
/******************************************************************/
}//End Class
}

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