Faster PHP Cloud Hosting

Howdy Web Developer, are you creating a web app that requires you to rename a folder or rename a file in phpRenaming a file is very easy in php you just need to use the php rename() function.

PHP Rename() Function

Defination :-

The rename() function is used for renaming a file or folder in php.

This function returns a boolean i.e true or false depending on whether the file or folder successfully renamed or not.


rename() function has a really easy syntax to understand.

implode( oldname, newname, context );


ParameterTypeData TypeDescription
CurrentNameRequiredStringThe current name of the File / Folder which you want to rename.
NewNameRequiredStringThe new file / folder name to which you want to rename the current file.
contextOptimalResourceThis parameter is used to specify the context of the file handle. Context is a set of options that can be used to modify the behaviour of the stream.


If you rename the file name to an already existing file then that file will be overwritten.

if you are renaming a folder to an already existing folder name then the rename function will fail and return false.

Renaming A File With PHP Example

Now let us see an example of php code for renaming a file in php.

Basic Example :-

$current name = "myfile.txt" ; // Current Name Of The file

$newname = "myrenamedfile.txt" ; // New Name For The File

rename( $currentname, $newname) ;

This was a very basic usage example of the php rename function. But I wont recommed you to use the above code for implementations in real projects.

Instead, you may use this proper implementation code.

Proper Implementation Of PHP Rename() Function Example

This is how you should properly implement the rename function.

$current name = "myfile.txt" ; // Current Name Of The file

$newname = "myrenamedfile.txt" ; // New Name For The File

if(!file_exists($newname)){ // Check If File Already Exists

    if(rename( $currentname, $newname)){ // Check If rename Function Completed Successfully

        echo "Successfully Renamed $currentname to $newname" ;


        echo "There Was Some Error While Renaming $currentname" ;



    echo "A File With The New File Name Already Exists" ;



I hope you may have properly understood and implemented the code for renaming file and folder.

In case if you did not get anything or you have any doubts don’t hesitate to ask me in the comments section below. It would be great to hear from you.

And one more thing if you like the post do share this post with your other web developer friends.