How to Rename, Copy, and Delete File in PHP

How to Rename, Copy, and Delete File in PHP

Sometimes we need to do some basic tasks in the project like rename, copy, delete and move the file from one location to another. In this post, we will try to explain, how you can Rename, Copy, and Delete the files in PHP.

PHP copying a file

To copy a file, we can use copy() function in PHP. Let’s suppose we have one file with some content, we need to create another file somewhere in the project. Now the copy() function will copy the content of the first file to another. Once the file is copied you will get true otherwise false, and accordingly, you can set the output message.

The following example shows how to copy the test1.txt file to test2.txt file.

Note: both the files are at the same location in the below script. You can change it and add the location with the file name.

<?php
$first = 'test1.txt';    
$second = 'test2.txt'; 
if(copy($first,$second))
echo 'The file was copied successfully';
else
echo 'An error occurred';
?>

PHP renaming a file

To rename a file, we can use rename() function in PHP. This function rename the file with given name as in the below code.

For example, to rename the test1.txt file to test2.bak file, you use the following code:

<?php 
$first = 'test1.txt';
$second = 'test2.bak';

if(rename($first,$second)){
 echo 'file renamed successfully';
}else{
 echo 'An error occurred';
}

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

PHP deleting a file

To delete a file, we can use unlink() function in PHP. you just need to pass the file name in unlink() function with the correct file path. The function returns true if successful or false if failure.

<?php 
$file = 'test1.txt';
if(unlink($file)){
 echo "file deleted";
}else{
 echo "An error occurred";
}

Notice it is a good practice to check the files on the server directory using file_exists() function before using the copy()rename() and unlink() functions because if file not found, that raises warning-level errors which can create problems in the project if you have some condition based output.