How to Make Image upload optional in codeigniter? - codeigniter

There is a form that has 4 text fields, Name, Mobile, Email & Image. However Image field is optional. When I submit the data without inserting an image it shows "You did not select a file to upload". How to solve it.
My controller function is:
public function addAgent(){
$this->form_validation->set_rules('AgentName','AgentName','required');
$this->form_validation->set_rules('mobile','mobile','required');
$this->form_validation->set_rules('email', 'email', 'required');
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('registerMessage',errors(),':old:');
redirect(base_url());
}else{
$config['upload_path'] = './uploads';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 50000;
$config['max_width'] = 10240;
$config['max_height'] = 7680;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('image'))
{
$this->session->set_flashdata('registerMessage',$this->upload->display_errors(),':old:');
redirect(base_url());
}
else
{
$dataUpload = $this->upload->data();
$filename = $dataUpload['file_name'];
}
}
$data = array(
'AgentName' => $this->input->post('AgentName'),
'mobile' => $this->input->post('mobile'),
'image' => $filename,
'email' => $this->input->post('email')
);
$this->general_model->insert('agent',$data);
$this->session->set_flashdata('registerMessage','AddedSuccessfully',':old:');
redirect(base_url());
}

Check if the file array for that key image is populated and if it has a tmp_name:
public function addAgent() {
$this->form_validation->set_rules('AgentName', 'AgentName', 'required');
$this->form_validation->set_rules('mobile', 'mobile', 'required');
$this->form_validation->set_rules('email', 'email', 'required');
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('registerMessage', errors(), ':old:');
redirect(base_url());
}
$filename = ''; // init as blank otherwise notice
if (isset($_FILES['image']) && !empty($_FILES['image']['tmp_name'])) {
$config['upload_path'] = './uploads/'; // should have slash at end
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 50000;
$config['max_width'] = 10240;
$config['max_height'] = 7680;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('image')) {
$this->session->set_flashdata('registerMessage', $this->upload->display_errors(), ':old:');
redirect(base_url());
} else {
$dataUpload = $this->upload->data();
$filename = $dataUpload['file_name'];
}
}
$data = array(
'AgentName' => $this->input->post('AgentName'),
'mobile' => $this->input->post('mobile'),
'image' => $filename,
'email' => $this->input->post('email')
);
$this->general_model->insert('agent', $data);
$this->session->set_flashdata('registerMessage', 'AddedSuccessfully', ':old:');
redirect(base_url());
}

Related

File Name Not Changing in Database but Changing in Assets folder in file upload of Codeigniter

my model
public function saveProduct(
$name,
$cat_id,
$user_id,
$description,
$status
) {
$post_image = '';
if (array_key_exists('post_image', $_FILES)) {
$config = [];
$config['upload_path'] = './assets/uploads/products';
$config['allowed_types'] = 'gif|svg|jpg|png|jpeg';
$config['max_size'] = '2048';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('post_image')) {
echo $this->upload->display_errors();
} else {
$post_image = $_FILES['post_image']['name'];
}
}
$data = [
'name' => $name,
'user_id' => $user_id,
'cat_id' => $cat_id,
'description' => $description,
'status' => 'active'
];
if ($post_image) {
$data['post_image'] = $post_image;
}
$this->db->insert('p0_products', $data);
return true;
}
it is changing file name to encryption in folder but in mysql i'am getting file name same as old name with unchanged on non-encrypted format
It's because you're taking from $_FILES veriable. You should take from
$this->upload->data()
So how?
$fileData = $this->upload->data();
This will return
file_name
file_type
file_path
etc.
$fileName = $fileData['file_name']

Codeigniter news image resize

How to resize the news picture? I never could.
My problem [source_image]
I use Codeigniter 3.1.6
Controller
public function insert_news() {
$config['upload_path'] = 'uploads/news/';
$config['allowed_types'] = 'gif|jpg|png';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ($this->upload->do_upload('news_image'))
{
$image = $this->upload->data();
$image_url = $image['file_name'];
$db_insert ='upload/news/'.$image_url.'';
$data=array(
'news_title' => $this->input->post('news_title'),
'news_content' => $this->input->post('news_content'),
'news_image' => $db_insert,
'news_sef'=>sef($this->input->post('news_title'))
);
$this->load->model('vt');
$result = $this->vt->insert_news($data);
if ($result) {
echo "yes";
} else {
echo "no";
}
}
}
You can try this solution for your problem :
Controller :
<?php
public function insert_news() {
$config['upload_path'] = 'uploads/news/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '20240000245';
$config['overwrite'] = TRUE;
$config['encrypt_name'] = TRUE;
// You can change width & height
$imgage_width= 60;
$imgage_height= 60;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload($field)) {
$error = $this->upload->display_errors();
// uploading failed. $error will holds the errors.
$this->form_validation->set_message('error',$error);
return FALSE;
} else {
$fdata = $this->upload->data();
$configer = array(
'image_library' => 'gd2',
'source_image' => $fdata['full_path'],
'maintain_ratio' => TRUE,
'width' => $imgage_width,
'height' => $imgage_height,
);
// Load Image Lib Library
$this->load->library('image_lib');
$this->image_lib->clear();
$this->image_lib->initialize($configer);
$this->image_lib->resize();
$img_data ['path'] = $config['upload_path'] . $fdata['file_name'];
// uploading successfull, now do your further actions
$data=array(
'news_title' => $this->input->post('news_title'),
'news_content' => $this->input->post('news_content'),
'news_image' => $img_data ['path'],
'news_sef'=>sef($this->input->post('news_title'))
);
$this->load->model('vt');
$result = $this->vt->insert_news($data);
if ($result) {
$this->form_validation->set_message('success',"News has been added successfully.");
redirect('contorller/action_name');
} else {
$this->form_validation->set_message('error',"Error in aading news");
redirect('contorller/action_name');
}
}
}
?>
I Hope it will Help you.

how to do image upload in codeigniter?

I am trying to upload an image in root folder and its file name in database. here is what I did for the upload function:
public function add_blog($id=0){
if(!empty($_FILES['picture']['name'])){
$config['upload_path'] = 'uploads/blog_image';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['picture']['name'];
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
// print_r($value['name'][$s]);exit;
if($this->upload->do_upload('picture')){
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
print_r($picture); exit;
}
}
print_r($config['file_name']); exit;
$data['blog_data']=array('blog_post'=>$this->input->post('blog_post'),
'posted_by'=>$this->input->post('posted_by'),
'blog_image'=>$picture);
if ($id==0){
$this->db->insert('blog',$data['blog_data']);
// $last_id = $this->db->insert_id();
}
else {
$this->db->where('id',$id);
// $last_id = $this->db->insert_id();
$this->db->update('blog',$data['blog_data']);
}
}
problem here is i am being able to insert other data except image. I get the image name with that print_r($config[file_name]) if i do print_r() and exit, if not it will just insert other data except image. But the image is neither uploaded in root folder nor its name in database. If I give the non existing upload path, then also its not throwing any error. I think code inside If is not executed. How can i solve this ? Thanks in advance.
private function _upload_image( ) {
$this->load->library( 'upload' );
if ($_FILES && $_FILES['picture']['name'] !== ""){
$config['upload_path'] = 'uploads/blog_image';
$config['allowed_types'] = 'jpg|jpeg|png|bmp';
$config['max_size'] = 10000;
/*the picture name must be unique, use function now()*/
$config['file_name'] = $_FILES['picture']['name'] . now();
$config['file_ext_tolower'] = TRUE;
$this->upload->initialize( $config );
if ( $this->upload->do_upload( 'picture' ) ){
$file_name = $this->upload->data()['file_name'];
$full_path = $this->upload->data()['full_path'];
/*If you want create a thumb, use this part*/
$this->load->library('image_lib');
$config = array(
'source_image' => $path,
'new_image' => $this->_image_path,
'maintain_ratio' => true,
'width' => 128,
'height' => 128,
'create_thumb' => TRUE,
'thumb_marker' => '_thumb',
);
$this->image_lib->initialize( $config );
$this->image_lib->resize();
/*Save in database*/
$this->db->insert('blog', [
'file_name' => $file_name,
'full_path' => $full_path
]);
} else {
//if picture is empty, do something
}
}
}
You do not need to use $_FILES && $_FILES ['picture']['name']! == "" only if your form has the picture field as an optional field, $this->upload->do_upload('picture') and get data from $this->upload->data(), read the manual
public function add_blog()
{
$config['upload_path'] = '.uploads/blog_image';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = 10000;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('picture'))
{//Do something with errors
$errors = $this->upload->display_errors();
}
else
{
$data = $this->upload->data();
$this->db->insert('blog', [
'file_name' => $data['file_name'],
'full_path' => $data['full_path']
]);
}
}
I just didn't mention the file size to be uploaded. I did this in my above code and worked.
EDIT
public function add_blog($id=0){
if(!empty($_FILES['picture']['name'])){
$config['upload_path'] = 'uploads/blog_image';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = 0;
$config['file_name'] = $_FILES['picture']['name'];
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
// print_r($value['name'][$s]);exit;
if($this->upload->do_upload('picture')){
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
// print_r($picture); exit;
}
}
// print_r($config['file_name']); exit;
$data['blog_data']=array('blog_post'=>$this->input->post('blog_post'),
'posted_by'=>$this->input->post('posted_by'),
'blog_image'=>$picture);
if ($id==0){
$this->db->insert('blog',$data['blog_data']);
// $last_id = $this->db->insert_id();
}
else {
$this->db->where('id',$id);
// $last_id = $this->db->insert_id();
$this->db->update('blog',$data['blog_data']);
}
}
And this code works for both insert and update.

codeigniter success insert to database but failed to insert uploaded file

I'm new here, so nice to meet you all.
I have trouble with codeigniter.
Maybe hard to tell so I will show all of my code :
my controller :
function upload_barang(){
$this->admin_model->login();
$this->admin_model->valid_product();
$config['upload_path'] = './produk/';
$config['allowed_types'] = 'jpg';
$config['max_size'] = '100';
$config['max_width'] = '400';
$config['max_height'] = '400';
$this->load->library('upload',$config);
$data['query'] = $this->db->get('kategori');
if($this->form_validation->run() == FALSE && ! $this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
$data['success'] = '';
$this->load->view('backoffice/tambahbarang',$data);
} else {
$upload_data = $this->upload->data();
$data['error'] = '';
$data = array(
'idkategori' => $this->input->post('idkategori'),
'namabarang' => $this->input->post('nbarang'),
'image' => $upload_data['file_name'],
'status' => 1
);
$data_insert = $this->db->insert('barang',$data);
if($data_insert == TRUE) {
$data['query'] = $this->db->get('kategori');
$query = $this->db->get('barang');
$rows = $query->row();
$data['idbarang'] = $rows->idbarang;
$harga = array(
'idbarang' => $data['idbarang'],
'satuan' => $this->input->post('stcbarang'),
'harga' => $this->input->post('hbarang')
);
$this->db->insert('hargabarang',$harga);
$data['success'] = '<b>Barang Telah Ditambahkan</b>';
$this->load->view('backoffice/tambahbarang',$data);
} else {
$data['success'] = '<b>Barang Gagal Ditambahkan</b>';
$this->load->view('backoffice/tambahbarang',$data);
}
}
}
This code success insert all of data to database, except on column 'image' that I fill with '$upload_data['file_name']' this empty on my database.
what's wrong with my code?
please help thanks
You can use this format:
/*
* ------- Start Image Upload---------
*/
$config['upload_path'] = 'image/product_images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '400';
$config['max_height'] = '400';
$this->load->library('upload', $config);
$this->upload->initialize($config);
$error='';
$fdata=array();
if ( ! $this->upload->do_upload('product_image'))
{
$error = $this->upload->display_errors();
echo $error;
exit();
}
else
{
$fdata = $this->upload->data();
$data['product_image']=$config['upload_path'] .$fdata['file_name'];
}
/*
* --------End Image Upload---------
*/
$this->super_admin_model->save_product_info($data);

how to pass array from controller to view in codeigniter

i want to upload file in codeigniter and want to show error in view file but display error array is not displaying at view file. when uploading file is failed, relevant error is not display at view
function add_model()
{
$this->checkuser();
if(isset($_POST['add_model']))
{
$config['upload_path'] = 'uploads/model/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['file_name'] = rand(1111, 99999).'_'.$_FILES['userfile']['name'];
$config['overwrite'] = TRUE;
$config['encrypt_name'] = TRUE;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$mDate = date('Y-m-d H:i:s');
$this->form_validation->set_rules('model_name', 'Model Name', 'trim|xss_clean|required');
$this->form_validation->set_rules('model_slug', 'Model Slug', 'trim|xss_clean|required');
if($this->form_validation->run() && $this->upload->do_upload())
{
$temp = $this->upload->data('userfile');
$model_image = $temp['file_name'];
$data = array(
'model_name' => $this->input->post('model_name'),
'model_image' => $model_image,
'brand_id' => $this->input->post('brand_id'),
'model_slug' => $this->toAscii($this->input->post('model_slug'))
);
$this->model_model->addmodel($data);
redirect('admin/model/model_listing');
}
else
{
$data['errors'] = array('error' => $this->upload->display_errors());
$data['brands'] = $this->model_model->allbrand();
$data['page_title'] = 'Add Content';
$this->load->view('admin/add_model', $data);
}
}
else
{
$data['errors'] = $this->upload->display_errors();
$data['brands'] = $this->model_model->allbrand();
$data['page_title'] = 'Add Content';
$this->load->view('admin/add_model', $data);
}
}
given below is the code of view file where i want to show error
<?php
if(validation_errors())
{
echo validation_errors('<div class="alert alert-error">', '</div>');
echo '<div class="alert alert-error">'.$error.'</div>';
}
if($errors)
{
foreach ($errors as $error)
{
echo '<div class="alert alert-error">'.$error.'</div>';
}
}
?>
i am using both validation error and display error at the same time
change this if condition
if($this->form_validation->run() && $this->upload->do_upload())
{
to this
if($this->form_validation->run() && $this->upload->do_upload('name'))
{
do_upload function requires name of field to upload image..

Resources