19.6. Copying or Moving a File
Problem
You want to copy or move a file.
Solution
Use copy( )
to copy a file:
copy($old,$new) or die("couldn't copy $old to $new: $php_errormsg");
Use rename( )
to move a file:
rename($old,$new) or die("couldn't move $old to $new: $php_errormsg");
Discussion
On Unix, rename( )
can’t move
files across filesystems. To do so, copy the file to the new location
and then delete the old file:
if (copy("/tmp/code.c","/usr/local/src/code.c")) { unlink("/tmp/code.c"); }
If you have multiple files to copy or move, call copy( )
or rename( )
in a loop. You can
operate only on one file each time you call these functions.
See Also
Documentation on copy( )
at
http://www.php.net/copy and rename( )
at http://www.php.net/rename.
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.