Open In App

How to move a file into a different folder on the server using PHP?

Last Updated : 24 May, 2019
Like Article

The move_uploaded_file() function and rename() function is used to move a file into a different folder on the server. In this case, we have a file already uploaded in the temp directory of server from where the new directory is assigned by the method. The file temp is fully moved to a new location. The move_uploaded_file() ensures the safety of this operation by allowing only those files uploaded through PHP to be moved. Thus to move an already uploaded file we use the rename() method.


move_uploaded_file ( string $Sourcefilename, string $destination ) : bool
rename ( string $oldname, string $newname [, resource $context ] ) : bool
  • move_upload_file() method: This function checks to ensure that the source file or ‘$Sourcefilename’ in the syntax is a valid upload file (meaning that it was uploaded via PHP’s HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination or ‘$destination’ in the syntax.
    The sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system. Note that if in case the destination file already exists, it will be overwritten. Due to this reason, a file should be checked first for its availability and then the only action must be taken.
  • rename() method: This method attempts to rename oldname to newname, moving it between directories if necessary. If newname file exists then it will be overwritten. If renaming newname directory exists then this function will emit a warning.

Example: This example is a code which uploads a file in a directory names Uploads and then it changes its path to another directory named as New.


<!DOCTYPE html>
         Move a file into a different
         folder on the server
    <form action="upfile.php" method="post"
        <input type="file" name="file" id="file">
        <input type="submit" name="submit" value="Submit">


// The target directory of uploading is uploads
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uOk = 1;
if(isset($_POST["submit"])) {
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "file already exists.<br>";
        $uOk = 0;
    // Check if $uOk is set to 0 
    if ($uOk == 0) {
        echo "Your file was not uploaded.<br>";
    // if uOk=1 then try to upload file
    else {
        // $_FILES["file"]["tmp_name"] implies storage path
        // in tmp directory which is moved to uploads
        // directory using move_uploaded_file() method
        if (move_uploaded_file($_FILES["file"]["tmp_name"],
                                            $target_file)) {
            echo "The file ". basename( $_FILES["file"]["name"])
                        . " has been uploaded.<br>";
            // Moving file to New directory 
            if(rename($target_file, "New/"
                        basename( $_FILES["file"]["name"]))) {
                echo "File moving operation success<br>";
            else {
                echo "File moving operation failed..<br>";
        else {
            echo "Sorry, there was an error uploading your file.<br>";

Note: The directories Uploads and New are already existing once and thus you will have to make them if they are not available inside the server.

Code running:

Code running with use of rename method (Moving to New)

Important methods:

  • file_exists($target_file): This method is used to check the existence of path. If it exists then it returns true else it returns false.
  • basename( $_FILES[“file”][“name”] ): This method is used to get the name of the chosen file and its specialty lies in the fact that it operates on the input string provided by the user and is unaware of the actual file system and provides usage of security feature provided by the browsers.

Similar Reads

How to include content of a PHP file into another PHP file ?
Including the content of a PHP file into another file reduces the complexity of code by reducing the code and improving its modularity by splitting the code into different files so that it is easy to understand and manage. There are two ways to do it by using the following PHP functions. PHP include() Function: It will show the warning if the file
2 min read
Deleting all files from a folder using PHP
In PHP, files from a folder can be deleted using various approaches and inbuilt methods such as unlink, DirectoryIterator and DirectoryRecursiveIterator. Some of these approaches are explained below: Approach 1: Generate a list of files using glob() method Iterate over the list of files. Check whether the name of files is valid. Delete the file usi
3 min read
How to Create a Folder if It Doesn't Exist in PHP ?
We can easily create a folder in PHP, but before that, you have to check if the folder or directory already exists or not. So In this article, you will learn both to Check and Create a folder or directory in PHP. Methods: file_exists(): It is an inbuilt function that is used to check whether a file or directory exists or not.is_dir(): It is also us
3 min read
Load CSV Data into MySQL Server Using PHP
In this article, we are going to store data present in CSV file into MySQL database using PHP in XAMPP server and display the data on web browser. Comma Separated Value (CSV) is a text file containing data contents. It facilitates the storage of data in a table like structure. CSV files are stored with a CSV extension. A CSV file can be created wit
3 min read
Convert JSON file into CSV file and displaying the data using Node.js
There are so many ways to store data for better understanding for individual purposes, in few cases, JSON files will be more suitable in few cases, CSV files, and there are also lots of other types as well like XML, etc. In this article, we will convert the JSON file data into CSV file data and also display that through Node.js. JSON stands for Jav
3 min read
How to Load an HTML File into Another File using jQuery?
Loading HTML files into other HTML files is a common practice in web development. It helps in reusing HTML components across different web pages. jQuery is a popular JavaScript library, that simplifies this process with its .load() method. Approach 1: Basic Loading with .load() MethodThe .load() method in jQuery is used to load data from the server
2 min read
How to link back out of a folder using the a-href tag?
Introduction: Whenever we make a project it is generally distributed among various folders. That is generally done to improve the connectivity and readability for the various web developers working on the same project. For example: The above classification is just an example but the classification can be bigger. So if you have to call an image from
2 min read
How to Move DataTable Search Filter to a Different Row with jQuery ?
We Move the DataTable Search Filter to a Different Row with jQuery. To achieve this functionality, you must know what is a Search filter and where we can use it, a search filter typically refers to a mechanism used to filter and display specific elements from a set of elements based on certain criteria. This is often used in scenarios where you hav
3 min read
jQuery | Move an element into another element
There are two methods to move an element inside another element are listed below: Method 1: Using append() method: This append() Method in jQuery is used to insert some content at the end of the selected elements. Syntax: $(selector).append( content, function(index, html) ) Parameters: This method accepts two parameters as mentioned above and descr
2 min read
Spectre Folder Structure
Spectre is a lightweight, responsive, and modern CSS framework, which provides the extensible with faster development. It facilitates the responsive layout system based on the flex-box property, along with providing the basic elements &amp; typography styling. To use Spectre, better to have minimum knowledge about folder structure. We are not recom
2 min read