i dont know how to update and replace image in codeigniter - php

I would like to replace and update uploaded Image using codeigniter. But I am not sure how to achieve that. Here is my below code -
MY CONTROLLER :
public function updateProccess()
{
$this->items_model->updateData();
if ($this->db->affected_rows() > 0) {
$this->session->set_flashdata('message', 'Update data is success');
}
redirect('items');
}
AND here's my model to update data
public function updateData()
{
$data = [
'barcode' => $this->input->post('barcode'),
'name' => $this->input->post('name'),
'categories_id' => $this->input->post('category'),
'units_id' => $this->input->post('unit'),
'price' => $this->input->post('price'),
'updated' => date('Y-m-d H:i:s')
];
$this->db->where('items_id', $this->input->post('items_id'));
$this->db->update('items', $data);
}
thank you for your help :)

This is my case:
Step 1: First I have checked file is not empty, if file is empty update file will not work, if file is uploaded from html then I have fetched previous record from database in a $row variable (temporary variables).
Step 2: After getting previous data, I have updated data in database i.e. path and name of new file.
Step 3: After that I have verified that user is updating data or inserting new one. If data is to be updated then old image will be deleted.
if($_FILES["img"]["name"]!="")
{
$row=$this->general_model->getSingle("banner", ["id"=>$id]);
$temp=$_FILES["img"]["name"];
$temp=explode(".", $temp);
$ext=end($temp);
$file_name_temp="banner".time().rand(0,9);
$file_name=$save["img"]=$file_name_temp.".".$ext;
$config["file_name"]=$file_name;
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = 1024*10;
enter code here
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('img'))
{`enter code here`
$msg=strip_tags($this->upload->display_errors());
_setFlashSession("msg", "<span class='label label-danger'>$msg</span>");
redirect("admin/site-configure/banner");
}
if($id!="")
{
$file="./uploads/".$row["img"];
unlink($file);
$file="./webp/".$row["webp"];
unlink($file);
}
}

Related

Laravel problem store variables data in Database

In my database name files have columns id_message and file_path. File is stored in MyFiles/{id_message}.
Problem is how variables $idParameter and $pathFile save in database. No errors show.
function fileUpload(Request $request)
{
$request->validate([
'id_message' => 'required|min:6'
]);
$idParameter = $request->id_message=$request->id_message;
$result=$request->file('file_path')->store('MyFiles/'.$idParameter);
return ["result"=>$result];
$pathFile = getPathname('MyFiles/'.$idParameter);
$file = new File;
$file->id_message=$idParameter;
$file->file_path=$pathFile;
$file->save();
}
Remove return ["result"=>$result]; and add this into end.

Image update and remove old image on Laravel

Trying to implement update article in my update controller it seems works, but the problem is when I only want to update the post without uploading an image the old always getting remove which is it shouldn't.
here's my store function
public function store(Post $post)
{
$post->update($this->validateRequest());
$this->storeImage($post);
return redirect('post/'.$post->id)->with('success', 'New ariticle has been posted');
}
}
here's my validation
private function validateRequest()
{
return request()->validate([
'title'=> 'required',
'content' => 'required',
'image' => 'sometimes|image|max:5000',
]);
}
here's my update function
public function update(Post $post)
{
File::delete(public_path('storage/'.$post->image));
$post->update($this->validateRequest());
$this->storeImage($post);
return redirect('post/'.$post->id)->with('success', 'This post has
been Edited');
}
}
I've tried to add File::delete to my storeImage function and delete it from my update function, it fix the problem but the old image is not removed from directory
private function storeImage($post)
{
if (request()->has('image')){
File::delete(public_path('storage/'.$post->image))
$post->update([
'image' => request()->image->store('uploads', 'public'),
]);
$image = Image::make(public_path('storage/'.$post->image))->fit(750, 300);
$image->save();
}
}
Ok since I use model binding in my controller I don't have to find the id right?
so I change my update function which is basically Akhtar munir suggested, and turn out to be something like this. The image update work, it also remove the old image when I update it. But I have found another issue, the problem is when I edit article and title it didn't change like when I update it, I hope you can take look at this is this correct?
public function update(Post $post){
$this->validateRequest();
if(request()->hasFile('image') && request('image') != ''){
$imagePath = public_path('storage/'.$post->image);
if(File::exists($imagePath)){
unlink($imagePath);
}
$image = request()->file('image')->store('uploads', 'public');
$post->update([
'title' => request()->title,
'content' => request()->content,
'image' => $image,
]);
}
}
This is what I have done in one of my method. It may help you.
public function update(Request $request, $id)
{
if (UserDocument::where('id',$id)->exists()) {
$this->validateUserDocument($request);
if ($request->hasFile('doc_file') && $request->doc_file != '') {
$doc = UserDocument::where('id',$id)->first();
// dd($doc);
$file_path = storage_path().'/app/'.$doc['doc_file'];
//You can also check existance of the file in storage.
if(Storage::exists($file_path)) {
unlink($file_path); //delete from storage
// Storage::delete($file_path); //Or you can do it as well
}
$file = $request->file('doc_file')->store('documents'); //new file path
$doc->update([
'title' => $request->title,
'doc_file' => $file //new file path updated
]);
session()->flash('success','Document updated successfully!');
return redirect()->route('userdocs');
}
session()->flash('error','Empty file can not be updated!');
return redirect()->back();
}
session()->flash('error','Record not found!');
return redirect()->back();
}
In this code, I just simply want to clearify to you that I have stored image path in database, first I have retrieved that path and with that path I have found image in my local storage, delete it first and then update it with the new one. But make sure to store image path in database in both cases ofcourse with insert and update.
So finally you can also optimize your code like this, it will do the same thing as you expect, whether image and all data or only title and content.
public function update(Post $post){
$this->validateRequest();
$data = [
'title' => request()->title,
'content' => request()->content
];
if (request()->hasFile('image') && request('image') != '') {
$imagePath = public_path('storage/'.$post->image);
if(File::exists($imagePath)){
unlink($imagePath);
}
$image = request()->file('image')->store('uploads', 'public');
$data['image'] = $image;
//$post->update($data);
}
$post->update($data);
}
Try this one
private function storeImage($post)
{
if (request()->hasFile('image')){
$image_path = "/storage/".'prev_img_name'; // prev image path
if(File::exists($image_path)) {
File::delete($image_path);
}
$post->update([
'image' => request()->image->store('uploads', 'public'),
]);
$image = Image::make(public_path('storage/'.$post->image))->fit(750, 300);
$image->save();
}
}

Image Upload to database reference original name

I am working on a codeigniter project. In the image upload config I have it as encrypted to allow unique file names to avoid overwriting and doubling of name and for more security in general.
So on upload it will encrypt the image file name, and store the encrypted name in the database while saving the image in my assets folder. But for some reason it doesn't seem to encrypt the image names at all. Almost like it is completely ignoring the $config options and just uploading the image.
Also I have attempted a call back function to avoid blank uploads and again seems that is ignored also and the post are still allowed.
If anyone can lend a tip. Please.
Controller
//Callback validation
$this->form_validation->set_rules('userfile','Photo','callback_photo_check');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('posts/create', $data);
$this->load->view('templates/footer');
} else {
if($this->form_validation->run()==TRUE){
$config['upload_path'] = 'assets/images/posts';
$config['allowed_types'] = 'gif|jpg|jpeg';
$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('userfile')){
$errors = array('error'=>$this->upload->display_errors());
$this->load->view('templates/header');
$this->load->view('posts/create', $errors);
$this->load->view('templates/footer');
}else {
$this->post_model->create_post($this->upload->data('full_path'),$this->input->post());
}
}
$this->session->set_flashdata('post_created','Your Post has been submitted');
redirect('posts');
}
}
public function photo_check(){
if(empty($_FILES['userfile'])){
$this->form_validation->set_message('photo_check', 'need a image');
return FALSE;
}
else{
return TRUE;
}
}
Model
public function create_post($path,$post){
$data = array(
'about'=> $this->input->post('Description'),
'image' => $path,
);
return $this->db->insert('posts',$data);
I have the same problem before, then I decided to give them(files) a unique name, what I did is:
• I assigned an empty variable which will hold the file name/ path data meant to be modified and I named it as $info_name.
• Everytime the file name will have a duplicate in the existing location it will add a unique extension such as time(seconds,date, etc).
Here is my sample code:
public function new_info($data,$photo){
extract($data);
$info_name = "";
$directory = "C:/xampp/htdocs/Parent folder/child folder/grand child folder/";
$extension= array("jpeg","jpg","png","gif");
$file_name=$photo["form_name"]["name"];
$file_tmp=$photo["form_name"]["tmp_name"];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(in_array($ext,$extension)){
if(!file_exists($directory.$file_name)){
move_uploaded_file($file_tmp=$photo["form_name"]["tmp_name"],$directory.$file_name);
$info_name = $file_name;
}
else{
$filename=basename($file_name,$ext);
$newFileName=$filename.time().".".$ext;
move_uploaded_file($file_tmp=$photo["form_name"]["tmp_name"],$directory.$newFileName);
$info_name = $newFileName;
}
}
// then your sql code here for example:
$data= array( 'user' => $_SESSION["user_id"],
'picture' => $info_name,
);
$this->db->insert('sys_post',$data);
}
To encrypt the uploaded file names, you have to follow below steps.
1) You have to load the Encryption Library.
You can call this library on particular page where there is upload code.
// LOAD LIBRARIES
$this->load->library('encryption');
OR you can also load it in autoload.php file in $autoload['libraries'] = array('database','form_validation','encryption');
2) Now you are using the Encryption class, you must set an encryption key in config.php file.
$config['encryption_key'] = 'your-own-encryption-key';
For more information regarding Encryption => https://codeigniter.com/user_guide/libraries/encryption.html
3) And finally, In your upload code $config['encrypt_name'] = TRUE;.
Hope this will help.

can't update photo in Laravel because validation even can upload photo when create a profile person

I can't upload a photo when update a profile even i can upload it when i create profile in first time. In Update section, i put validation in form request for photo update and create. It's
'foto' => 'sometimes|image|max:500|mimes:jpeg,jpg,bmp,png',
Eveything good when upload in create. But, when upload for updating, warning appears because validation. Such 'The PHOTO must be an image.' or 'The PHOTO must be a file of type: jpeg,jpg,bmp,png.'
This my code :
On Controller for update :
public function update(Siswa $siswa, SiswaRequest $request){
$input = $request->all();
if($request->hasFile('foto')) {
$exist = Storage::disk('foto')->exists($siswa->foto);
if(isset($siswa->foto) && $exist) {
$delete = Storage::disk('foto')->delete($siswa->foto);
}
$foto = $request->file('foto');
$ext = $foto->getClientOriginalExtension();
if ($request->file('foto')->isValid()) {
$foto_name = date('YmdHis').".$ext";
$upload_path = 'fotoupload';
$request->file('foto')->move($upload_path, $foto_name);
$input['foto'] = $foto_name;
}
}
$siswa->update($input);
$telepon = $siswa->telepon ?? new Telepon();
$telepon->nomor_telepon = $request->input('nomor_telepon');
$siswa->telepon()->save($telepon);
$siswa->hobi()->sync($request->get('hobi_siswa', []));
return redirect('siswa');
}
This my code for validation in request
public function rules()
{
if($this->method() == 'PATCH') {
$id_rules = 'required|numeric|digits:8|unique:siswa,id,' . $this->get('id');
$telepon_rules = 'sometimes|numeric|digits_between:10,15|unique:telepon,nomor_telepon,' . $this->get('id') . ',id_siswa';
}
else {
$id_rules = 'required|numeric|digits:8|unique:siswa,id';
$telepon_rules = 'sometimes|numeric|digits_between:10,15|unique:telepon,nomor_telepon';
}
return [
'id' => $id_rules,
'nama_siswa' => 'required|regex:/^[\pL\s]+$/u|max:30',
'tanggal_lahir' => 'required|date',
'jenis_kelamin' => 'required|in:L,P',
'nomor_telepon' => $telepon_rules,
'id_kelas' => 'required',
'foto' => 'sometimes|image|max:500|mimes:jpeg,jpg,bmp,png',
];
}
So, i can't update my photo at all. How is the way to fix it?
Add this to your form. Maybe this will fix it.
enctype="multipart/form-data" :
<form action="..." class="...." method="post" enctype="multipart/form-data">

CodeIgniter Image Upload Not Working and No Errors

Okay so I've been messing with this for a couple hours now, reading the docs and browsing forums but I cannot find out why this upload form isn't working.
The entire form works perfectly, data saves to the DB and everything. But I just added an image upload input and it doesn't work! I have followed the exact tutorial in the docs, as well as several others.
Here is the code that processes the form submit ($this->page_m is my model):
public function edit ($id = NULL)
{
// Fetch a page or set a new one
if ($id) {
$this->data['page'] = $this->page_m->get($id);
count($this->data['page']) || $this->data['errors'][] = 'page could not be found';
}
else {
$this->data['page'] = $this->page_m->get_new();
}
// Pages for dropdown
$this->data['pages_no_parents'] = $this->page_m->get_no_parents();
// Process the form
if ($this->form_validation->run('page_rules') == TRUE) {
$data = $this->page_m->array_from_post(array(
'title',
'slug',
'body',
'template',
'parent_id'
));
if(!empty($_FILES['userfile'])) {
$this->do_upload();
}
$this->page_m->save($data, $id);
redirect('admin/page');
}
// Load the view
$this->data['subview'] = 'admin/page/edit';
$this->load->view('admin/_layout_main', $this->data);
}
and here is the code that processes the photo upload, which is called right after the $this->form_validation->run() check:
//upload a slider photo
public function do_upload() {
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => site_url('uploads/')
);
$this->load->library('upload');
$this->upload->initialize($config);
$field_name = "userfile";
if ( ! $this->upload->do_upload($field_name)) {
$this->data['error'] = array('error' => $this->upload->display_errors());
$this->data['subview'] = 'admin/page/edit';
$this->load->view('admin/_layout_main', $this->data);
} else {
return true;
}
}
I have purposely made this upload script as simple and basic as possible for debugging purposes, but still I have had no success in getting this form to upload properly.
After I get the upload working I need to save the image name in my database table, but that is besides the point right now. I just need to get this actually uploading.
SOLVED -- INVALID UPLOAD DIRECTORY
To debug your script you should try and echo out the value returned by $this->upload->display_errors();
Try changing your do_upload() methods last if{} else {} statement to the following:
if ( ! $this->upload->do_upload($field_name)) {
// return the error message and kill the script
echo $this->upload->display_errors(); die();
$this->data['error'] = array('error' => $this->upload->display_errors());
$this->data['subview'] = 'admin/page/edit';
$this->load->view('admin/_layout_main', $this->data);
} else {
return true;
}
Hopefully this will help you find out what is causing the problem.
same problem with mine, I resolve that by upgrading CodeIgniter,
my old version is 3.1.2, then i just upgrade to CI-3.1.3,
just replace the system folder in root folder,
after that, the problem resolve in live server,
i hope my suggest is useful to use

Categories