13.3. Moving, Copying, and Deleting FilesPHP 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) commandit 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 themselvesto unlink a file is to delete it.
13.3.1. 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.
13.3.2. Copying Files with copy( )Like rename( ), copy( ) also takes two parameters: the filename you wish to copy from and the filename you wish to copy to. The difference between rename( ) and copy( ) is that calling rename( ) results in the file being in only one place, the destination, whereas copy( ) leaves the file in the source location and places a new copy of the file into the destination. $filename2 = $filename . '.old'; $result = copy($filename, $filename2); if ($result) { print "$filename has been copied to $filename2.\n"; } else { print "Error: couldn't copy $filename to $filename2!\n"; } The result of that script is that there will be a file $filename and also a $filename.old, e.g., c:\\windows\\myfile.txt and c:\\windows\\myfile.txt.old.
13.3.3. Deleting Files with unlink( )To delete files, pass a filename string as the only parameter to unlink( ). This function only deals only with filesto delete directories, you need rmdir( ). if (unlink($filename)) { print "Deleted $filename!\n"; } else { print "Delete of $filename failed!\n"; }
|