rename file in php

You need to use either absolute or relative path (maybe better in that case). If it's in the parent directory, try this code:

old = '..' . DIRECTORY_SEPARATOR . 'picture';
$new = '..' . DIRECTORY_SEPARATOR . 'old.jpg';
rename($old , $new);

Like Seth and Jack mentioned, the error is appearing because the script cannot find the old file. You're making it look in the current directory and not it's parent.

To fix this, either enter the full path of the old file, or try this:

rename("../picture.jpg", "old.jpg");

The ../ traverses up a single directory, in this case, the parent directory. Using ../ works in windows as well, no need to use a backslash.

If you are still getting an error after making these changes, then you may want to post your directory structure so we can all look at it.


A relative path is based on the script that's being executed ($_SERVER['SCRIPT_FILENAME'] when run in web server) which is not always the file in which the file operation takes place:

// index.php
include('includes/mylib.php');

// mylib.php
rename('picture', 'img506.jpg'); // looks for 'picture' in ../

Finding a relative path involves comparing the absolute paths of both the executing script and the file you wish to operate on, e.g.:

/var/www/html/index.php
/var/www/images/picture

In this example, the relative path is: ../images/picture

Tags:

Php