phpcodeignitercodeigniter-url

Rename file in CodeIgniter


I have a file 1353683037.jpg in the tmp folder as shown below:

C:\xampp\htdocs\ci_project\public\images\tmp\1353683037.jpg

I need to rename this file to:

C:\xampp\htdocs\ci_project\public\images\main\1353683037.jpg

To do this, I have done the following:

$file = '1353683037.jpg';
$dir = './public/images/';
rename($dir.'tmp\'. $file, $dir.'main\'. $file);

I'm having the follwing reply from the server:

A PHP Error was encountered

Severity: Warning

Message: rename(./public/images/tmp/1353683037.jpg,../public/images/main/1353683037.jpg) [function.rename]: The system cannot find the path specified. (code: 3)

Filename: controllers/test.php

Line Number: 1

What could possibly be the problem? Thanks


Solution

  • There are two possible reasons that your code will not work:

    First - You are using backslashes for your directory path. The backslash is escaping some of your characters including the single quote after tmp and main. Even though your windows environment uses backslashes, you should use forward.


    Second - Your path is likely incorrect. Rather than use a relative path, try using an absolute path.

    The constant (as set in index.php) FCPATH will give you the server path to your base CodeIgniter directory.

    So, we should be able to modify your code to the following:

    $file = $file = '1353683037.jpg';
    
    $oldDir = FCPATH . 'public/images/tmp/';
    $newDir = FCPATH . 'public/images/main/';
    
    rename($oldDir.$file, $newDir.$file);
    

    If this code does not work, you probably have FCPATH incorrectly set in your index.php file for CodeIgniter. If it is incorrect, you should change it to the proper path, i.e. /xampp/htdocs/ci_project/