By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Renaming Files with PHP

This short PHP Tutorial will show you how to rename files, using build-in functions of PHP.

Edited: 2014-12-28 04:10

Renaming files is done with the rename function of PHP. This function not only allows you to rename files, it can also be used to move files in the renaming process. The function rename takes just 2 parameters that we care about, the first is the oldname and the second is the newname, representing the current location and file name, and the new one respectively.

<?php
  rename("/MyDIR/MyFileName.txt", "/AnotherDir/my-new-file-name.txt");
?>

See also: Absolute and Relative Paths

The rename function also works on URLs if the URL wrappers has been enabled, you can read more about that in the tutorials on HTTP requests.

File Renaming in PHP

Renaming files has never been easier. To rename a file that lives in a directory – without moving it to another directory – you should do like demonstrated in the below example:

<?php
 rename("/folder/old-file-name.ext", "/folder/new-file-name.ext");
?>

Keep in mind that the rename function operates from the PHP Working Directory, as such the above examples are using root relative paths to access, rename and/or move files.

To easily find out what the current working directory is, you may want to do something like below:

<?php
// current directory
echo getcwd() . "<br>";

chdir('MySubDir');

// New directory after Changing using chdir to change directory!
echo getcwd() . "<br>";
?>

See also

  1. Create and Write to Files
  2. Reading Files
  3. Deleting Files and Directories
  4. Copying files in PHP