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

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.

Syntax:

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.

Upload.html

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
         Move a file into a different
         folder on the server
    </title>
</head>
  
<body>
    <form action="upfile.php" method="post"
            enctype="multipart/form-data">
          
        <input type="file" name="file" id="file">
          
        <br><br>
          
        <input type="submit" name="submit" value="Submit">
    </form>
</body>
  
</html>                    

chevron_right


upfile.php

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// 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>";
        }
    }
}
  
?>

chevron_right


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.


My Personal Notes arrow_drop_up

Im a final year MCA student at Panjab University, Chandigarh, one of the most prestigious university of India I am skilled in various aspects related to Web Development and AI I have worked as a freelancer at upwork and thus have knowledge on various aspects related to NLP, image processing and web

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.