Moving, copying, and deleting files

bool rename ( string old_name, string new_name [, resource context])

bool copy ( string source, string dest)

bool unlink ( string filename, resource context)

PHP has simple functions to handle all moving, copying, and deleting files, and quite rightly - they are all very popular things to do, so there is no point making them difficult. If you are using Unix you will know that there is no command for "rename", because renaming a file is essentially the same as moving it, so you use the move (mv) command - it is the same in PHP.

Files are moved using rename(), copied using copy(), and deleted using unlink(). Unlink() might seem like an odd choice of word at first, but Unix systems consider filenames to be "hard links" to the actual files themselves, so to unlink a file is to delete it.

Author's Note: 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.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Moving files with rename() >>

Previous chapter: fwrite()

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.