rename

rename($from, $to, $context)

Renames or moves a file or folder and returns true, on failure false with a warning. It overwrites an existing target file.

Parameters

  • $from – the current path.
  • $to – the new path including the name. The target folder must exist.
  • $context – optional, a context from stream_context_create().

Examples

$folder = sys_get_temp_dir();
file_put_contents($folder . "/garth-a.txt", "content");
var_dump(rename($folder . "/garth-a.txt", $folder . "/garth-b.txt")); // bool(true)
var_dump(file_exists($folder . "/garth-a.txt")); // bool(false)
echo file_get_contents($folder . "/garth-b.txt"); // content
// moving to another folder
mkdir($folder . "/garth-archive");
rename($folder . "/garth-b.txt", $folder . "/garth-archive/garth-b.txt");
var_dump(is_file($folder . "/garth-archive/garth-b.txt")); // bool(true)
// safe saving: write to a temporary file and rename it
$target = $folder . "/garth-settings.json";
file_put_contents($target . ".tmp", json_encode(array("color" => "blue"), JSON_UNESCAPED_UNICODE));
rename($target . ".tmp", $target);
echo file_get_contents($target); // {"color":"blue"}
unlink($target);
unlink($folder . "/garth-archive/garth-b.txt");
rmdir($folder . "/garth-archive");

Things to watch out for

  • It overwrites an existing target file without a warning.
  • Renaming within one disk happens at once, so another request sees either the old or the new file, never a half-written one. That is why files that are being read are saved this way.
  • When moving between different disks, PHP copies the file and deletes the original, and such a change no longer happens at once.
  • The target folder must exist. mkdir() creates it.
  • Do not build the path from user input, check the name against a list of allowed values.

Related functions:
copy()
unlink()
file_put_contents()