PHP: Copy, Rename or Move a File

by Yang Yang on April 22, 2009

in PHP Tips & Tutorials

Share This Article:
Subscribe to Kavoir: blog feed

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")) {
  unlink("/tmp/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.

Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 6 comments… read them below or add one }

christian July 6, 2009 at 6:22 pm

Hi, maybe you could help me with a problem i’m having, i need ti rename a file, with a specific name, how can i create a function that let do the following, if the file exist, rename the file with a new name like, document.php, document_2.php, document_3.php, document_4.php. i need to create a function to do that, when it renames a file rename it with the next number.

thank you

Reply

John Ryan November 14, 2010 at 7:46 pm

This is the simplist tutorial on file management iv’e seen so far.. Thanks for the help

Reply

website design gold coast November 21, 2010 at 5:10 pm

Thanks for valuable information

Reply

Badminton Training January 22, 2011 at 2:55 am

Thank you! Copied your sample code and got it working immediately.

Reply

popo March 5, 2011 at 7:13 am

You can easy move files with rename: rename(“/tmp/code.c”,”/usr/local/src/code.c”)

Reply

mehdi May 9, 2011 at 3:50 am

its not working!!
its saying failed to open stream
help plzzz!

Reply

Leave a Comment

{ 1 trackback }

Previous post:

Next post: