This tutorial will show you to rename files and folders in PHP with the rename() function – including some code examples you can use in your own project.
We’ve already covered uploading files and deleting files in PHP, read on to find out how to rename them.
rename() PHP Function Syntax
The syntax for the rename() function used to delete files in PHP is as follows:
rename($FROM, $TO, $CONTEXT)
Note that:
- $FROM is the path of the existing file you wish to rename
- $TO is the new path you wish to rename the file specified in $FROM
- If the path differs, the file will be moved
- The operation will attempt to overwrite any existing file at the same path
- $CONTEXT is an optional parameter which can be used to specify a context stream
- This option is rarely used, you can probably ignore it
- rename() will return a boolean value
- TRUE if successful, FALSE if not successful
Renaming a Single File
Here’s how to rename a single file with the rename() function in PHP.
Ensure The File is Closed Before Renaming
First, if you have been using the file in your PHP script, you must ensure it is closed, otherwise the rename operation will fail.
// Close an open file pointer fclose($filePointer);
Renaming a File
If there are no open references to the file it can be renamed using the rename() function and supplying the current name of the file and the new name of the file:
rename( 'file.tt', 'renamed-file.txt' );
Moving a File
rename() can be used to move files by specifying the full path to the new location:
rename( 'file.txt', 'path/to/new/locationrenamed-file.txt' );
Using realpath() to Fix Path Issues
If you run into trouble with your paths (due to them containing symbolic links, containing extra slashes or because they are relative paths which do not resolve properly), you can try using the realpath() function to rename the file using the absolute path:
unlink(realpath($pathToFile));
Renaming Multiple Files Matching a Pattern
Multiple files can be renamed by using the glob() function to search for all files with names matching a certain pattern. Below, all files with the .txt file extension are found and then renamed:
foreach (glob("*.txt") as $pathToFile) { $newFilePath = str_replace("foo","bar", $pathToFile); rename($pathToFile, $newFilePath); }
The str_replace() function is used to replace “foo” in all of the file names, renaming them to “bar”.