Last active
February 12, 2022 15:50
-
-
Save nagiyevelchin/da5cce076d8909e9c6cf56bb8d99a81e to your computer and use it in GitHub Desktop.
Copy a file, or recursively copy a folder and its contents in PHP
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 | |
/** | |
* Copy a file, or recursively copy a folder and its contents | |
* | |
* @author Aidan Lister <[email protected]> | |
* @version 1.0.1 | |
* @link http://aidanlister.com/2004/04/recursively-copying-directories-in-php/ | |
* @param string $source Source path | |
* @param string $dest Destination path | |
* @return bool Returns TRUE on success, FALSE on failure | |
*/ | |
function copyr($source, $dest) { | |
// Check for symlinks | |
if (is_link($source)) { | |
return symlink(readlink($source), $dest); | |
} | |
// Simple copy for a file | |
if (is_file($source)) { | |
return copy($source, $dest); | |
} | |
// Make destination directory | |
if (!is_dir($dest)) { | |
mkdir($dest); | |
} | |
// Loop through the folder | |
$dir = dir($source); | |
while (false !== $entry = $dir->read()) { | |
// Skip pointers | |
if ($entry == '.' || $entry == '..') { | |
continue; | |
} | |
// Deep copy directories | |
copyr("$source/$entry", "$dest/$entry"); | |
} | |
// Clean up | |
$dir->close(); | |
return true; | |
} | |
/** | |
* Makes directory | |
* @link http://stackoverflow.com/questions/5425891/check-if-directory-exists-php | |
* @param string $pathname The directory path. | |
* @param int $mode [optional]<p> | |
* The mode is 0777 by default, which means the widest possible | |
* access. For more information on modes, read the details | |
* on the <b>chmod</b> page. | |
* </p> | |
* @since 11/23/12 12:43 PM | |
* @return bool <p><b>INT</b> on success or <b>FALSE</b> on failure. | |
* 1 - The directory $pathname was successfully created. | |
* </p> | |
*/ | |
function mkdir($pathname, $mode = 0777) { | |
$p = ""; | |
$pathname = explode('/', $pathname); | |
foreach ($pathname as $path) { | |
$p .= $path . "/"; | |
if (!file_exists($p)) { | |
if (!mkdir($p, $mode)) { | |
return false; | |
} | |
} | |
} | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment