Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Copy the contents of a directory from one location to another with PHP

Given a source and destination directory, the following function will copy contents between the two locations. Generally speaking, this isn't the code I use myself. I'll generally log into another remote server using PHP's FTP functions ... although the same principles apply.

To copy a single file, use PHP's copy() function. It's requires a path (or URL) to your source and path to a destination location. Because filenames are required, you may alter the name of the destination file.

PHP Function

This function will recursively copy all contents of a directory.

1
<?php 
2
/*
3
 Copy the contents of a directory from one location to another with PHP
4
 http://www.beliefmedia.com/copy-directory-php
5
*/
6
 
7
function beliefmedia_recurse_copy($src, $dst) {
8
 
9
  /* Returns false if src doesn't exist */
10
  $dir = @opendir($src);
11
 
12
  /* Make destination directory. False on failure */
13
  if (!file_exists($dst)) @mkdir($dst);
14
 
15
  /* Recursively copy */
16
  while (false !== ($file = readdir($dir))) {
17
 
18
      if (( $file != '.' ) && ( $file != '..' )) {
19
         if ( is_dir($src . '/' . $file) ) beliefmedia_recurse_copy($src . '/' . $file, $dst . '/' . $file);
20
         else copy($src . '/' . $file, $dst . '/' . $file);
21
      }
22
 
23
  }
24
 closedir($dir);
25
}
26
 
27
/* Source directory (can be an FTP address) */
28
$src = '/home/your/public_html/source/directory';
29
 
30
/* Full path to the destination directory */
31
$dst = '/home/your/public_html/destination/directory';
32
 
33
/* Usage */
34
beliefmedia_recurse_copy($src, $dst);

If you find that the source directory has a lot of content and is large in size (causing the copy to time out), you can use the following to potentially fix your problem. The value you set will be the script maximum execution time.

set_time_limit(0);

If you get an error message because your server is configured in safe-mode, try this rather than the above:

1
if (!ini_get('safe_mode')) {
2
 set_time_limit(25);
3
}

A value of '0' will set the execution timeout limit to 'infinity'.

Download


Title: Copy directory contents with PHP
Description: Copy the contents of a directory from one location to another with PHP.
  Download • Version 0.2, 616.0B, zip, Category: PHP Code & Snippets

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  AUS Eastern Standard Time (Virginia)

  Want to have a chat?
 

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment

READY TO HAVE A CHAT? CALL US ANYTIME ON 1300 235 433