PHP: Copy, Rename or Move a File

PHP can only copy, rename or move files that are of the same owner with who is running the PHP script. After making sure of this, you can proceed to:

Copy a file to another place in PHP:

$old = '/tmp/yesterday.txt';
$new = '/tmp/today.txt';
copy($old, $new) or die("Unable to copy $old to $new.");

Rename a file and give it a new name:

$old = '/tmp/today.txt';
$new = '/tmp/tomorrow.txt';
rename($old, $new) or die("Unable to rename $old to $new.");

Move a file to a new place in PHP:

if (copy("/tmp/code.c","/usr/local/src/code.c")) {
  unlink("/tmp/code.c");
}

Apparently you must make sure the copying is successful before doing the deletion.

Of course you can always execute a native Linux shell command such as ‘cp’ and ‘mv’ to do the dirty work for you instead of resorting to a PHP function. In this situation, you need the php function exec() to execute an external command.

17 thoughts on “PHP: Copy, Rename or Move a File”

  1. Hi, maybe you could help me with a problem i’m having, i need ti rename a file, with a specific name, how can i create a function that let do the following, if the file exist, rename the file with a new name like, document.php, document_2.php, document_3.php, document_4.php. i need to create a function to do that, when it renames a file rename it with the next number.

    thank you

    1. Two and half years overdue but maybe it can help someone else. Amazing that I was just using this code. Maybe there’s a better way but I’ve used something similar so here’s a function to achieve that.

      $file = “/files/docs/document.php”;
      $file = rename_existing($file);

      returns full path with /document_1.php if it exists, or /document_2.php if document_1.php exists.
      Returns same filename if file doesn’t exist, Simple really

      //add _# to file name if exists
      function rename_existing($file){
      $ext = strtolower(end(explode(“.”, basename( $file ))));
      $filename = basename($file, “.$ext”)
      $dir = str_replace(“$filename.$ext”, “”, $file);

      if(file_exists($dir . “$filename.$ext”)){
      for ($i = 1; ; $i++) { //I don’t know why I used for instead of while
      $new_name = $dir . $filename . ‘_’ . $i . $ext;
      if (!file_exists($new_name)) {
      return $new_name;
      break;
      }
      }
      }
      else{ return $file; }
      }

      Sorry, it’s untested but I’m sure it can be fixed or improved easily

  2. Pingback: Safely and Quickly Transfer Files between Your Hosts / Hosting Accounts / Servers with scp command

  3. You can easy move files with rename: rename(“/tmp/code.c”,”/usr/local/src/code.c”)

  4. Please go and read php documentation for “rename” . What are you doing.
    Look here.
    $file_c = “files/file_c.txt” ;
    rename($file_c,”/userfiles/file_b.txt”); // this will move the file !!!!.
    // why to copy and then unlink .

    What are you doing people , read documentation then post any posts.
    Php programmers have problems with this , somebody thinks that he knows something and he starts publishing wrong information .

  5. Qtronik Webmaster

    You are freacking right ! We should only read the more secure way is to do that…
    Is it not secure to delete after a copy?
    Rename function do this in background anyway… is it good to decompose steps to know exactly what problem ocur ?

    A complete document should be developed on this function… 😉

  6. Pingback: PHP Move Files With Specific Format vs Move All Files | question code

  7. Don’t forget to use $_SERVER[‘DOCUMENT_ROOT’]:

    for instance:

    unlink($_SERVER[‘DOCUMENT_ROOT’].”/tmp/code.c”);

    and so on with all the others. Otherwise it will still not work. Using only “/tmp/code.c” is what you do only when calling upon the filename with the attribute href=”…” or src=”..” in html elements like <a>, and or in the css background-image: url (“…”). The above examples of both the author and commentators are far too simplistic for a beginner to get it right, but they do have some general usefulness as a reminder if you are advanced enough in PHP and capable of editing them to your needs. And you should especially test everything thoroughly before ever posting a routine. Alas, this is usually not bothered to be done by most know-it-all posters. It’s a pitty that most posts are either incomplete or extremely lazy, buggy or downright faulty and never tested by their authors.

  8. Hi,
    i m facing errors like below while using rename function().

    here is my code:

    output/errors:
    Warning: rename(/learn/sangna/tmp_file.txt,/learn/sangna/php/my_file.txt) [function.rename]: No such file or directory in D:\Program Files\Apache Software Foundation\Apache2.2\htdocs\learn\sangna\rename.php on line 4

  9. $old = “/learn/sangna/tmp_file.txt”;
    $new = “/learn/sangna/php/my_file.txt”;
    rename($old, $new) or die(“Unable to rename $old to $new.”);

Comments are closed.

Scroll to Top