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.
1 2 3 4 5 6 7 8 | <?php $fn = './test.txt'; $newfn = './test2.txt'; if(copy($fn,$newfn)) echo 'The file was copied successfully'; else echo 'An error occurred during copying the file'; |
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:
1 2 3 4 5 6 7 8 9 | <?php $fn = './test.txt'; $newfn = './test.bak'; if(rename($fn,$newfn)){ echo sprintf("%s was renamed to %s",$fn,$newfn); }else{ echo 'An error occurred during renaming the file'; } |
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:
1 2 3 4 5 6 7 8 9 | <?php $fn = './test.bak'; $newfn = './backup/test.bak'; if(rename($fn,$newfn)){ echo sprintf("%s was moved to %s",$fn,$newfn); }else{ echo 'An error occurred during moving the file'; } |
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.
1 2 3 4 5 6 7 | <?php $fn = './backup/test.bak'; if(unlink($fn)){ echo sprintf("The file %s deleted successfully",$fn); }else{ echo sprintf("An error occurred deleting the file %s",$fn); } |
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.