To move a file from one directory to another using php, the easiest way is to use the php rename() function.
rename("./folder1/file.txt","./folder2/file.txt");
Moving files with php is easy. We can use the php rename() function to move a file into a different folder or directory.
If we want to move a file named “file.txt” from “folder1” to “folder2”, we can do this with the following code:
rename("./folder1/file.txt","./folder2/file.txt");
We can also change the destination file name if we want. If we want to rename the file name from “file.txt” to “new_name.txt”, we can do so in the following php code:
rename("./folder1/file.txt","./folder2/new_name.txt");
Moving Multiple Files to a Different Folder in php
In php, it is easy to move multiple files to different folders. To do so, we can use the php rename() function in a loop.
Let’s say we have 5 files and we want to move these 5 files from the “development” folder to the “production” folder.
We can put the 5 file names in an array, and then loop over that array calling the rename() function inside the loop
$array_of_file_names = array("file1.php","file2.php","file3.php","file4.php","file5.php");
for ($x = 0; $x < 5; $x++) {
rename("./development/" . $array_of_file_names[$x], "./production/" . $array_of_file_names[$x]);
}
With this code, the 5 files will move to the new folder.
Moving a Directory with php
We can also move directories to new locations with the rename() function.
Let's say we want to move the "assets" folder from folder named "edits_done" folder to a different folder named "production".
We can move the directory easily with the php rename() function in the following php code:
rename("./edits_done/assets","./production/assets"
Hopefully this article has been helpful for you to understand how you move a file, move a directory, and move multiple files to different folders using php.