How to move files in PHP
In this tutorial, you are going to learn how to move a file in PHP using PHP’s rename() function.
We can move a file easily from one folder to another using rename() function. The rename() function is a pre-built function in PHP. It renames a file name and moves. We are going to move forward in this tutorial step by step and see some examples. Let’s start-
Move a text file:
Suppose we have a text file called “Present.txt” with some text and a folder called “Newfolder” in our project directory. We are going to move the “Present.txt” text file to “Newfolder” using the rename() function.
Now, let’s jump into straight in the code-
<?php
$presentFile = '/xampp/htdocs/PHPcodeExamples/Present.txt';
$moveFile = '/xampp/htdocs/PHPcodeExamples/Newfolder/Move.txt';
if (rename($presentFile, $moveFile)) {
echo "Text file moved successfully";
}
else {
echo "Text file moved failed";
}
?>
The rename() function simply takes two parameters. The first parameter takes the directory of current folder and in the second one we have to define the directory we want to move the file. Here, the if-else condition is not necessary for using the rename() function. It is just for showing input in the browser.
OUTPUT:
Move an image:
We can also move an image in the same way. Let’s look at the example-
<?php
$presentImage = '/xampp/htdocs/PHPcodeExamples/PresentImage.jpg';
$movedImage = '/xampp/htdocs/PHPcodeExamples/Newfolder/MovedImage.jpg';
if (rename($presentImage, $movedImage)) {
echo "Image moved successfully";
}
else {
echo "Image moved failed";
}
?>
OUTPUT:
So, in this tutorial, you learned how to move a file in PHP using the rename() function. If a file remains and exists, it will be overwritten. If you use the same directory to move, this function will give a warning. I hope, this will help you. Thank you.