facing problems uploading image in a form using codeigniter - php

Am trying to include an image in a form, the image is added correctly but however two rows are added in the database table.
Structure of table with data added is below:
My controller
public function addRecordToTable(){
$this->load->library('form_validation');
$this->form_validation->set_rules('client_id' , 'client_id', 'required');
$this->form_validation->set_rules('l_address' , 'location address', 'required|min_length[3]|max_length[50]');
if ($this->form_validation->run() == false) {
$this->load->model('Clientaccount_model');
$data['bids']=$this->Clientaccount_model->bids();
$data['loads']=$this->Truckeraccount_model->loads();
$this->load->view('footer');
} else {
$array = array(
'client_id' => $this->input->post('client_id'),
'l_address' => $this->input->post('l_address'),
);
$record_id = $this->consignmentupload_model->addData('consignment', $array);
$this->uploadFiles($record_id);
}
}
public function uploadFiles($record_id){
$config = array(
'upload_path' => FCPATH . "/uploads/",
'allowed_types' => 'jpg|png|jpeg',
'overwrite' => TRUE,
);
$this->load->library('upload', $config);
$files = $_FILES['uploads'];
foreach ($files['name'] as $key => $filename) {
$_FILES['uploads[]']['name'] = $files['name'][$key];
$_FILES['uploads[]']['type'] = $files['type'][$key];
$_FILES['uploads[]']['tmp_name'] = $files['tmp_name'][$key];
$_FILES['uploads[]']['error'] = $files['error'][$key];
$_FILES['uploads[]']['size'] = $files['size'][$key];
$config['file_name'] = $filename;
$this->upload->initialize($config);
if (isset($_FILES['uploads[]']['name']) && !empty($_FILES['uploads[]']['name'])) {
if ( ! $this->upload->do_upload('uploads[]')) {
$error = array('error' => $this->upload->display_errors());
} else {
$uploads[] = $this->upload->data();
$array = array(
'record_id' => $record_id,
'filename' => $_FILES['uploads[]']['name'],
'size' => $_FILES['uploads[]']['size']
);
$this->consignmentupload_model->addData('consignment', $array);
}
}
}
redirect(site_url('clientaccount_ctrl'));
}
My Model
public function addData($table, $array)
{
$this->db->insert($table, $array);
return $this->db->insert_id();
}

after your first insert that is,
$record_id = $this->consignmentupload_model->addData('consignment', $array);
you have to update the same row with your image,
so in uploadFiles instead of, $this->consignmentupload_model->addData('consignment', $array);
make a new model function updateData() where you update the same row which was inserted earlier, pass the luggage_id to updateData()

Related

Download files from external url in Laravel/PHP

I want to download files using external urls on click below code i am using and its working fine now error but file is not downloading anywhere.
public function checkCount(Request $request)
{
$userid = Session::get('UserId');
$count = DB::table('download_details')
->where('type','=',$request->type)
->where('user_id','=',$userid)
->get()
// echo "<pre>"; print_r($count); die;
->count();
if($count >= 2)
{
echo 0;
}
else
{
$data = array(
'corporate_id' => $request->corporateid,
'user_id' => Session::get('UserId'),
'ip_address' => \Request::ip(),
'mac_address' => '',
'type' => $request->type,
'count' => '',
'date' => date('Y-m-d'),
'status' => 1
);
$insert = DB::table('download_details')->insert($data);
$name = basename($request->url);
$path = $request->url;
// echo $path; die;
$tempImage = tempnam(sys_get_temp_dir(), $path);
copy($request->url, $tempImage);
return response()->download($tempImage, $name);
}
}
My Ajax Code
function saveData(type,url)
{
var corporateid = $('#corporateid').val();
// alert(type);
$.ajax({
type:'POST',
url:'/check-count',
data:{'_token':'{{csrf_token()}}',corporateid:corporateid,type:type,url:url},
success:function(response){
// alert(response);
if(response == 0)
{
$('#download_error_message').show();
$('#download_error_message').html("Download Limit Exceeded");
$('#download_error_message').fadeOut(4000);
}
else
{
alert("Success");
}
}
});
}
Else part shows that i am downloading file. NO errors is ajax request but file is not downloading at all.
file is not downloading.please help
Hopefully, it will work.
public function checkCount(Request $request)
{
$userid = Session::get('UserId');
$count = DB::table('download_details')
->where('type','=',$request->type)
->where('user_id','=',$userid)
->get()
// echo "<pre>"; print_r($count); die;
->count();
if($count >= 2)
{
echo 0;
}
else
{
$data = array(
'corporate_id' => $request->corporateid,
'user_id' => Session::get('UserId'),
'ip_address' => \Request::ip(),
'mac_address' => '',
'type' => $request->type,
'count' => '',
'date' => date('Y-m-d'),
'status' => 1
);
$insert = DB::table('download_details')->insert($data);
$name = basename($request->url);
$path = $request->url;
// echo $path; die;
$tempImage = tempnam(sys_get_temp_dir(), $path);
copy($request->url, $tempImage);
$mimeType = mime_content_type($tempImage);
$headers = ["Content-Type: {$mimeType}"];
return Response::download($tempImage, $name, $headers);
}
}

How to read Images from excel and store them in database using laravel?

I am using Maatwebsite\Excel\ExcelServiceProvider::class plugin ,I want to store images and product details through Excel sheet.
How can I upload images .excel data ?
please help me...
ProductController.php
public function excelupload()
{
if(Input::hasFile('import_file')){
$path = Input::file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
dd($value);
$insert[] = ['product_name' => $value->product_name, 'cataloge_number' => $value->cataloge_number, 'cas_number' => $value->cas_number, 'product_image' => $value->product_image, 'chemical_name' => $value->chemical_name , 'synonyms' => $value->synonyms , 'molecular_formula' => $value->molecular_formula, 'molecular_mass' => $value->molecular_mass ,'product_stock' => $value->product_stock];
}
if(!empty($insert)){
DB::table('products')->insert($insert);
return redirect('admin/product')->with('message', 'New Product Added Successfully!');
}
}
}
return back();
}
If product_image column in excel has URL of image then you need to install Laravel Image Intervention Package:
http://image.intervention.io/
or
https://github.com/Intervention/image
After install, try this code for store images from URL in Local Laravel Storage and save the path in Database:
public function excelupload()
{
if(Input::hasFile('import_file')){
$path = Input::file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
dd($value);
$file = $value->product_image;
if ($file)
{
$ext = pathinfo($file, PATHINFO_EXTENSION);
$main_image = Image::make(file_get_contents($file))->widen(860, function ($constraint) {
$constraint->upsize();
});
$dir = 'photos/';
$path = uniqid().'.jpg';
$main_image->encode();
Storage::put($dir.$path, (string)$main_image);
$product_image = $path;
}else{
$product_image = null;
}
$insert[] = [
'product_name' => $value->product_name,
'cataloge_number' => $value->cataloge_number,
'cas_number' => $value->cas_number,
// 'product_image' => $value->product_image,
'product_image' => $product_image,
'chemical_name' => $value->chemical_name ,
'synonyms' => $value->synonyms ,
'molecular_formula' => $value->molecular_formula,
'molecular_mass' => $value->molecular_mass,
'product_stock' => $value->product_stock
];
}
if(!empty($insert)){
DB::table('products')->insert($insert);
return redirect('admin/product')->with('message', 'New Product Added Successfully!');
}
}
}
return back();
}

getting multiple customer details In codeigniter

i have written this code to receive data from the Android device. it was inserted just one customer data I need to receive multiple customer details if app goes offline. but it was inserting one data into DB in offline mode also.how can i change this for multiple customer data insertions.
function index_post($customerID = false) {
if ($customerID) {
//update the record
$updateData = array();
$allowedparams = array('streetid' => 'streetid', 'name' => 'name', 'mobile' => 'mobile', 'adhaar' => 'adhaar', 'profession' => 'profession', 'address' => 'address', 'pincode' => 'pincode', 'nearby' => 'nearby', 'paddress' => 'paddress', 'isOwned' => 'isOwned');
foreach ($allowedparams as $k => $v) {
if (!$this->IsNullOrEmptyString($this->post($k, true))) {
$updateData[$v] = $this->post($k, true);
}
}
if ($this->model_customer->update($customerID, $updateData)) {
$data = array('status' => true, 'messsage' => 'cusotmer updated succesfully');
$http_code = REST_Controller::HTTP_OK;
} else {
$data = array('status' => false, 'messsage' => 'cusotmer failed to update.');
$http_code = REST_Controller::HTTP_INTERNAL_SERVER_ERROR;
}
} else {
//insert the record
$allowedparams = array('streetid' => 'streetid', 'name' => 'name', 'mobile' => 'mobile', 'adhaar' => 'adhaar', 'profession' => 'profession', 'address' => 'address', 'pincode' => 'pincode', 'cycle' => 'cycle', 'nearby' => 'nearby', 'paddress' => 'paddress', 'isOwned' => 'isOwned');
$requiredParam = array('streetid', 'name', 'mobile', 'cycle');
$insertdata = array();
foreach ($allowedparams as $k => $v) {
if (in_array($k, $requiredParam)) {
//check if its not null
if ($this->post($k) == null || trim($this->post($k)) == '') {
$data = array('status' => false, 'message' => $k . ' parameter missing or empty');
$http_code = REST_Controller::HTTP_BAD_REQUEST;
break;
}
}
$insertData[$v] = $this->post($k, true);
}
if ($customerID = $this->model_customer->create($insertData)) {
$data['customerID'] = $this->_frameCustomer2($this->model_customer->get($customerID)); //you need to put
$http_code = REST_Controller::HTTP_OK;
} else {
$data = array('status' => false, 'message' => 'unable to create customer');
$http_code = REST_Controller::HTTP_INTERNAL_SERVER_ERROR;
}
}
$this->response($data, $http_code);
}
private function _frameCustomer2($c) { //get value from index_get
$data = array();
$data['id'] = $c->id;
$data['name'] = $c->name;
$data['street'] = array('id' => $c->streetid);
$data['creationDate'] = $c->creationdate;
$data['mobile'] = $c->mobile;
$data['adhaar'] = $c->adhaar;
$data['profession'] = $c->profession;
$data['isOwned'] = ($c->isOwned == 1) ? true : false;
$data['address'] = $c->address;
$data['pincode'] = $c->pincode;
$data['status'] = $c->status;
$data['cycle'] = $c->cycle;
$data['balance'] = $c->balance;
$data['creditAvailable'] = $c->creditbalance;
$data['nearby'] = $c->nearby;
$data['accountNumber'] = $c->accountnumber;
$data['permanentAddress'] = $c->paddress;
$data['lastVisit'] = $this->model_customer->lastVisit($c->id);
return $data;
}
and my part of model function is
function create($insertdata = array()) { //new customer insert
if ($this->db->insert('customer', $insertdata)) {
return $this->db->insert_id();
} else {
return false;
}
}
function update($customerID = 0, $updateData = array()) {
$this->db->where('id', $customerID);
if ($this->db->update('customer', $updateData) && $this->db->affected_rows() == 1) {
return true;
} else {
return false;
}
Instead of customer Id, you can ask the mobile developers to send data in the form of array. In both online and offline. In case of online there will be just one element in the request array.
function index_post() {
$request_data = $this->request->body;
foreach($request_data as $key => $value)
{
//Check if customer id is present
if(Customer present)
{
Update the record
} else {
Insert the record
}
}
}

Codeigniter:Update Image and Display Current image if I don't want to update

I'm stuck on a problem with updating image. I've created image upload which works fine but I also want it to be updated. When I add a need image it updates correctly but I if don't want to change the image and leave it as it is, then my current image can't be retrieve. Please help me
Here is my code:
Controller:
function edit_product($product_id)
{
$data = array('recipe_info' => $this->products_model->getRcipe($this->uri->segment(3)),
'product_id' => $this->uri->segment(3)
);
/*var_dump($data); die();*/
$this->load->view('edit_product', $data);
}
public function save_edit_recipe()
{
$thumnail="";
$stats = "";
$msg = "";
$filename = 'r_image';
$data = array(
'recipe_id' => $this->uri->segment(3),
'r_name' => $this->input->post('r_name'),
'r_image' => '',
'r_description' => $this->input->post('r_description'),
'time_id' => $this->input->post('cooking_time'),
'r_cal' => $this->input->post('calories'),
'r_serve' => $this->input->post('serving_size'),
'r_procedure' => $this->input->post('recipe_procedure')
);
$recipe_id = $this->products_model->update_product($this->uri->segment(3), $data);
foreach($this->input->post('ingredients') as $key => $value)
{
$menuData[] = array('recipe_id' => $this->input->post('recipe_id'),
'ingredient_id' => $value,
'category_id' => $this->input->post('recipe_category')
);
}
$this->products_model->saveMenu($menuData);
$config['upload_path'] = 'img/recipes/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024 * 8 ;
$config['encrypt_name'] = true;
$this->load->library('upload',$config);
if (!$this->upload->do_upload($filename))
{
$stats = 'error';
$msg = $this->upload->display_errors('', '');
}else{
$uploadData = $this->upload->data('file_name');
if($uploadData['file_name'])
{
$thumnail = 'img/recipes/'.$uploadData['file_name'];
}else{
$thumnail = 'No thumnbail uploaded!';
}
$updateThumbData = array('recipe_id' => $this->input->post('recipe_id'),
'r_image' => $thumnail
);
$this->products_model->updataRecipeThumnail($updateThumbData);
}
redirect('dashboard');
}
Model:
function getRcipe($recipe_id)
{
$this->db->where('recipe_id', $recipe_id);
$query = $this->db->get('recipe');
return $query->result();
}
public function update_product($product_id, $data)
{
$this->db->where('recipe_id', $product_id);
$this->db->update('recipe', $data);
}
public function updataRecipeThumnail($data)
{
$this->db->where('recipe_id', $data['recipe_id']);
$this->db->update('recipe', $data);
}
i have updated in your script...please used this function... then your problem may be shortout..
public function save_edit_recipe()
{
$thumnail="";
$stats = "";
$msg = "";
$filename = 'r_image';
$data = array(
'recipe_id' => $this->uri->segment(3),
'r_name' => $this->input->post('r_name'),
'r_description' => $this->input->post('r_description'),
'time_id' => $this->input->post('cooking_time'),
'r_cal' => $this->input->post('calories'),
'r_serve' => $this->input->post('serving_size'),
'r_procedure' => $this->input->post('recipe_procedure')
);
$recipe_id = $this->products_model->update_product($this->uri->segment(3), $data);
foreach($this->input->post('ingredients') as $key => $value)
{
$menuData[] = array('recipe_id' => $this->input->post('recipe_id'),
'ingredient_id' => $value,
'category_id' => $this->input->post('recipe_category')
);
}
$this->products_model->saveMenu($menuData);
$config['upload_path'] = 'img/recipes/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024 * 8 ;
$config['encrypt_name'] = true;
$this->load->library('upload',$config);
if (!$this->upload->do_upload($filename))
{
$stats = 'error';
$msg = $this->upload->display_errors('', '');
}else{
$uploadData = $this->upload->data('file_name');
if($uploadData['file_name'])
{
$thumnail = 'img/recipes/'.$uploadData['file_name'];
$updateThumbData = array(
'recipe_id' => $this->input->post('recipe_id'),
'r_image' => $thumnail
);
$this->products_model->updataRecipeThumnail($updateThumbData);
}else{
$thumnail = 'No thumnbail uploaded!';
}
}
redirect('dashboard');
}

Codeigniter 2.1 - fileupload You did not select a file to upload

Model function:
public function file_upload($folder, $allowed_type, $max_size = 0, $max_width = 0, $max_height = 0)
{
$folder = $this->path . $folder;
$files = array();
$count = 0;
foreach ($_FILES as $key => $value) :
$file_name = is_array($value['name']) ? $value['name'][$count] : $value['name'];
$file_name = $this->global_functions->char_replace($file_name, '_');
$count++;
$config = array(
'allowed_types' => $allowed_type,
'upload_path' => $folder,
'file_name' => $file_name,
'max_size' => $max_size,
'max_width' => $max_width,
'max_height' => $max_height,
'remove_spaces' => TRUE
);
$this->load->library('image_lib');
$this->image_lib->clear();
$this->load->library('upload');
$this->upload->initialize($config);
if (!$this->upload->do_upload($key)) :
$error = array('error' => $this->upload->display_errors());
var_dump($error);
return FALSE;
else :
$file = $this->upload->data();
$files[] = $file['file_name'];
endif;
endforeach;
if(empty($files)):
return FALSE;
else:
return implode(',', $files);
endif;
}
This function is working partially. Files are being uploaded to the selected folder, but I am getting this error: You did not select a file to upload. and getting FALSE as a result? What seems to be a problem? (form is using form_open_multipart)
Please make sure that you have this name of your file tag field:
$key='userfile' //which is name of input type field name
Are any of your file inputs empty when this happens? $_FILES will contain an array of "empty" data if there is no file specified for the input. For example, my file input name is one, and I submitted it without specifying a file:
Array
(
[one] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] => 0
)
)
You should check if the file data is empty before processing the upload. PHP's is_uploaded_file() is useful for this.

Categories