Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Files and I/O

PHP unlink(), rename() and copy() functions

Reference for PHP unlink(), rename() and copy(): delete, move and duplicate files, what happens to existing targets, failure values, and atomic replacement.

Three small functions manage files on disk. unlink() deletes a file. rename() moves or renames a file or directory. copy() duplicates a file, leaving the original in place. Each returns true on success and false on failure, with a warning explaining why.

Deleting is permanent: PHP has no recycle bin. Check the path, and never build it from raw user input.

PHP
copy("report.txt", "report-backup.txt");
rename("report.txt", "archive/report.txt");
unlink("archive/report.txt");

Try it

PHP Copy, rename and delete

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Existing targets and atomic replacement

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
unlink(string $filename, ?resource $context = null): bool
rename(string $from, string $to, ?resource $context = null): bool
copy(string $from, string $to, ?resource $context = null): bool
Name Description
$filename The file to delete.
$from The existing source path.
$to The destination path.

Return value: true on success, false on failure (missing file, no permission, missing destination directory).

Usage notes

  • unlink() deletes files, not directories. Use rmdir() for an empty directory.
  • Missing files give a warning. Test with is_file() first, or silence it with @ when "already gone" is fine.
  • rename() replaces an existing target file on most systems (on Windows it replaces files as well in modern PHP, but fails if the target is locked or open).
  • copy() overwrites the destination without asking. Check file_exists() first if that is not what you want.
  • Atomic update. Write to a temporary file in the same directory and rename() it over the target: readers see either the old file or the new one, never half of it. Both paths must be on the same filesystem.
  • Moving across filesystems may make rename() fail or fall back to a copy; check the result.
  • copy() copies content only, not directories. Copying a folder needs a loop over scandir().
  • Open handles on Windows can block unlink() and rename(). Close them with fclose() first.
  • Never trust user input in paths. Names like ../../secret escape the folder you expect; whitelist names or use basename().