Pradeep G
Pradeep G

Reputation: 139

Rename and replace an image in my images folder 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....

Upvotes: 2

Views: 6477

Answers (3)

Deepanshu Goyal
Deepanshu Goyal

Reputation: 2813

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";
}

Upvotes: 1

Nil'z
Nil'z

Reputation: 7475

Try this for deletion of the old file:

$oldfile   = $config['upload_path'].$config['file_name'];
if( file_exists( $oldfile ) ){
    unlink( $oldfile );
}

Upvotes: 3

baldrs
baldrs

Reputation: 2161

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.

Upvotes: 2

Related Questions