To copy a file using php, the easiest way is to use the php copy() function.

copy("./folder/file_name1.txt","./folder/file_name2.txt");

Copying files with php is easy. We can use the php copy() function to copy files.

If we want to copy a file named “file_name.txt” to “copied_file_name.txt”, we can do this with the following php code:

copy("./folder/file_name.txt","./folder/copied_file_name.txt");

One thing to note with the copy function, you need to make sure the target directory exists. If the target directory doesn’t exist, then the copy() function will not work.

Finally, if you want to move a file in php instead of copying, you can use the php rename() function.

Copying Multiple Files with php

In php, it is easy to copy multiple files. To do so, we can use the php copy() function in a loop.

Let’s say we have 5 files and we want to copy these 5 files from a folder named “folder” to another folder named “folder2”.

We can put the 5 file names in an array, define a new array with the 5 new file names, and then loop over that array calling the copy() function inside the loop:

$files_to_copy = array("file1.php","file2.php","file3.php","file4.php","file5.php");

$new_file_names = array("file1_new.php","file2_new.php","file3_new.php","file4_new.php","file5_new.php");

for ($x = 0; $x < 5; $x++) {
  copy("./folder/" . $files_to_copy[$x], "./folder2/" . $new_file_names[$x]);
}

With this code, the 5 files will all be copied to the other directory.

Hopefully this article has been helpful for you to understand how you copy one file or copy multiple files using php.

Categorized in:

PHP,

Last Update: February 26, 2024