6 Ways To Move Files In PHP (Simple Examples)

Welcome to a quick tutorial on how to move files in PHP. Need to move a file from one folder into another?

Moving files in PHP is as simple as using a single function – rename("SOURCE.FILE", "FOLDER/TARGET.FILE"). Yes, there is no move file function in PHP, and we literally “rename” a file into another folder.

That should cover the basics, but things are different when it comes to “advanced file moving” – Read on for more examples!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

WAYS TO MOVE FILES IN PHP

All right, let us now get into the various ways and examples of how to move files in PHP.

 

TUTORIAL VIDEO

 

1) BASIC RENAME FILE

1-rename.php
<?php
// NOTE: IF THERE IS AN EXISTING NEW.TXT, IT WILL BE OVERRIDEN.
echo rename("old.txt", "new.txt") ? "OK" : "ERROR";

As in the introduction, changing a file name is as easy as using the rename() function. But please take note that if there is an existing new.txt, it will be overridden without any warning.

 

 

2) BASIC MOVE FILE

2-move.php
<?php
$source = "old.txt";
$destination = "d:/temp/new.txt";
echo rename($source, $destination) ? "OK" : "ERROR" ;

As in the introduction again, there is no move() function in PHP – We literally just use rename() to move a file from one directory to another.

 

3) MOVE WITHOUT OVERRIDING

3-safe-move.php
<?php
// (A) MOVE WITHOUT OVERRIDE
function safemove ($src, $dest) {
  if (file_exists($dest)) { return false; }
  return rename($src, $dest);
}
 
// (B) GO!
echo safemove("old.txt", "new.txt") ? "OK" : "ERROR" ;

To prevent overriding on moving files, we can do a simple file_exists() check – Then, you decide. Either don’t move the file or choose a different file name.

 

 

4) MOVE FILES OF CERTAIN EXTENSIONS

4-move.ext.php
<?php
function movetype ($ext, $src, $dest) {
  // (A) CREATE DESTINATION FOLDER
  if (!file_exists($dest)) { 
    mkdir($dest); 
    echo "$dest created\r\n";
  }

  // (B) GET ALL FILES
  $files = glob($src."*.{".$ext."}", GLOB_BRACE);

  // (C) MOVE
  if (count($files)>0) { foreach ($files as $f) {
    $moveTo = $dest . basename($f);
    echo rename($f, $moveTo) 
      ? "$f moved to $moveTo\r\n"
      : "Error moving $f to $moveTo\r\n";
  }}
}
movetype("jpg,png,gif", "d:/from/", "d:/to/");

Only want to move certain types of files in a folder? Use the glob() function to help filter out those files first, then move them one-by-one.

 

 

5) MOVE FILES TO ANOTHER SERVER

5a-send.php
<?php
// (A) CURL INIT + OPTIONS
$file = "test.txt"; // File to move
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://localhost/4b-recv.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, [
  "up" => curl_file_create($file), // NOTE: PHP 5.5+ ONLY
  "key" => "value" // OPTIONAL EXTRA FIELDS
]);
 
// (B) SEND FILE
$results = curl_exec($curl);
curl_close($curl);
 
// (C) DELETE LOCAL FILE AFTER SUCCESSFUL SEND
if ($results == "OK") {
  unlink($file);
  print_r($results);
}

There are actually quite a number of ways to move files from one server to another. This is a “PHP way” if you don’t want to set up an FTP server, shared drive, or anything of that sort.

On the “source server”, we will use CURL (client URL) to send the file to the “destination server”. Thereafter, we delete the file after a successful transfer.

 

 

5b-recv.php
<?php
// (A) YOU MIGHT WANT TO SECURE THIS SCRIPT BY CHECKING THE REQUESTOR
/*
if ($_SERVER['REMOTE_ADDR'] != "SERVER IP ADDRESS") { 
  http_response_code(403); // forbidden
  exit("NO PERMISSION TO ACCESS"); 
}
*/
// (B) WORKS THE SAME AS REGULAR FILE UPLOAD
// move_uploaded_file(SOURCE, DESTINATION)
echo move_uploaded_file($_FILES["up"]["tmp_name"], $_FILES["up"]["name"])
  ? "OK" : "ERROR" ;
 
// (C) FOR DEBUGGING
// print_r($_SERVER);
// print_r($_POST);
// print_r($_FILES);

On the “destination server”, we handle the file transfer just like a “normal file upload”. But you might want to protect this script a little more – Verify the identity of the client, restrict by IP address, or maybe set a “secret key”.

 

6) MOVE FILES WITH COMMAND PROMPT

6-command-move.php
<?php
// WINDOWS
echo exec("move source.txt destination.txt");
 
// LINUX
echo exec("mv source.txt destination.txt");

Finally, this is not exactly using PHP to move files… But we are running a shell command to move files from PHP.

 

 

EXTRAS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

THE SUMMARY

Function Description Reference Link
rename(FROM, TO) Rename or move a file. Click Here
file_exists(FILE) Checks if the target file exists. Click Here
mkdir(FOLDER) Create a folder. Click Here
glob(PATTERN) Get all pathnames for the given pattern/target folder. Click Here
basename(PATH) Get the trailing file or folder name for the given path. Click Here
curl_init()

curl_setopt()

curl_close()

PHP Client URL. Click Here
exec() Run a shell command. Click Here

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “6 Ways To Move Files In PHP (Simple Examples)”

  1. how can i filter the files by name?
    example :

    there are 3 files,
    10_example1.pdf
    20_example2.pdf
    30_example3.pdf

    and 3 folder 10, 20 and 30

    so i want each file is moved to certain folder, is this possible?

Leave a Comment

Your email address will not be published. Required fields are marked *