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!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes PHP Move Useful Bits & Links
Tutorial Video The End

 

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

WAYS TO MOVE FILES IN PHP

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

 

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.

 

 

USEFUL BITS & LINKS

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

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEAT SHEET

How To Move Files In PHP (Click To Enlarge)

 

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!

Leave a Comment

Your email address will not be published.