Last active
November 18, 2015 01:14
-
-
Save mauriciogofas/126f0c1fd156d3e3364d to your computer and use it in GitHub Desktop.
#php - copy all files (recursive) in a directory to another
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// function definition | |
// copy a directory and its contents | |
function copyTree($source, $destination) { | |
if (file_exists($source)) { | |
// create source pointer | |
$dp = opendir($source) or die ('ERROR: Cannot open directory'); | |
// if destination directory does not exist | |
// create it | |
if (!file_exists($destination)) { | |
mkdir($destination) or die('ERROR: Cannot create directory ' . $destination); | |
} | |
// read source contents | |
// if file, copy to destination | |
// if directory, call recursively | |
while ($file = readdir($dp)) { | |
if ($file != '.' && $file != '..') { | |
if (is_file("$source/$file")) { | |
copy("$source/$file", "$destination/$file") or die('ERROR: Cannot copy file ' . "$source/$file"); | |
} else if (is_dir("$source/$file")) { | |
copyTree("$source/$file", "$destination/$file"); | |
} | |
} | |
} | |
// close source pointer | |
closedir($dp); | |
} | |
} | |
?> | |
<?php | |
if (file_exists('/home/username/public_html/')) { | |
copyTree('/home/username/public_html/', 'beta'); | |
echo 'File(s) copied.'; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment