Codeigniter 3 blog application: update() method deletes thumbnail - codeigniter

I am working on a basic blog application in Codeigniter 3.1.8.
There is a create post and an update post functionality.
When a post is created, there is the option to upload a post thumbnail, else a default image is displayed. In the post controller there is the method for creating posts:
public function create() {
// More code here
if($this->form_validation->run() === FALSE){
$this->load->view('partials/header', $data);
$this->load->view('create');
$this->load->view('partials/footer');
} else {
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = 'default.jpg';
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
$this->Posts_model->create_post($post_image);
redirect('posts');
}
}
There is a method for updating posts:
public function update() {
// Form data validation rules
// irrelevant for the question suppressed
$id = $this->input->post('id');
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
$data = array('upload_data' => $this->upload->data());
$this->upload->do_upload();
$post_image = $_FILES['userfile']['name'];
if ($this->form_validation->run()) {
$this->Posts_model->update_post($id, $post_image);
redirect('posts/post/' . $id);
} else {
$this->edit($id);
}
}
In the Posts_model model:
public function update_post($id, $post_image) {
$data = [
'title' => $this->input->post('title'),
'description' => $this->input->post('desc'),
'content' => $this->input->post('body'),
'post_image' => $post_image,
'cat_id' => $this->input->post('category')
];
$this->db->where('id', $id);
return $this->db->update('posts', $data);
}
The edit post view:
<?php echo form_open_multipart(base_url('posts/update')); ?>
<input type="hidden" name="id" id="pid" value="<?php echo $post->id; ?>">
<div class="form-group <?php if(form_error('title')) echo 'has-error';?>">
<input type="text" name="title" id="title" class="form-control" placeholder="Title" value="<?php echo $post->title; ?>">
<?php if(form_error('title')) echo form_error('title'); ?>
</div>
<div class="form-group <?php if(form_error('desc')) echo 'has-error';?>">
<input type="text" name="desc" id="desc" class="form-control" placeholder="Short decription" value="<?php echo $post->description; ?>">
<?php if(form_error('desc')) echo form_error('desc'); ?>
</div>
<div class="form-group <?php if(form_error('body')) echo 'has-error';?>">
<textarea name="body" id="body" cols="30" rows="5" class="form-control" placeholder="Add post body"><?php echo $post->content; ?></textarea>
<?php if(form_error('body')) echo form_error('body'); ?>
</div>
<div class="form-group">
<select name="category" id="category" class="form-control">
<?php foreach ($categories as $category): ?>
<?php if ($category->id == $post->cat_id): ?>
<option value="<?php echo $category->id; ?>" selected><?php echo $category->name; ?></option>
<?php else: ?>
<option value="<?php echo $category->id; ?>"><?php echo $category->name; ?></option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<label for="postimage">Upload an image</label>
<div class="form-group">
<input type="file" name="userfile" id="postimage" size="20">
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-block btn-md btn-success">
</div>
<?php echo form_close(); ?>
The problem with the update() method is that, when editing a post, unless I replace it's existing thumbnail with a new one (in other words, if I let the file upload field empty), results in leaving the post without a thumbnail:
<img src="http://localhost/ciblog/assets/img/posts/">
What I have tried (not the best idea, I admit) is to fetch the name pg the file already existing in the posts table this way:
$data['post'] = $this->Posts_model->get_post($id);
$post_image = $data['post']->post_image;
But it gives the error Trying to get property of non-object.
What am I doing wrong?

Solved it:
In the edit post form, I have added an input of type hidden above the file input, in order to "capture" the posts image from the database:
<input type="hidden" name="postimage" id="postimage" value="<?php echo $post->post_image; ?>">
<label for="postimage">Upload an image</label><div class="form-group">
<input type="file" name="userfile" id="postimage" size="20">
</div>
In the Posts controller, I have replaced
$data = array('upload_data' => $this->upload->data());
$this->upload->do_upload();
$post_image = $_FILES['userfile']['name'];
with:
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = $this->input->post('postimage');
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
The code above means: if no new image is uploaded, write the name of the existing one in the posts table again, instead of writing nothing. If instead a new photo is uploaded, write the name of the new photo.

Related

page blashes while redirecting a form with codeigniter

I am learning to develop with codeigniter 3.1.8, for that I am confronted with a problem: I am confronted with a problem: I am redirected in a blank page and my errors do not display. please I would like to give you a hand
here is the function of the model for insertion
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class M_root extends CI_Model{
function isertion_root(){
$root=array(
'nom_admin'=>'$user_name',
'prenom_admin'=>'$user_prenom',
'email_admin'=>'$user_email',
'date_nais_admin'=>'$date_nais',
'date_inscription_admin'=>'NOW(),false',
'avatar_root'=>'$avatar_root',
'password_root'=>'$pssword_root'
);
$this->db->insert('root', $root);
}
/**
* #param $email
* #param $password
* #return bool
*/
function login_root($email,$password){
$this->db->select('*');
$this->db->from('root');
$this->db->where('email_admin',$email);
$this->db->where('password_root',$password);
if ($query=$this->db->get())
{
return $query->row_array();
}
else{
return false;
}
}
public function email_check($email_admin){
$this->db->select('*');
$this->db->from('root');
$this->db->where('email_admin',$email_admin);
$query=$this->db->get();
if($query->num_rows()>0){
return false;
}else{
return true;
}
}
}
here is the function of the controller for insertion
class Root extends CI_Controller{
function __construct(){
parent:: __construct();
$this->load->database();
$this->load->model('M_root');
$this->load->library('upload');
$this->load->library('form_validation');
$this->load->helper(array('form', 'url'));
$this->load->library('session');
}
public function index()
{
$this->load->view("register.php");
}
//debut fonction d'enregistrement
public function isertion_root(){
if($this->input->post('registersubmit')){
$config['upload_path'] = './assets/avatar-root/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->upload->initialize($config);
if(!empty($_FILES['filefoto']['name']))
{
if ($this->upload->do_upload('filefoto'))
{
$gbr = $this->upload->data();
//Compress Image
$config['image_library']='gd2';
$config['source_image']='./assets/avatar-root/'.$gbr['file_name'];
$config['create_thumb']= FALSE;
$config['maintain_ratio']= FALSE;
$config['quality']= '60%';
$config['new_image']= './assets/avatar-root/'.$gbr['file_name'];
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$this->form_validation->set_rules('nom_admin', 'nom administrateur', 'trim|required|min_length[3]|max_length[23]|alpha_dash|encode_php_tags|xss_clean');
$this->form_validation->set_rules('prenom_admin', 'prenom administrateur', 'trim|required|alpha_dash|encode_php_tags|xss_clean');
$this->form_validation->set_rules('email_admin', 'Email administrateur', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('date_nais_admin', 'Date de naissance administateur', 'trim|required');
$this->form_validation->set_rules('avatar_root', 'Avatar root', 'trim|required');
$this->form_validation->set_rules('password_root', 'password root', 'trim|required|min_length[8]|xss_clean');
$this->form_validation->set_rules('conf_password', 'confirm password', 'trim|required|matches[password]');
$root = array(
'nom_admin' => strip_tags($this->input->post('nom_admin')),
'prenom_admin' => strip_tags($this->input->post('prenom_admin')),
'email_admin' => strip_tags($this->input->post('email_admin')),
'date_nais_admin' => strip_tags($this->input->post('date_nais_admin')),
'avatar_root' => strip_tags($this->input->post('avatar_root')),
'password_root' => password_hash($this->input->post('password'),PASSWORD_DEFAULT)
);
print_r($root);
if ($this->form_validation->run() == TRUE)
{
$email_check=$this->M_root->email_check($root['email_admin']);
if($email_check){
$this->M_root->isertion_root($root);
$this->session->set_flashdata('success_msg', 'Registered successfully.Now login to your account.');
redirect('root/login_view');
}
}
else{
$this->load->view('register');
}
}
}
}
}
//fin fonction d'enregistrement
view
<span style="background-color:red;">
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Creation d'un compte</h3>
</div>
<div class="panel-body">
<p class="alert-danger"><?php
$error_msg=$this->session->flashdata('error_msg');
if($error_msg){
echo $error_msg;
}
?></p>
<?php echo validation_errors(); ?>
<form role="form" method="post" enctype="multipart/form-data" autocomplete="off" action="<?php echo base_url().'Root/isertion_root'?>">
<fieldset>
<div class="form-group">
<?php echo form_error('nom_admin'); ?>
<input class="form-control" placeholder="Votre nom" name="nom_admin" value="<?php echo set_value('nom_admin'); ?>"type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Votre prenom" name="prenom_admin" type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="E-mail" name="email_admin" type="email" autofocus>
</div>
<div class="form-group">
<div class="form-group">
<input class="form-control" placeholder="votre date de naissance" name="date_nais_admin" type="date" value="">
</div>
<div class="form-group">
<input class="form-control" placeholder="mot de passe " name="password_root" type="password" value="">
</div>
<div class="form-group">
<input class="form-control" placeholder="confirmez votre mot de passe" name="conf_password" type="password" value="">
</div>
<div class="form-group">
<input class="form-control" placeholder="votre photo" name="avatar_root" type="file" value="">
</div>
<input class="btn btn-lg btn-success btn-block" type="submit" value="Register" name="registersubmit" >
</fieldset>
</form>
<center><b>Already registered ?</b> <br></b>Login here</center><!--for centered text-->
</div>
</div>
</div>
</div>
</div>
</span>
Once i faced with this same problem i rectified by using this please try this.
ini_set('display_errors', 1);
Your original code contained many ifs and no elses. This mean if an if condition evaluates to false there is no reason for anything to be displayed.
This is a better way of doing it. If you keep everything all in one function and avoid redirects you can properly repopulate the input fields when an error occurs either from form validation or image uploading.
public function index() {
if ($this->input->post('registersubmit')) {
$this->form_validation->set_rules('nom_admin', 'nom administrateur', 'trim|required|min_length[3]|max_length[23]|alpha_dash|encode_php_tags|xss_clean');
$this->form_validation->set_rules('prenom_admin', 'prenom administrateur', 'trim|required|alpha_dash|encode_php_tags|xss_clean');
$this->form_validation->set_rules('email_admin', 'Email administrateur', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('date_nais_admin', 'Date de naissance administateur', 'trim|required');
$this->form_validation->set_rules('avatar_root', 'Avatar root', 'trim|required');
$this->form_validation->set_rules('password_root', 'password root', 'trim|required|min_length[8]|xss_clean');
$this->form_validation->set_rules('conf_password', 'confirm password', 'trim|required|matches[password]');
if ($this->form_validation->run()) {
$this->load->library('upload');
$config['upload_path'] = './assets/avatar-root/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->upload->initialize($config);
if ($this->upload->do_upload('filefoto')) {
$gbr = $this->upload->data();
//Compress Image
$config['image_library'] = 'gd2';
$config['source_image'] = './assets/avatar-root/' . $gbr['file_name'];
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = FALSE;
$config['quality'] = '60%';
$config['new_image'] = './assets/avatar-root/' . $gbr['file_name'];
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$root = array(
'nom_admin' => strip_tags($this->input->post('nom_admin')),
'prenom_admin' => strip_tags($this->input->post('prenom_admin')),
'email_admin' => strip_tags($this->input->post('email_admin')),
'date_nais_admin' => strip_tags($this->input->post('date_nais_admin')),
'avatar_root' => strip_tags($this->input->post('avatar_root')),
'password_root' => password_hash($this->input->post('password'), PASSWORD_DEFAULT)
);
// i have a feeling you are checking if an email already exists here
// you can use form validations is_unique function in the rules above and forgo this
if ($this->M_root->email_check($root['email_admin'])) {
$this->M_root->isertion_root($root);
$this->session->set_flashdata('success_msg', 'Registered successfully.Now login to your account.');
redirect('root/login_view');
} else {
$this->session->set_flashdata('error_msg', 'bad email');
}
} else {
$this->session->set_flashdata('error_msg', $this->upload->display_errors());
}
}
}
$this->load->view("register.php");
}
You just have to change your form action to be blank so it submits to the same page.
Also in each input value except passwords you should do something like this:
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />
This way the user won't lose their input when natural errors occur due to them entering wrong information or whatever.

get selected form_dropdown codeigniter from database

i am new with codeigniter, and i am trying to set selected value from database,
this code doesn't work,
<?php
$options = array(
'one' => 'one',
'two' => 'two',
);
$selected = $teach->number;
echo form_dropdown('number', $options, $selected);
?>
but when i try to manual, it work.
<?php
$options = array(
'one' => 'one',
'two' => 'two',
);
$selected = 'one';
echo form_dropdown('number', $options, $selected);
?>
I don't know why,
Any advice would be great. Thanks
this my controller
public function index() {
$this->load->helper('url');
$id = $this->uri->segment(3);
$this->data['teach'] = $this->EditTeachModel->getPosts(); // calling Post model method getPosts()
$this->data['singleTeach'] = $this->EditTeachModel->getPostsId($id); // calling Post model method getPosts()
//view
$this->load->view('edit_teach', $this->data); // load the view file , we are passing $data array to view file
}
public function update(){
$id = $this->input->post('kd');
$this->load->library('form_validation');
$data = array(
'kd' => $this->input->post('kd'),
'name' => $this->input->post('name'),
'date' => $this->input->post('date'),
'number' => $this->input->post('number'),
'pass' => $this->input->post('pass')
);
$this->EditTeachModel->updatePosts($id, $data);
$this->index();
}
This my model
public function getPosts(){
$this->db->from('teach');
$query = $this->db->get();
return $query->result();
}
public function getPostsId($data){
$this->db->select('*');
$this->db->from('teach');
$this->db->where('kd', $data);
$query = $this->db->get();
$result = $query->result();
return $result;
}
public function updatePosts($id, $data){
$this->db->where('kd', $id);
$this->db->update('teach', $data);
}
this my view
<?php foreach($singleTeach as $teach) {?>
<form method="post" action="<?php echo base_url() . "edit_teach/update"?>">
<div class="card-body"><td>
<div class="row">
<div class="col-6">
<div class="form-group">
<label id="kd">Kode :</label>
<input type="text" id="kd" name="kd" class="form-control" value="<?php echo $teach->kd; ?>">
</div>
<div class="form-group">
<label id="name">Nama:</label>
<input type="text" id="name" name="name" class="form-control" value="<?php echo $teach->name; ?>">
</div>
<div class="form-group">
<label id="date">Date :</label>
<input type="text" id="date" name="date" class="form-control" value="<?php echo $teach->date; ?>">
</div>
<div class="form-group">
<?php echo form_label('Number '); ?> <?php echo form_error('number'); ?>
<?php
$options = array(
'one' => 'one',
'two' => 'two',
);
$selected = $teach->number;
print_r($teach);
echo form_dropdown('number', $options, $selected);
?>
</div>
<div class="form-group">
<label id="pass">Password :</label>
<input type="text" id="pass" name="pass" class="form-control" value="<?php echo $teach->pass; ?>">
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<?php echo form_submit(array('id' => 'submit','class'=> 'btn btn-primary', 'value' => 'Submit')); ?>
</div>
</form>
<?php } ?>

retrive two uploaded images in two separate pages of a same web page

This is my controller with index function and index2 function to upload two images
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Upload_Files extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->model('file');
}
function index(){
$data = array();
if($this->input->post('fileSubmit') && !empty($_FILES['userFiles']['name'])){
$filesCount = count($_FILES['userFiles']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['userFile']['name'] = $_FILES['userFiles']['name'][$i];
$_FILES['userFile']['type'] = $_FILES['userFiles']['type'][$i];
$_FILES['userFile']['tmp_name'] = $_FILES['userFiles']['tmp_name'][$i];
$_FILES['userFile']['error'] = $_FILES['userFiles']['error'][$i];
$_FILES['userFile']['size'] = $_FILES['userFiles']['size'][$i];
$uploadPath = 'uploads/files/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('userFile')){
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['created'] = date("Y-m-d H:i:s");
$uploadData[$i]['modified'] = date("Y-m-d H:i:s");
}
}
if(!empty($uploadData)){
//Insert file information into the database
$insert = $this->file->insert($uploadData);
$statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
$this->session->set_flashdata('statusMsg',$statusMsg);
}
}
//Get files data from database
$data['files'] = $this->file->getRows();
//Pass the files data to view
$this->load->view('upload_files', $data);
}
function index2(){
$data = array();
if($this->input->post('fileSubmit2') && !empty($_FILES['userFiles']['name'])){
$filesCount = count($_FILES['userFiles']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['userFile']['name'] = $_FILES['userFiles']['name'][$i];
$_FILES['userFile']['type'] = $_FILES['userFiles']['type'][$i];
$_FILES['userFile']['tmp_name'] = $_FILES['userFiles']['tmp_name'][$i];
$_FILES['userFile']['error'] = $_FILES['userFiles']['error'][$i];
$_FILES['userFile']['size'] = $_FILES['userFiles']['size'][$i];
$uploadPath = 'uploads/index2/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('userFile')){
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['created'] = date("Y-m-d H:i:s");
$uploadData[$i]['modified'] = date("Y-m-d H:i:s");
$uploadData[$i]['divid'] =2;
}
}
if(!empty($uploadData)){
//Insert file information into the database
$insert = $this->file->insert($uploadData);
$statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
$this->session->set_flashdata('statusMsg',$statusMsg);
}
}
//Get files data from database
$data['files'] = $this->file->getRows2();
//Pass the files data to view
$this->load->view('upload_files', $data);
}
}
This is my model to retrieve images from databases
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class File extends CI_Model{
public function getRows($id = ''){
$this->db->select('id,file_name,created');
$this->db->from('files');
if($id){
$this->db->where('divid',1);
$query = $this->db->get();
$result = $query->row_array();
}else{
$this->db->order_by('created','desc');
$query = $this->db->get();
$result = $query->result_array();
}
return !empty($result)?$result:false;
}
public function insert($data = array()){
$insert = $this->db->insert_batch('files',$data);
return $insert?true:false;
}
public function getRows2($id = ''){
$this->db->select('id,file_name,created');
$this->db->from('files');
if($id){
$this->db->where('divid',2);
$query = $this->db->get();
$result = $query->row_array();
}else{
$this->db->order_by('created','desc');
$query = $this->db->get();
$result = $query->result_array();
}
return !empty($result)?$result:false;
}
public function insert2($data = array()){
$insert = $this->db->insert_batch('files',$data);
return $insert?true:false;
}
}
This is my view to upload 2 images and view those 2 images
<div class="container">
<div class="row">
<p><?php echo $this->session->flashdata('statusMsg'); ?></p>
<form enctype="multipart/form-data" action="<?php echo site_url('Upload_Files/index'); ?>" method="post">
<div class="form-group">
<label>Choose Files1</label>
<input type="file" class="form-control" name="userFiles[]" multiple/>
</div>
<div class="form-group">
<input class="form-control" type="submit" name="fileSubmit" value="UPLOAD"/>
</div>
</form>
</div>
<div class="row">
<ul class="gallery">
<?php if(!empty($files)): foreach($files as $file): ?>
<li class="item">
<img src="<?php echo base_url('uploads/files/'.$file['file_name']); ?>" alt="" >
<p>Uploaded On <?php echo date("j M Y",strtotime($file['created'])); ?></p>
</li>
<?php endforeach; else: ?>
<p>Image(s) not found.....</p>
<?php endif; ?>
</ul>
</div>
</div>
<div class="container">
<div class="row">
<p><?php echo $this->session->flashdata('statusMsg'); ?></p>
<form enctype="multipart/form-data" action="<?php echo site_url('Upload_Files/index2'); ?>" method="post">
<div class="form-group">
<label>Choose Files1</label>
<input type="file" class="form-control" name="userFiles[]" multiple/>
</div>
<div class="form-group">
<input class="form-control" type="submit" name="fileSubmit2" value="UPLOAD"/>
</div>
</form>
</div>
<div class="row">
<ul class="gallery">
<?php if(!empty($files)): foreach($files as $file): ?>
<li class="item">
<img src="<?php echo base_url('uploads/index2/'.$file['file_name']); ?>" alt="" >
<p>Uploaded On <?php echo date("j M Y",strtotime($file['created'])); ?></p>
</li>
<?php endforeach; else: ?>
<p>Image(s) not found.....</p>
<?php endif; ?>
</ul>
</div>
</div>
My problem is when I upload one image it appears in the other image view also. I tried so hard and put this question 2 times in stackoverflow. If someone helps me It will be a great thing

Codeigniter:Update Image and Display

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
Controller
public function insert()
{
$data['s_em']=$this->input->post('s_em');
$data['s_na']=$this->input->post('s_na');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|jpe|pdf|doc|docx|rtf|text|txt';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('file'))
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data['file']=$this->upload->data('file_name');
}
$this->Students_m->db_ins($data);
$this->load->view('admin/newstudents');
}
public function edit($id)
{
$dt['da']=$this->Students_m->db_edit($id)->row_array();
$this->load->view('admin/st_edt',$dt);
}
public function update()
{
$id=$this->input->post("id");
$s_em=$this->input->post("s_em");
$s_na=$this->input->post("s_na");
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|jpe|pdf|doc|docx|rtf|text|txt';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('file'))
{
$error = array('error' => $this->upload- >display_errors());
}
else
{
$upload_data=$this->upload->data();
$image_name=$upload_data['file_name'];
}
$data=array('s_em'=>$s_em,'s_na'=>$s_na,'file'=>$image_name);
$this->Students_m->db_update($data,$id);
}
redirect("admin/students");
}
Model
public function db_ins($data)
{
$query=$this->db->insert('student',$data);
return $query;
}
public function db_edit($id)
{
return $this->db->get_where('student', array('id'=>$id));
}
public function db_update($data,$id)
{
$this->db->where('id', $id);
$this->db->update('student', $data);
}
view
<form action="../update" method="post" enctype="multipart/form-data">
<legend class="text-semibold">Personal data</legend>
<img src=" <?php echo base_url( 'uploads/'. $da['file']);?>" height="205" width="205">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="display-block">image:<span class="text-danger">*</span></label>
<input name="file" type="file" id="image_id" class="file-styled ">
<span class="help-block"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Email address: <span class="text-danger">*</span></label>
<input type="email" name="s_em" class="form-control required" value="<?php echo $da['s_em'];?>">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Student name: <span class="text-danger">*</span></label>
<input type="text" name="s_na" class="form-control required" value="<?php echo $da['s_na'];?>" id="n1">
</div>
</div>
<button type="submit">Update<i class="icon-check position-right"></i></button>
<input type="hidden" name="id" value="<?php echo $da['id'] ;?>">
</form>
</div>
public function update()
{
$id=$this->input->post("id");
$s_em=$this->input->post("s_em");
$s_na=$this->input->post("s_na");
if($_FILES[file]['name']!="")
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|jpe|pdf|doc|docx|rtf|text|txt';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('file'))
{
$error = array('error' => $this->upload- >display_errors());
}
else
{
$upload_data=$this->upload->data();
$image_name=$upload_data['file_name'];
}
}
else{
$image_name=$this->input->post('old');
}
$data=array('s_em'=>$s_em,'s_na'=>$s_na,'file'=>$image_name);
$this->Students_m->db_update($data,$id);
}
in the view file add the following
<input type="hidden" id="old" name="old" value="<?php echo $da['file'] ?>">
try this..let me know this works or not.
Be always careful when you upload image with a same name. It's uploaded successfully but you can't see the if changed on the front end of it has same URL and same name that is because your browser have Cached previous Image.
Make sure image is updated successfully on server first

codeIgniter form validation not working with file upload option

I am trying this code but it is not working with file upload.
When there is no file uploading field it works fine but with file upload its not working.
Please help me.
form.php
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('emp'); ?>
<form name="ajaxform" id="ajaxform" action="<?php echo base_url().'/emp/operation'?>" method="POST" enctype="multipart/form-data">
<table border="1">
<tr>
<th>Name</th>
<td><input type="text" name="name" value="<?php echo $name; ?>" size="50"/></td>
</tr>
<tr>
<th>Email </th>
<td><input type="text" name="email" value="<?php echo $email; ?>"/></td>
</tr>
<tr>
<th>Address</th>
<td><input type="text" name="address" value="<?php echo $address; ?>" /></td>
</tr>
<tr>
<th>Phone</th>
<td><input type="text" name="phone" value="<?php echo $phone; ?>" /></td>
</tr>
<tr>
<th>Photo</th>
<td><input type="file" name="userfile" /></td>
</tr>
</table>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="hidden" id="btn" value="<?php echo $submit; ?>" name="btn"/>
<input type="submit" id="simple-post" value="<?php echo $submit; ?>" name="simple-post"/>
</form>
</body>
Here is the controller code.
Emp.php
public function index(){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name','required','callback_username_check');
$this->form_validation->set_rules('email', 'Email', 'required|is_unique[registration.email]');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'required');
if (empty($_FILES['userfile']['name']))
{
$this->form_validation->set_rules('userfile', 'Photo', 'required');
}
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1800';
$config['max_width'] = '1924';
$config['max_height'] = '1924';
$new_name = time().$_FILES['userfile']['name'];
$config['file_name'] = $new_name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload() OR $this->form_validation->run() == FALSE)
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->emp_model->add_data();
$query['value']=$this->GetAll();
}
}
try this
if (null != ($_FILES['userfile']['tmp_name']))
{
$this->form_validation->set_rules('userfile', 'Photo', 'callback_checkPostedFiles');
}
And this function for validation
public function checkPostedFiles()
{
$file_name = trim(basename(stripslashes($_FILES['userfile']['name'])), ".\x00..\x20");
$file_name = str_replace(" ", "", $file_name);
if (isset($_FILES['userfile']) && !empty($file_name)) {
$allowedExts = array("jpeg", "jpg", "png"); // use as per your requirement
$extension = end(explode(".", $file_name));
if (in_array($extension, $allowedExts)) {
return true;
} else {
$this->form_validation->set_message('checkPostedFiles', "You can upload jpg or png image only");
return false;
}
} else {
$this->form_validation->set_message('checkPostedFiles', "You must upload an image!");
return false;
}
}
Check this sample code for image uploading :
Form :
<form method="post" action="" id="upload_file">
<div class="modal-body">
<div class="box-body">
<div class="form-group">
<label for="exampleInputFile">Profile Picture</label>
<input type="file" id="userfile" accept="image/*" name="userfile">
<p class="help-block">Requested size : 215*215</p>
</div>
</div>
</div>
<div class="modal-footer">
<div class="btn-group">
<button type="button" class="btn btn-default md-close" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" name="submit" value="Save Changes">
</div>
</div>
</form>
Include this js in your view.
Js for form submission
$(function() {
$('#upload_file').submit(function(e) {
e.preventDefault();
$.ajaxFileUpload({
url:'<?php echo base_url(); ?>profile/upload_file',
type: "POST",
fileElementId :'userfile',
success: function() {
alert("file uploaded!");
}
});
return false;
});
});
In controller
$userid = $session_data['id'];
$file_element_name = 'userfile';
$pathToUpload = '/var/www/html/uploads/' . $userid;
if ( ! file_exists($pathToUpload) )
{
$create = mkdir($pathToUpload, 0777);
if (!$create)
return;
}
$config['upload_path'] = $pathToUpload;
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$this->upload->display_errors();
}
else
{
$data = $this->upload->data();
//$this->user->insert_file($data['file_name'], $userid);
$data = array(
'userPhoto' => $data['file_name']
);
$this->db->where('user_id', $userid);
$this->db->update('tbl_user_profile', $data);
}
//#unlink($_FILES[$file_element_name]);

Resources