Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page