In addition to offering you path information, PHP comes with a whole bunch of functions designed to simplify the task of moving, copying, renaming and deleting files on the filesystem. The first of these is the copy() function, which accepts two arguments, a source file and a destination, and copies the former to the latter. Here's an example which demonstrates:
Note that if the destination file already exists, copy() will usually overwrite it. A failure to copy the file will cause copy() to return false; success returns true. A corollary to the copy() function is the rename() function, which can be used to both rename and move files. Like copy(), it too accepts two arguments, a source file and a destination file. Consider the following example, which renames a file,
and this one, which simultaneously renames and moves a file.
It's possible to rename directories in the same manner as files - as illustrated in this next snippet:
The rename() function comes in handy when you need to update files which are constantly being used by multiple processes. Instead of directly updating the target file with new data, rename() allows you to copy the original file contents into a new file, make your changes and then, once you're happy with the result, simply rename() the new file to the old one. The following example demonstrates:
Note my use of the tempnam() function above - this function generates a unique file name, given a directory and a filename prefix, and can help to avoid filename collisions between different processes. When it comes time to delete files, PHP offers the unlink() function, which can be used to erase a file from the filesystem. Consider the following example, which demonstrates by deleting a specific file:
You can also use the unlink() function to iterate over a directory and remove all the files within it - this is demonstrated in an example coming up shortly. Note that the unlink() function (and indeed, all other file manipulation
blog comments powered by Disqus |