PHP File Operations

Summary: in this tutorial, you will learn some common used PHP file operations such as copying, renaming and deleting files in PHP.

PHP copying a file

To copy a file, you use the copy() function. First, you need to determine which file to copy by passing the file path to the first parameter of the copy() function. Second, you need to specify the file path to copy the file to. The copy() function returns true if the file was copied successfully, otherwise it returns false.

The following example illustrates how to copy the test.txt file to test2.txt file, which locates in the same directory as the script.

PHP renaming a file

To rename a file, you use the  rename() function. This function also allows you to move a file to a different directory. For example, to rename the test.txt file to test.bak file, you use the following code:

Notice that the rename() function returns true if the file is renamed successfully, otherwise it returns false.

The following example shows you how to use the rename() function to move the test.bak to the backup directory:

PHP deleting a file

To delete a file, you use the unlink() function. You need to pass the  file name that you want to delete to the unlink() function. The function returns  true on success or false on failure.

Notice that copy(), rename() and unlink() functions raise warning-level errors if the file cannot be found therefore it is good practice to check the file exists using the file_exists() function before copying, renaming or deleting it.

In this tutorial, we introduced you some handy functions that deal with copying, renaming or move and deleting a file.

  • Was this tutorial helpful ?
  • YesNo