PHP: Copy, Rename or Move a File

by Yang Yang on April 22, 2009

PHP can only copy, rename or move files that are of the same owner with who is running the PHP script. After making sure of this, you can proceed to:

Copy a file to another place in PHP:

$old = '/tmp/yesterday.txt';
$new = '/tmp/today.txt';
copy($old, $new) or die("Unable to copy $old to $new.");

Rename a file and give it a new name:

$old = '/tmp/today.txt';
$new = '/tmp/tomorrow.txt';
rename($old, $new) or die("Unable to rename $old to $new.");

Move a file to a new place in PHP:

if (copy("/tmp/code.c","/usr/local/src/code.c")) {

Apparently you must make sure the copying is successful before doing the deletion.

Of course you can always execute a native Linux shell command such as ‘cp’ and ‘mv’ to do the dirty work for you instead of resorting to a PHP function. In this situation, you need the php function exec() to execute an external command.