codeigniter upload image with other data - codeigniter

I have a form am submitting and user has the ability to upload a picture in that form then submit the form as whole. I found a tutorial on codeigniter site showing upload form (dedicated only to upload, not other data along). link is: Codeigniter Upload Tutorial. How can I submit the form and then upload the files while also uploading other details to other table in database?

Below is an example
function add_staff(){
$this->load->library('form_validation');
$this->load->helper(array('form', 'url'));
// field name, error message, validation rules
$this->form_validation->set_rules('name', 'Full name', 'trim|required');
$this->form_validation->set_rules('designation', 'Last Name', 'trim|required');
if($this->form_validation->run() == FALSE)
{
$data['main_content'] = 'staff/add_staff';
$this->load->view('admin/template',$data);
}
else
{
$config['upload_path'] = 'uploads/staff/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('file'))
{
$data['error'] = array('error' => $this->upload->display_errors());
$new_staff = array(
'name' => $this->input->post('name'),
'designation' => $this->input->post('designation'),
'phone' => $this->input->post('phone'),
'email' => $this->input->post('email'),
'address' => $this->input->post('address'),
'description' => $this->input->post('description'),
'status' => $this->input->post('status')
);
}
else
{
$file_data = $this->upload->data('file');
$new_staff = array(
'name' => $this->input->post('name'),
'designation' => $this->input->post('designation'),
'phone' => $this->input->post('phone'),
'email' => $this->input->post('email'),
'address' => $this->input->post('address'),
'photo' => $file_data['file_name'],
'description' => $this->input->post('description'),
'status' => $this->input->post('status')
);
}
if($this->staff_model->add_staff($new_staff)):
$this->session->set_flashdata('success', 'Staff added Sucessfully !!');
endif;
redirect('admin/staff');
}
}

you can pass in other data as well along with file form your form to controller, like
<?php echo form_open_multipart('upload/do_upload');?>
<input type="text" name="someField" value="" />
<input type="file" name="userfile" size="20" />
<input type="submit" value="upload" />
</form>
and in your upload controller's do_upload function:
$someField = $this->input->post("somefield"); //save to some db
//and rest of your file to be uploaded code from the same link you provided
Did you mean something like this

Image MOO is a excellent library that can accomplish image manipulations on the fly....
e.g for resizing the uploaded image to a particular path, you just have to do this
public function thumbnailer($uploader_response,$field_info,$files_to_upload)
{
$this->load->library('image_moo');
$file_uploaded=$field_info->upload_path.'/'.$uploader_response[0]->name;
$thumbnails=$field_info->upload_path.'/thumbnails/'.$uploader_response[0]->name;
$cart_thumbnails=$field_info->upload_path.'/cart_thumbnails/'.$uploader_response[0]->name;
$this->image_moo->load($file_uploaded)->resize(400,250)->save($thumbnails,false);
}
Hope this helps !!

Related

how to upload both image and video at the same time with laravel

i'm trying to upload image and video at the same time but couldn't
i've tried this but it seems to not work, the image file will upload successfully but the video won't
$request->validate([
'title'=> 'required',
'description' => 'required',
'file' => 'required|mimes:jpg,jpeg,png|max:2048',
'video' => 'required|mimes:mp4'
]);
$film= Film::create([
'title' => $request->title,
'slug' => Str::slug($request->title),
'description' => $request->description,
'user_id' => auth()->id()
]);
$file = new Film();
if($request->file('file')) {
$file_name = time().'_'.$request->file->getClientOriginalName();
$file_path = $request->file('file')->storeAs('uploads', $file_name, 'public');
$file->name = time().'_'.$request->file->getClientOriginalName();
$file->file = '/storage/' . $file_path;
$film->update(['file' => $file_name]);
$film->update(['path' => $file_path]);
return response()->json(['success'=>'File uploaded successfully.']);
}
if ($request->file('video')){
$file_name = time().'_'.$request->file->getClientOriginalName();
$file_path = $request->file('video')->storeAs('uploads', $file_name, 'public');
$file->name = time().'_'.$request->file->getClientOriginalName();
$file->file = '/storage/' . $file_path;
$film->update(['video' => $file_name]);
$film->update(['videoPath' => $file_path]);
return response()->json(['success'=>'File uploaded successfully.']);
}
It's because you are returning a response after you process the image file so the condition for the video can't be reached. If you want to process both just return after all the operations are done.
$request->validate([
'title'=> 'required',
'description' => 'required',
'file' => 'required|mimes:jpg,jpeg,png|max:2048',
'video' => 'required|mimes:mp4'
]);
$film= Film::create([
'title' => $request->title,
'slug' => Str::slug($request->title),
'description' => $request->description,
'user_id' => auth()->id()
]);
if($request->file('file')) {
$file_name = time().'_'.$request->file->getClientOriginalName();
$file_path = $request->file('file')->storeAs('uploads', $file_name, 'public');
$film->update([
'file' => $file_name,
'path' => $file_path
]);
}
if ($request->file('video')){
$file_name = time().'_'.$request->video->getClientOriginalName();
$file_path = $request->file('video')->storeAs('uploads', $file_name, 'public');
$film->update([
'video' => $file_name,
'videoPath' => $file_path
]);
}
return response()->json(['success'=>'Files uploaded successfully.']);
You can also add additional checks if the files inside each condition is processed successfully.
The $file variable is unnecessary and it's not even saved so that can be removed as well.
As for the reason it's uploading twice, you are calling ->file again inside the video condition which should be ->video.
And as an aside, you can update multiple fields at once by passing multiple array items instead of calling update for each property which can save you db requests.
jech chua, thanks it worked but it uploads the image twice.
maybe there a problem in my blade
<form action="/film" class="form" method="POST" enctype="multipart/form-data">
#csrf
<div class="f">
<div class="sect1">
<input type="text" class="input" name="title" placeholder="Title..">
<textarea name="description" class="textarea" placeholder="Description.."></textarea>
<h2>Upload image</h2><input type="file" name="file" class="file">
</div>
<div class="dropz" id="image-upload">
<h2>Upload video</h2>
<input type="file" name="video">
</div>
</div>
<button type="submit" class="buttn">Create film</button>
</form>

How to show error message from do_upload using codigniter

i create image module and i edit image more then 1mb then can not show errormsg.
i used codigniter fremwork.
controller:
public function edit($id) {
$this->edit_status_check($id);
$this->form_validation->set_rules('agent_name', 'Agent Name', 'required');
$this->form_validation->set_rules('mobile', 'Mobile No.', 'required');
$this->form_validation->set_rules('agent_vehicle', 'Agent Vehicle', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Edit Agent',
'page_name' => 'agent/edit',
'result' => $this->agent_model->select_id($id),
'result_vehicle' => $this->vehicle_model->list_all(),
'error' => validation_errors(),
'id' => $id
);
$this->load->view('template', $data);
} else {
$config['upload_path'] = '../uploads/agent/';
$config['allowed_types'] = 'jpg|jpeg';
$config['encrypt_name'] = TRUE;
$config['max_size'] = 1000; // 1 mb
$this->load->library('upload', $config);
if (!empty($_FILES['agent_image']['name'])) {
if ($this->upload->do_upload('agent_image')) {
$_POST['agent_img_url'] = 'uploads/agent/' . $this->upload->data('file_name');
} else {
$data = array(
'page_title' => 'Edit Agent',
'page_name' => 'agent/edit',
'result' => $this->agent_model->select_id($id),
'result_vehicle' => $this->vehicle_model->list_all(),
'error' => $this->upload->display_errors(),
'id' => $id
);
$this->load->view('template', $data);
}
}
$this->agent_model->update($_POST, $id);
alert('Update', $_POST['agent_name']);
redirect('agent');
}
}
Model:
public function update($data, $id) {
$updatedata = array(
'name' => $data['agent_name'],
'mobile' => $data['mobile'],
'password' => sha1($data['password']),
'vehicle' => $data['agent_vehicle'],
'address' => $data['agent_address'],
'category' => $data['category'],
'created_on' => date('Y-m-d h:i:sa')
);
if (!empty($data['agent_img_url'])) {
$updatedata['img_url'] = $data['agent_img_url'];
}
$this->db->where('id', $id);
$this->db->update('agent', $updatedata);
}
View:
<div class="form-group">
<img src="/<?= $result['img_url']; ?>" class="img-responsive" name="old_agent_image" width="133" height="100">
</div>
<div class="form-group">
<label>Agent Image</label>
<input type="file" name="agent_image">
</div>
MY question: I edit image for particular user then image uploaded,but if image size more then 1mb ,then image can not upload and display error message.
so my question how to show errormsg.
$uploaded = $this->upload->do_upload('file'); //'file' is input field name
if($uploaded) {
$upload_data = $this->upload->data();
// do database stuff
} else {
$data['errors'] = array("error" => $this->upload->display_errors());
}

Form inputs cannot bypass the form validation in codeigniter version 3.0.0

I am having trouble bypassing the $this->form_validation->set_rules("blah") even when i'm writing the correct inputs. (Using data exisiting in the databases). What happens is that whatever input i do, the form_validation->run() seems to always return false. Please Help Me :(
The View Part (The Form that i'm using):
<div class="navbar-form navbar-right">
<?php
$user = array('name' => 'username', 'class' => 'form-control', 'placeholder' => 'Username', 'autocomplete' => 'off');
$pass = array('name' => 'password', 'class' => 'form-control', 'placeholder' => 'Password', 'autocomplete' => 'off');
$button = array('id' => 'loginbutton', 'class' => 'form-control');
echo form_open('bigphloginc/validateUser');
?>
<div class="form-group">
<?php echo form_input($user); ?>
</div>
<div class="form-group">
<?php echo form_password($pass); ?>
</div>
<div class="form-group">
<?php
echo form_submit($button,'Login');
echo form_close();
?>
</div>
</div>
The Controller i'm Using:
public function validateUser(){
//Gets the posted values
$tempUsername = $this->input->post('username');
$tempPassword = $this->input->post('password');
//Set the rules for forms
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|md5');
if($this->form_validation->run()==FALSE){ //If the form data isn't accepted, loads back to login
redirect(bigphloginc/index);
}else{ //If form data is accepted, checks the database
if(isset($this->session->userdata($tempUsername))){
redirect(bigphloginc/index);
}else{
$this->load->model('bigphuser');
$query = $this->bigphuser->login($tempUsername,$tempPassword);
if($query==FALSE){ //If the form data doesn't exist in db, loads back to login
$this->load->view('warning');
$this->load->view('ilogin');
}else{ //If the form data exist on db, then continues to their respective pages
$data = array(
'username' => $tempUsername,
'password' => $tempPassword,
'type' => $query[0]->type,
'employeeNumber' => $query[0]->employeeNumber,
'loggedIn' => true
);
$this->session->set_userdata($data); //Sets the data to the session
if($query[0]->type=="admin"){ //if the user is an admin
redirect('bigphadmin/home');
}else if($query[0]->type=="employee"){
redirect('bigphemployee/home'); //if the user is an employee
}//Query Type
}//Query false
}
}//validation false
}
xss_clean is no longer part of form validation in codeigniter 3. The alternative is not to use it, as xss_clean is doing sanitization and not validation.
xss_clean is part of security helper.You can use it as
$this->load->helper('security');
$value = $this->input->post('formvalue', TRUE); //TRUE enables the xss filtering
Check this link for more detail

CodeIgniter: How can I store a photo name into database

I had looked for many examples about it and I did something as I can do.
I will build a registration form. There will be five text fields and also a photo upload section.
what I did
The text fields are stored in the database. In here only one field is shown. (successfully)
The photo is stored in the folder after the form submitted (successfuly)
I need you to help me
The name of the photo is not stored in the database. it is stored on the folder.
The codes below.
Model
public function registration($post)
{
$this->db->insert('registration', $post);
}
Controller
function do_upload()
{
$post = $this->input->post();
$this->form_validation->set_rules('Name','Name','trim|required|xss_clean');
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('example/registration_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$result = $this->register_model->registration($post);
$this->load->view('upload_success', $data, $result);
}
}
View
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="userfile" size="20" />
<br />
<input type="text" name="name" class="form-control" placeholder="Your name">
<input type="submit" value="upload" />
</form>
It is photo_name on the database. It will be written on controller or model? How do I do in basically?
You need to use a variable for $this->do_upload->data() if you would like to insert content into database.
Example: $data_file = $this->do_upload->data();
Example: $data_file['file_name']
$data = array(
'file_name' => $data_file['file_name'],
'file_type' => $data_file['file_type'],
'full_path' => $data_file['full_path'],
'raw_name' => $data_file['raw_name'],
'orig_name' => $data_file['orig_name'],
'client_name' => $data_file['client_name'],
'file_ext' => $data_file['file_ext'],
'file_size' => $data_file['file_size'],
'is_image' => $data_file['is_image'],
'image_width' => $data_file['image_width'],
'image_height' => $data_file['image_height'],
'image_type' => $data_file['image_type'],
'image_size_str' => $data_file['image_size_str']
);
$this->db->where('whatever', $whatever);
$this->db->update('tablename', $data);
Or
$data = array(
'file_name' => $data_file['file_name'],
'file_type' => $data_file['file_type'],
'full_path' => $data_file['full_path'],
'raw_name' => $data_file['raw_name'],
'orig_name' => $data_file['orig_name'],
'client_name' => $data_file['client_name'],
'file_ext' => $data_file['file_ext'],
'file_size' => $data_file['file_size'],
'is_image' => $data_file['is_image'],
'image_width' => $data_file['image_width'],
'image_height' => $data_file['image_height'],
'image_type' => $data_file['image_type'],
'image_size_str' => $data_file['image_size_str']
);
$this->db->insert('tablename', $data);

Error on passing data from controller to view of Codeigniter

I am facing a wired problem for more than 2 hours. I couldn't figured it out. I am trying to pass the variable "errors" from model to view but when I try to load the page it shows error saying "undefined variable: errors". I am trying to build a "register" page for registering new users.
Here is my controller for register
function register(){
if($_POST){
$config = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|min_length[3]|is_unique[users.username]'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[5]'
),
array(
'field' => 'password2',
'label' => 'Password Confirm',
'rules' => 'trim|required|min_length[5]|matches[password]'
),
array(
'field' => 'user_type',
'label' => 'User Type',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|is_unique[users.email]|valid_email'
)
);
$this->load->library('form_validation');
$this->form_validation->set_rules($config);
if($this->form_validation->run() == FALSE){
$data['errors'] = validation_errors();
}else{
$data_array = array(
'username' => $_POST['username'],
'password' => sha1($_POST['password']),
'email' => $_POST['email'],
'user_type' => $_POST['user_type']
);
$this->load->model('user');
$userid = $this->user->create_user($data_array);
$this->session->set_userdata('userID', $userid);
$this->session->set_userdata('user_type',$_POST['user_type']);
redirect(base_url().'index.php/posts');
}
}
$this->load->helper('form');
$this->load->view('header');
$this->load->view('register_user');
$this->load->view('footer');
}
In above when there is a error in validation I set the error in $data['errors'] array.
The view is given below
<h2>Register User</h2>
<?php if($errors): ?>
<div style="background:red;color:white;">
<?php echo $errors; ?>
</div>
<?php endif; ?>
But when I open the register page on browser, it shows the error saying "Undefined variable: errors". Can anyone tell me where I have done wrong?
You are not passing any data to your views. You can use the 2nd parameter to pass data to your views so rather than doing
$this->load->view('header');
$this->load->view('register_user');
$this->load->view('footer');
You want to do
$aData['errors']
$this->load->view('header', $aData);
$this->load->view('register_user', $aData);
$this->load->view('footer', $aData);
Then when you are in your view you can do
<h2>Register User</h2>
<?php if($errors): ?>
<div style="background:red;color:white;">
<?php echo $errors; ?>
</div>
<?php endif; ?>

Resources