Rename and replace an image in my images folder php - php

I'm a newbie working on an app in which i allow users to upload their pics and when they need to change the pic I can't delete the old pic and hence cant rename too. Here's my code to upload an img as per tutorial in codeigniter.
$config['upload_path'] = './img/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['file_name'] = $id.'_img';
$this->load->library('upload', $config);
if ( $this->upload->do_upload())
{
$this->view_data['message'] = "File Uploaded";
}
Here I pass the user id and hence need to rename and replace the old image with the name like 44_img..... Any help would be appreciated , Thanks in advance....

Try this for deletion of the old file:
$oldfile = $config['upload_path'].$config['file_name'];
if( file_exists( $oldfile ) ){
unlink( $oldfile );
}

You can use $this->upload->data() to retrieve data related to upload, and inside do something like that:
if ( $this->upload->do_upload())
{
$this->view_data['message'] = "File Uploaded";
$data = $this->upload->data();
$path = $data['full_path'];
$dir = dirname($path);
$ext = pathinfo($path, PATHINFO_EXTENSION);
if(rename($path, $dir.'/'.$your_file_new_name.'.'.$ext)) {
$this->view_data['message'] .= '<br/> And renamed';
}
}
Note that you must have enough rights to upload your files, especially write righths on a directory you want to upload to. Also, good practice is to give files unique names and separate them into user related directories. For example, you can combine mysql users id with image id.

if you want to over write the existing one, i.e., delete the older one and save new one with same name then
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
if you want to keep both, better save the new one with old one, the code will automatically rename the new one and you can save the name of new uploaded image to access it
$config['overwrite'] = FALSE;
$this->load->library('upload', $config);
if ($this->upload->do_upload())
{
$uploaded_filename = $this->CI->upload->file_name; //name of the save image
$this->view_data['message'] = "File Uploaded";
}

Related

adding timestamp while uploading image file is not working

I am developing a ad site that anyone able to upload 3 images.
So I am coding to upload that 3 images by adding timestamp in front of their file name to make them unique. I use codeigniter framework and attaching the code below.
when I submitting form data, localhost server shows that images have been saved correctly with some code infornt of image filename. But problem is there are no images saved in relevant image folder in that name and I cannot retrieve that images in next preview advertisement page.
I don't know much about php or codeignitor. Your help is highly appreciated.
$config['upload_path'] = './assets/images/adsimages';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 5120;
$this->load->library('upload',$config);
$this->upload->initialize($config);
if (!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = 'no_image.jpg';
}
else {
$data = array('upload_data' => $this->upload->data());
$post_image1 = time().$_FILES['userfile1']['name'];
$post_image2 = time().$_FILES['userfile2']['name'];
$post_image3 = time().$_FILES['userfile3']['name'];
}
$result = $this->post_model->adregister($post_image1,$post_image2,$post_image3);
You can append time to 'filename' in config of upload library
$config['file_name'] = time().$_FILES['userfile1']['name'];
Or if you want unique name for all files the simply add
$config['encrypt_name'] = TRUE;
then
$this->load->library('upload', $config);
Try this one:-
$path = pathinfo($_FILES["userfile1"]["name"]);
$image_path = $path['filename'].'_'.time().'.'.$path['extension'];
I've written a possible solution for your code. You haven't shared your full code so you'll have to fill in the gaps yourself and maybe make some changes here and there; Comments are mentioned wherever necessary. See if it helps you.
public function your_function_name(){
// your-code
// your-code
// check if file is uploaded in field1
if(!empty($_FILES['userfile1']['name'])){
// call function to upload file
$userfile1 = $this->upload_file('userfile1');
}
// check if file is uploaded in field2
if(!empty($_FILES['userfile2']['name'])){
$userfile2 = $this->upload_file('userfile2');
}
// check if file is uploaded in field3
if(!empty($_FILES['userfile3']['name'])){
$userfile3 = $this->upload_file('userfile3');
}
$result = $this->post_model->adregister($userfile1, $userfile2, $userfile3);
}
// function to upload file
function upload_file($filename){
$config['file_name'] = time().$_FILES[$filename]['name']; // append time to filename
$config['upload_path'] = './assets/images/adsimages';
$config['allowed_types'] = 'gif|jpg|jpeg|png|GIF|JPG|PNG|JPEG';
$config['max_size'] = 5120;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$uploaded = $this->upload->do_upload($filename);
if ( ! $uploaded ){
$error = array('error' => $this->upload->display_errors());
$file = 'no_image.jpg'; // default file
}else{
$upload_data = $this->upload->data();
$file = $upload_data['file_name']; // uploaded file name
}
return $file; // return filename
}

How to delete old images from uploads folder after inserting insert a new image

I am able to overwrite the image in the database but the old images still remains in the assets folder.
How can I delete the previous image from the assests folder when i insert a new one?
Please explain in a bit of details since i am a beginner.
public function image_insert(){
$id=1;
if ($this->input->post('submit') && !empty($_FILES['body_image']['name'])) {
$body_image = $_FILES['body_image']['name'];
if($body_image != NULL){
$config['upload_path'] = './assets/image/';
$config['log_threshold'] = 1;
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['max_size'] = '0'; // 0 = no file size limit
$config['overwrite'] = true;
$this->load->library('upload', $config);
$this->upload->do_upload('body_image');
$upload_data = $this->upload->data();
$body_image = $upload_data['file_name'];
}
$this->Home_model->insert_image($body_image,$id);
redirect(base_url('landing_page/home_edit'));
}
else {
redirect(base_url('landing_page/home_edit'));
}
}
If you want to delete a file which already exists in your image folder.
Suppose your image folder path is: /assets/image/
Then, the image delete code will be something like this.
$filePath="/assets/image/";
$fileName=$filePath."dummy.jpg";
if (file_exists($fileName))
{
unlink($fileName);
}
The above code will call you before uploading the image in upload folder.
you may use File helper to delete file :-
$this->load->helper('file');
$path='./assets/image/'.$file_name;
delete_files($path);

How to rename more than 1 file during upload ? Codeigniter

I have a form to upload about 5 files,
lets say it is a photo of the person who is registering and other document about him.
now i'm creating a folder for every registered user with their name ( btw, is it good thing to do? ), and i want to rename each file with the right name let say photo,document A,document B and etc.
my current code
$upload_setting['upload_path'] = './uploads/'.$_POST['name'].'/';
$upload_setting['allowed_types'] = 'jpg|pdf';
$upload_setting['max_size'] = 5000; // 5 MB
$upload_setting['file_name'] = $_POST['name']; // this define the uploaded file name
$this->load->library('upload', $upload_setting);
if ($this->form_validation->run() == FALSE){
$this->load->view('form');
}
else{
if (!is_dir('./uploads/'.$_POST['name'].'/')) {
mkdir('./uploads/'.$_POST['name'].'/', 0777, TRUE);
}
$this->member->register($this->input->post(NULL, TRUE));
$this->upload->do_upload('photo');
$this->upload->do_upload('document-A');
$this->upload->do_upload('document-B');
Also how can i let them free to upload JPG,PDF,DOC ?
i have to link these file in their profile page.
how can i know what extension they upload for each document ?
Please let me know if you have any suggestion or best practice to do this upload and then display each upload in their profile.
Thanks
To know the extension of your file you can use-
$newname= "name";
$path_parts = pathinfo($_FILES["picture"]["name"]);
$file_newname = $newname.'.'.$path_parts['extension'];
To Upload-
if( $_FILES['picture']['name'] )
{
$config['upload_path'] = 'images/receipt/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['file_name'] = $file_newname; //Here your file is being renamed
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('picture'))
{
$error = array('error' => $this->upload->display_errors());
return false;
}
}

Store path of a photo in codeigniter

I followed this tutorial on how to upload a photo in a codeigniter folder:
http://codeigniter.com/user_guide/libraries/file_uploading.html
Can anybody tell me how can I store the path of the photo I just uploaded in my db?
Let's say have table called photo_paths
thanks in advance
This assumes you have an Images table.
Configure the file upload as follows:
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000000';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = FALSE;
$this->load->library('upload', $config);
Then on successful upload insert the file information into the database.
$insert_data = array(
'id_fk' => $this->input->post('page_id'),
'imgfilename' => $upload_info['file_name'],
'imgfilepath' => $upload_info['file_path']
);
$this->db->insert('images', $insert_data);
$upload info is retrived from the file_uploader class on successful upload using the following:
$upload_info = $this->upload->data();
If you want to see exactly what is returned:
echo var_dump($upload_info);
For me, since most of my uploaded images are about the same thing (for example, product images) I might just store the filename (e.g. productshot1.jpg) in the database, since I know where it is anyway (for example, I might keep all product images in "/images/products/"). That way if you need to change something later, it's not so difficult.

Upload problem with PHP: Thumbnail picking up the image name

I have the following model(codeigniter) code to upload image and thumbnail.
However the result of image path becomes, images/comfort_big.jpg and images/comfort_big.jpg.jpg.
The thumbnail image picks up the name of image and add .jpg.
I am uploading images/confort_thumb.jpg for thumb.
Can anyone tell me what's wrong please?
if ($_FILES){
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '200';
$config['remove_spaces'] = true;
$config['overwrite'] = false;
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->load->library('upload', $config);
if (strlen($_FILES['image']['name'])){
if(!$this->upload->do_upload('image')){
$this->upload->display_errors();
exit();
}
$image = $this->upload->data();
if ($image['file_name']){
$data['image'] = "images/".$image['file_name'];
}
}
if (strlen($_FILES['thumbnail']['name'])){
if(!$this->upload->do_upload('thumbnail')){
$this->upload->display_errors();
exit();
}
$thumb = $this->upload->data();
if ($thumb['file_name']){
$data['thumbnail'] = "images/".$thumb['file_name'];
}
}
}
I had a quick look at File Uploading Class in the user guide
In the preferences tables it states:
Note:The filename should not include a file extension.
So my guess is that you get the user to name the file
$config['file_name'] = "User defined";
or remove the extension programmatically. Since you know and list the extensions already you could do
$types = array(".gif",".jpg",".png");
$image['file_name'] = str_replace($types , "", $image['file_name'] );
Your problem is that when you create a thumb you are passing the full image.
So it will add another extension to it.
Use Below code to remove extension from file name.
<?php
$filename=$image['file_name'];
$file_name_with_dot = substr($filename,0, strrpos($filename, '.') + 1);
$only_file_name = substr($file_name_with_dot,0,strlen($file_name_with_dot)-1);
?>
Now pass this $only_file_name variable to your thumb function..
It will be better to use automatic thumb creation from main image.
Hope this will help for you.

Categories