Recipe 24.6. Copying or Moving a File

24.6.1. Problem

You want to copy or move a file.

24.6.2. Solution

Use copy( ) to copy a file, as shown in Example 24-17.

Copying a file

<?php $old = '/tmp/yesterday.txt'; $new = '/tmp/today.txt'; copy($old,$new) or die("couldn't copy $old to $new: $php_errormsg"); ?>

Use rename( ) to move a file, as shown in Example 24-18.

Moving a file

<?php $old = '/tmp/today.txt'; $new = '/tmp/tomorrow.txt'; rename($old,$new) or die("couldn't move $old to $new: $php_errormsg"); ?>

24.6.3. Discussion

On Unix, rename( ) can't move files across filesystems under PHP versions before 4.3.3. To do so, copy the file to the new location and then delete the old file. This is shown in Example 24-19.

Moving a file across filesystems

<?php 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.

24.6.4. See Also

Documentation on copy( ) at and rename( ) at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445 © 2008-2017.
If you may any questions please contact us: