codeigniter alert if image size exceeds - php

Hi I have this code for uploading an image. I can perfectly add the image but I want to add restrictions and there will an alert that will pop up if image size exceeds but I don't know how can add I alert if image size exceeds. please help me
Here's my code:
CONTROLLERS:
public function upload_file()
{
$filename = 'r_image';
$status = "";
$msg = "";
$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' => $recipe_id,
'r_image' => $thumnail
);
$this->products_model->updataRecipeThumnail($updateThumbData);
redirect('dashboard/view_product');
} /* upload_file() */
}

for uploading files you must use POST method. read this w3schools file upload.
if($_FILES['Your_POST_name']['size']>1024 * 8 )// to check what is your post name print_r($_FILES);
{
$this->session->set_flashdata('msg', '<div class="alert alert-danger alert-dismissible fade in" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>Image is too big!</div>');
redirect('dashboard/view_product');
}
and in your view_product's view file, add following code to display error
<?php echo $this->session->flashdata('msg'); ?>
Important things to remember while dealing with file uploads in php.
Make sure that the form uses method="post"
The form also needs the following attribute:
enctype="multipart/form-data". It specifies which content-type to use
when submitting the form
Without the requirements above, the file upload will not work.

Related

How to multiple upload files in codeigniter 3

i'm newbie on codeigniter and php, i just don't know how to upload multiple files..
I am able to upload & insert a image ine the database. But I am unable to upload multiple images, what should I change in the below code , in order to upload multiple images
help me, here is my code
Controller
public function index()
{
$data['title'] = 'Pengaduan';
$masyarakat = $this->db->get_where('masyarakat',['username' => $this->session->userdata('username')])->row_array();
$data['data_pengaduan'] = $this->Pengaduan_m->data_pengaduan_masyarakat_nik($masyarakat['nik'])->result_array();
$this->form_validation->set_rules('isi_laporan','Isi Laporan Pengaduan','trim|required');
$this->form_validation->set_rules('foto','Foto Pengaduan','trim');
if ($this->form_validation->run() == FALSE) :
$this->load->view('_part/backend_head', $data);
$this->load->view('_part/backend_sidebar_v');
$this->load->view('_part/backend_topbar_v');
$this->load->view('masyarakat/pengaduan');
$this->load->view('_part/backend_footer_v');
$this->load->view('_part/backend_foot');
else :
$upload_foto = $this->upload_foto('foto'); // parameter nama foto
if ($upload_foto == FALSE) :
$this->session->set_flashdata('msg','<div class="alert alert-danger" role="alert">
Upload foto pengaduan gagal, hanya png,jpg dan jpeg yang dapat di upload!
</div>');
redirect('Masyarakat/PengaduanController');
else :
$params = [
'tgl_pengaduan' => date('Y-m-d'),
'nik' => $masyarakat['nik'],
'isi_laporan' => htmlspecialchars($this->input->post('isi_laporan',true)),
'foto' => $upload_foto,
'status' => '0',
];
$resp = $this->Pengaduan_m->create($params);
if ($resp) :
$this->session->set_flashdata('msg','<div class="alert alert-primary" role="alert">
Laporan berhasil dibuat
</div>');
redirect('Masyarakat/PengaduanController');
else :
$this->session->set_flashdata('msg','<div class="alert alert-danger" role="alert">
Laporan gagal dibuat!
</div>');
redirect('Masyarakat/PengaduanController');
endif;
endif;
endif;
}
private function upload_foto($foto)
{
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'jpeg|jpg|png';
$config['max_size'] = 2048;
$config['remove_spaces'] = TRUE;
$config['detect_mime'] = TRUE;
$config['mod_mime_fix'] = TRUE;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($foto)) :
return FALSE;
else :
return $this->upload->data('file_name');
endif;
}
i tried using [] but it's show error, Is there a way to use this code so i can upload multiple images?

Image upload still submitting with callback validation in CI

I am trying to do a image upload validation on codeigniter 3. I have tried many tut's but still face this issue. I would like if the user was to leave the upload a photo area blank ( eventually if they upload a unsupported mime and size) for it to throw a error before it allows or tries to submit the data.
Right now it throws a error but showing the database query along with "Image in sql cannot be blank". I would like it to show like a regular form validation would without it showing the sql query and error.
It still seems to submit the form without it throwing the error first, because it says $post_image undefined.
I have already tried entering a callback with isset function to try to only allow the form to submit data if a image was uploaded, if not I was trying to display the errors by passing the error variable. None of this seems to work correctly as I explained above.
Controller:
public function create(){
//Check in login session
if(!$this->session->userdata('logged_in')){
$this->session->set_flashdata('log_post','Please login or create a free account to post a ad.');
redirect('users/register');
}
$data['title'] = 'Create a Post';
$data['categories'] = $this->post_model->get_categories();
$data['states'] = $this->post_model->get_city();
$this->form_validation->set_error_delimiters('<div class="error"> <h7> Error: </h7>', '</div>');
$this->form_validation->set_rules('title','Title',array('required', 'min_length[3]'));
//$this->form_validation->set_rules('file','Image Upload','required');
$this->form_validation->set_rules('Description','About You',array('required', 'min_length[5]'));
$this->form_validation->set_rules('Number','Phone Number',array('required', 'min_length[7]'));
$this->form_validation->set_rules('Area','Location/Area',array('required', 'min_length[2]'));
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('posts/create', $data);
$this->load->view('templates/footer');
} else {
// $this->load->helper('file');
//$this->form_validation->set_rules('file','','callback_file_check');
if($this->form_validation->run()==TRUE){
$config['upload_path'] = 'assets/images/posts';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['encrypt_name'] = TRUE; //TURN ON
$config['max_size'] = 0;
$config['max_width'] = 0;
$config['max_height'] = 0;
$this->upload->initialize($config);
if(!$this->upload->do_upload('file')){
$errors = array('error'=>$this->upload->display_errors());
$this->load->view('templates/header');
$this->load->view('posts/create', $errors);
$this->load->view('templates/footer');
}else {
$data = $this->upload->data();
$post_image = $data['file_name'];
}
}
$this->post_model->create_post($post_image);
$this->session->set_flashdata('post_created','Your Post has been submitted');
redirect('posts');
}
}
}// end of class
Model:
public function create_post($post_image){
$slug = md5(uniqid().mt_rand());
//url_title($this->input->post('title'), 'dash', TRUE). // this is the orginal way for slug SEO friendly
$site = $this->input->post('site');
//adds HTTP too website links
if (!preg_match("~^(?:f|ht)tps?://~i", $site)) {
$site = "http://" . $site;
}
$data = array(
'title'=>$this->input->post('title'),
'body'=> $this->input->post('Description'),
'post_image' => $post_image
);
return $this->db->insert('posts',$data);
}
View:
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="textarea">Photo</label>
<div class="col-lg-8">
<div class="mb10">
<?php echo form_error('file') ?>
<input name="file" type="file" class="form-control-file" id="exampleInputFile" aria-describedby="fileHelp">
</div>
<?php if (isset($error)) { echo $error; } ?>
</div>

Why do I get warning 'Too few arguments to function' even though the update process is success on database?

So here is the error :
Message: Too few arguments to function Admin::edit_item(), 0 passed in
.. exactly 1 expected
/*
* Edit Item
*/
public function edit_item($id) {
// Validate Rules
$this->form_validation->set_rules('item_name','Item Name','trim|required|min_length[2]|max_length[30]');
$this->form_validation->set_rules('price','Price','trim|required|is_natural_no_zero');
$this->form_validation->set_rules('description','Description','trim|required|min_length[2]|max_length[500]');
$this->form_validation->set_rules('quantity','Quantity','trim|required|is_natural_no_zero');
// Get Item Details
$data['products'] = $this->Product_model->get_product_details($id);
if ($this->form_validation->run() == FALSE) {
// Load view
$data['main_content'] = 'admin_edit_item';
$this->load->view('layouts/main_admin', $data);
}
else
{
if ($_FILES['userfile']['size'] == 0 && $_FILES['userfile']['error'] == 0) {
// If There Is No Image Uploaded
$product_update = $this->Product_model->update_item();
if (!$product_update)
{
$this->session->set_flashdata('failed_edit_item', 'The Item Failed To Be Edited');
redirect('admin/edit_item');
}
else
{
$this->session->set_flashdata('success_edit_item', 'The Item Is Successfully Edited');
redirect('admin/edit_item');
}
}
else
{
// Update The Database
$this->Product_model->update_item();
$product_id = $this->input->post('product_id');
// Set Config For Uploading Image
$config['upload_path'] = './assets/images/product/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 10000;
$config['max_width'] = 225;
$config['max_height'] = 225;
$config['file_name'] = $product_id;
$this->load->library('upload', $config);
$this->upload->overwrite = true;
if ( ! $this->upload->do_upload('userfile'))
{
$this->session->set_flashdata('failed_edit_item', 'The Item Failed To Be Edited');
redirect('admin/edit_item');
}
else
{
// After Image Get Uploaded, Adjust The Image Field On The Database
$success_data['image_name'] = $this->upload->data('file_name');
$success_data['id'] = $product_id;
$update = $this->Product_model->adjust_image($success_data);
if($update) {
$this->session->set_flashdata('success_edit_item', 'The Item Is Successfully Edited');
redirect('admin/edit_item');
}
}
}
}
}
And On the admin_edit_item view
here is the form head
<form method="post" accept-charset="utf-8" enctype="multipart/form-data" action="<?php echo base_url(); ?>admin/edit_item/<?php echo $products->id; ?>">
As you can see, I already set the action on the form,
So, it should work.
I mean, even though I get that error, when I reload the database,
the data has been updated according to the edited data that I change.
But still I get that error.
I tried to find the bug, but have no luck.
The warning is telling you that $products->id is not being passed. I cannot tell why not... looks like it should.
Note this is a warning not a fatal error which means that the method edit_item($id) will still run. Why it works is not clear mostly because you do not share the code for Product_model->update_item() which I assume is where the db is updated. (How does update_item() know which item to update???)
Because of this line of code
$product_id = $this->input->post('product_id');
It appears that the "product_id" value is a form field.
Perhaps using the above code at the top of the method to get the value instead of trying to pass it to the method via URL will help solve your problem.
I suggest you rewrite your form html (without the product_id) as follows
<form method="post" accept-charset="utf-8" enctype="multipart/form-data"
action="<?php echo base_url('admin/edit_item'); ?>">
The above makes better use of base_url() (documentation here.) and is easier to read.
If you insist on passing the data via URL you could do this
<form method="post" accept-charset="utf-8" enctype="multipart/form-data"
action="<?php echo base_url("admin/edit_item/{$products->id}"); ?>">

Codeigniter 2.x optional file uploading issue "You did not select a file to upload"

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

How to make codeigniter sticky form when error comes from upload file field

I have a form that allows user to upload multiple files. Additionaly user have to fill other input text fields like address, email etc.
I don't know how to make form sticky if error comes from file uploading and how to access error messages set by form_validation library. Because if for example one of the filetype is not allowed I use redirect to step out of the loop responsible for uploading every file.
To keep upload error message I use $this->session->set_flashdata('errors', $errors) but then I'm not able to use error messages from form_validation library ( echo form_error('field_name) ) and display user input in form fields ( echo set_value('field_name'))
Here is controller method responsible for file upload and data insert:
function do_upload()
{
// load form validation library
$this->load->library('form_validation');
// set validation rules
$this->form_validation->set_rules('email','Email','trim|required|valid_email|matches[confirm_email]');
$this->form_validation->set_rules('confirm_email','Email','trim|required|valid_email');
$this->form_validation->set_rules('delivery_name','Nazwa','trim|required');
$this->form_validation->set_rules('delivery_street','Ulica','trim|required');
$this->form_validation->set_rules('delivery_city','Miasto','trim|required');
$this->form_validation->set_rules('delivery_postcode','Kod pocztowy','trim|required');
$this->form_validation->set_rules('delivery_country','Kraj','trim|required');
$this->form_validation->set_rules('captcha','Captcha','callback_check_captcha');
if ( $this->form_validation->run() )
{
// if validation passes I insert form data into database and I start to upload
// all the files using foreach loop
$config['upload_path'] = './uploads/upload_directory';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$upload_data = array();
$task_address_id_array = $this->MTasks->insertNewTask($task_directory);
$task_id = $task_address_id_array['task_id'];
$address_id = $task_address_id_array['address_id'];
// iterate over files to be uploaded
foreach ($_FILES as $key => $value)
{
if (!empty($value['name']))
{
$this->upload->initialize($config);
$result = $this->upload->do_upload($key);
if (!$result)
{
// if upload error occurs I need to redirect to break the loop
$errors = $this->upload->display_errors();
$this->session->set_flashdata('errors', $errors);
redirect();
}
else
{
$current_upload_data = $this->upload->data();
// insert upload data to database
$this->MTasks->insertFileInfo($current_upload_data,$task_id);
}
}
}
redirect('upload/success_message');
}
else
{
$this->load->view('include/header');
$this->load->view('upload_form',$this->data);
$this->load->view('include/footer');
}
}
The main problem is you can not put as validation rule file uploads, because the library executes one by one.
A simple solution is to validate your fields and then validate the file upload. Example:
<?php
function save()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'trim|required');
if($this->form_validation->run() == FALSE)
{
$this->form_validation->set_error_delimiters('', '<br />');
echo validation_errors();
exit();
}
else
{
if($_FILES['imagen']['error'] != 4)
{
$image $this->_manage_image($this->input->post('name'));
}
else
{
exit('No empty field!');
}
# save in your bd o success message...
}
}
function _manage_image($name)
{
# config
$config['upload_path'] = './images/products/';
$config['allowed_types'] = 'gif|jpg|png';
// ...
$config['file_name'] = $name;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('image'))
{
# errors...
echo $this->upload->display_errors();
exit();
}
else
{
# upload
return $img_data['file_name'];
}
}

Categories