codeigniter uploading issues - codeigniter

i know this repeated question here , but i did not get meaning i can not understand. before i was uploaded the file using codeigniter format all are working fine. but the following code is give this error Message: Undefined index: file_name
my html code
<?php echo form_open('fileuplod/setflag') ;?>
<input type="text" name="tagname" class="tagname" id="tagname" placeholder="Flag Name"> <br/>
<input type="file" name="file_name" class="flagimg" id="flagimg">
<input type="submit" name="flagsubmit" value="set">
</div>
<?php
echo form_close(); ?>
and my php upload code
if($_FILES['file_name']['name'] != "")
{
$config['upload_path'] ='images/flag';
$config['allowed_types'] = 'jpg|png';
$config['overwrite'] = false;
$ext =pathinfo($_FILES['file_name']['name'], PATHINFO_EXTENSION);
$config['file_name']= $ext;
$imgname = $config['file_name'];
$this->upload->initialize($config);
$this->load->library('upload', $config);
if(!$this->upload->do_upload('file_name'))
{
$error = $this->upload->display_errors();
$data= array('error'=>$error,);
$this->load->view('error',$data);
return false;
}
}
i can not identify why this error arise. please help anyone

Use form_open_multipart() in your form declaration.

Add this or replace your form_open()
<?php echo form_open_multipart('upload/do_upload');?>
or
<form method="post" action="<?=site_url("fileuplod/setflag");?>" enctype="multipart/form-data">
<input type="text" name="tagname" class="tagname" id="tagname" placeholder="Flag Name"> <br/>
<input type="file" name="file_name" class="flagimg" id="flagimg">
<input type="submit" name="flagsubmit" value="set">
</form>

Related

What is the cause of this wrong image upload error message in my Codeigniter 3 application?

I am working on a basic blog application with Codeigniter 3.1.8 and Bootstrap 4.
There is, among others an "Edit account information" form, which has an image upload field. In the controller, the update() method contains the logic for the image upload action:
public function update() {
// Only logged in users can edit user profiles
if (!$this->session->userdata('is_logged_in')) {
redirect('login');
}
$id = $this->input->post('id');
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
$data['author'] = $this->Usermodel->editAuthor($id);
$this->form_validation->set_rules('first_name', 'First name', 'required');
$this->form_validation->set_rules('last_name', 'Last name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
// Upload avatar
$config['upload_path'] = './assets/img/avatars';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = '100';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
$uerrors = array('uerrors' => $this->upload->display_errors());
$data['uerrors'] = $uerrors;
}
if(!$this->form_validation->run() || !empty($uerrors))
{
print_r($data['uerrors']);
$this->load->view('partials/header', $data);
$this->load->view('dashboard/edit-author');
$this->load->view('partials/footer');
} else
{
$this->Usermodel->update_user($id);
$this->session->set_flashdata('user_updated', 'Your account details have been updated');
redirect(base_url('/dashboard/manage-authors'));
}
}
The (surprising) problem I have is that, even though I am uploading an image, print_r($data['uerrors']); returns You did not select a file to upload. in the browser.
In the view, the same error is returned:
<?php echo form_open(base_url('dashboard/users/update')); ?>
<input type="hidden" name="id" id="uid" value="<?php echo $author->id; ?>">
<div class="form-group <?php if(form_error('first_name')) echo 'has-error';?>">
<input type="text" name="first_name" id="first_name" class="form-control" value="<?php echo set_value('first_name', $author->first_name); ?>" placeholder="First name">
<?php if(form_error('first_name')) echo form_error('first_name'); ?>
</div>
<div class="form-group <?php if(form_error('last_name')) echo 'has-error';?>">
<input type="text" name="last_name" id="last_name" class="form-control" value="<?php echo set_value('last_name', $author->last_name); ?>" placeholder="Last name">
<?php if(form_error('last_name')) echo form_error('last_name'); ?>
</div>
<div class="form-group <?php if(form_error('email')) echo 'has-error';?>">
<input type="text" name="email" id="email" class="form-control" value="<?php echo set_value('email', $author->email); ?>" placeholder="Email">
<?php if(form_error('email')) echo form_error('email'); ?>
</div>
<div class="form-group <?php if(form_error('bio')) echo 'has-error';?>">
<textarea name="bio" id="bio" cols="30" rows="5" class="form-control" placeholder="Add a short bio"><?php echo set_value('bio', $author->bio); ?></textarea>
<?php if(form_error('bio')) echo form_error('bio'); ?>
</div>
<input type="hidden" name="avatar" id="avatar" value="<?php echo $author->avatar; ?>">
<label for="avatar">Upload avatar</label>
<div class="form-group">
<input type="file" name="userfile" id="uavatar" size="20">
<p><?php print_r($uerrors); ?></p>
</div>
<div class="form-group">
<div class="w-50 pull-left pr-1">
<input type="submit" value="Update" class="btn btn-block btn-md btn-success">
</div>
<div class="w-50 pull-right pl-1">
Cancel
</div>
</div>
<?php echo form_close(); ?>
The error message I was expecting, considering that the image I was trying to upload is larger then the specified limit (100KB) is: The file you are attempting to upload is larger than the permitted size.
What am I doing wrong?
Try this
<?php echo form_open_multipart(base_url('dashboard/users/update')); ?>
<div class="form-group">
<input type="file" name="userfile" id="userfile" size="20">
<p><?php print_r($uerrors); ?></p>
</div>
Try to change your form opening, from :
<?php echo form_open(base_url('dashboard/users/update')); ?>
to
<?php echo form_open_multipart(base_url('dashboard/users/update')); ?>
To change the form encoding type from text/plain to multipart/form-data to support image data upload. Here is the difference between each encoding type.

Codeigniter 3 blog application: update() method deletes thumbnail

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.

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

localhost is redirecting to 127.0.0.1 after submitting form in Codeigniter 3

I have a problem in my code. I have a form in my code that looks like this:
<?php echo form_open('users/auth/login', array('class' => 'form floating-label')); ?>
<div class="form-group">
<input type="text" class="form-control" id="username" name="username" />
<label for="username">Username</label>
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" />
<label for="password">Password</label>
<p class="help-block">Forgotten?</p>
</div>
<br/>
<div class="row">
<div class="col-xs-12 text-right">
<?php echo $this->session->flashdata('note'); ?>
<button class="btn btn-primary btn-raised btn-ink" type="submit">Login Account</button>
</div>
</div>
<?php echo form_close(); ?>
Then after clicking the submit it redirect my localhost to 127.0.0.1
After submitting the form it redirects me to
http://127.0.0.1/teradasys/index.php/user/login
Here's my controller
public function index() {
if($this->aauth->is_loggedin()) {
} else {
$data['page_header'] = 'Login Form';
$this->load->view('users/login', $data);
}
}
public function login() {
$identifier = $this->input->post('username');
$password = $this->input->post('password');
if ($this->aauth->login($identifier, $password, true)){
return true;
} else {
$note = $this->aauth->get_errors_array();
$this->session->set_flashdata('note', $note[0]);
$data['page_header'] = 'Login Form';
$this->load->view('users/login', $data);
}
}
Please check your base url in application/config/config.php
and change it.
$config['base_url'] = 'http://localhost/test/';
Please check your base url in application/config/config.php
change from
$config['base_url'] = 'http://localhost/test/';
to
$config['base_url'] = (isset($_SERVER['HTTPS']) ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . preg_replace('#/+$#', '', dirname($_SERVER['SCRIPT_NAME'])) . '/';
$config['base_path'] = $_SERVER['DOCUMENT_ROOT'] . preg_replace('#/+$#', '', dirname($_SERVER['SCRIPT_NAME'])) . '/';
No need to change anything after placing this .If u r using local or live host.

updating data in codiegniter with out selecting the file field in form

I am updating the data in database where I have images file too .So what i want is to put the condition on the image input field if the user want to update data as well as the image so the image will be updated accordingly and if user don't want to update image the rest of the data will be updated now I am having problem in getting the image input field data in controller. I am unable to get the filename directly in controller please help me out.
Here is the code.
function save_update()
{
$id=$this->input->post('id');
if(!empty($_FILES['userfile']['name']))
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$config['max_width'] = '2000';
$config['max_height'] = '2000';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_successful', $error);
}
else
{
$data1 = $this->upload->data();
$filename=$data1['file_name'];
$data=array(
'pname'=>$this->input->post('product_name'),
'pprice'=>$this->input->post('product_price'),
'pquantity'=>$this->input->post('product_quantity'),
'pcategory'=>$this->input->post('category'),
'product_pic'=>$filename
);
$result=$this->cartmodel->update_data($data,$id,'product');
}
}
else
{
$data=array(
'pname'=>$this->input->post('product_name'),
'pprice'=>$this->input->post('product_price'),
'pquantity'=>$this->input->post('product_quantity'),
'pcategory'=>$this->input->post('category'),
'product_pic'=>$this->input->post('oldfile')
);
$result=$this->cartmodel->update_data($data,$id,'product');
if($result==true)
{
redirect('cart/admin');
}
else
{
echo '<script type="text/javascript">alert("sorry Could\'nt delete the file")</script>';
}
}
}
Html is here.
<form class="form-horizontal" method="post" action="<?php echo base_url(); ?>cart/save_update" enctype="multipart/form-data">
<?php
if(isset($specific))
{?>
<fieldset>
<legend>Form Components</legend>
<div class="control-group">
<label class="control-label" for="project_tittle">Product Name</label>
<div class="controls">
<input type="text" class="span6" id="typeahead" name="product_name" value=
"<?=$specific->pname; ?>">
</div>
</div>
<input type="hidden" name="id" value="<?=$specific->pid ?>">
<div class="control-group">
<label class="control-label" for="project_name">Price </label>
<div class="controls">
<input type="text" class="span6" id="typeahead" name="product_price"
value=
"<?=$specific->pprice; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="project_caption">Quantity </label>
<div class="controls">
<input type="number" class="span6" id="typeahead" name="product_quantity"
value=
"<?=$specific->pquantity; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="project_link">Category </label>
<div class="controls">
<select name="category">
<option value=
"<?=$specific->pcategory; ?>"><?=$specific->pcategory; ?></option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="userfile">Product Pic </label>
<div class="controls">
<input type="file" class="span6" id="typeahead" name="userfile" >
</div>
</div>
<input type="hidden" name="oldfile" value="<?=$specific->product_pic; ?>" >
<div class="form-actions">
<button type="submit" class="btn btn-primary">Save changes</button>
<button type="reset" class="btn">Cancel</button>
</div>
</fieldset>
<?php
}
?>
</form>
Replace
if(!empty($_FILES['userfile']['name']))
With
if(isset($_FILES['userfile']))
It is best practice to use isset() to see whether the data is being set or not
Replace
if ( ! $this->upload->do_upload())
With
if ( ! $this->upload->do_upload($_FILES['userfile']['name']))

Resources