Moving, Copying, and Deleting Files

PHP has simple functions to handle all moving , copying , and deleting of files. Unix users will know there is no command for "rename," because renaming a file is essentially the same as moving it. Thus, you use the move (mv) command—it is the same in PHP.

Files are moved using rename(), copied using copy(), and deleted using unlink(). This is so named because Unix systems consider filenames to be "hard links" to the actual files themselves—to unlink a file is to delete it.

Warning

All three functions will operate without further input from you. If you choose to pass an existing file to the second parameter of rename(), it will rename the file in parameter one to the file in parameter two, overwriting the original file. The same applies to copy()—you will overwrite all files without question, as long as you have the correct permissions.

Moving Files with rename()

Used for both renaming and moving files, rename() takes two parameters: the original filename and the new filename you wish to use. The function can rename/move files across directories and drives, and will return true on success or false otherwise.

Here is an example:

    $filename2 = $filename . '.old';
    $result = rename($filename, $filename2);
    if ($result) {
            print "$filename has been renamed to $filename2.\n";
    } else {
            print "Error: couldn't rename $filename to $filename2!\n";
    }

If you had $filename set to c:\\windows\\myfile.txt, the above script would move that file to c:\\windows\\myfile.txt.old ...

Get PHP in a Nutshell 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.