Skip to content

Instantly share code, notes, and snippets.

@voku
Last active August 29, 2015 14:02
Show Gist options
  • Save voku/c11382b3e2ddca192479 to your computer and use it in GitHub Desktop.
Save voku/c11382b3e2ddca192479 to your computer and use it in GitHub Desktop.
copy files and dirs via php
<?php
/**
* recursively creates & chmod directories
*
* @param String $name
* @param Int $mode (null for default value from config)
*
* @return Boolean
*/
function makeDir($name, $mode = null)
{
// if it exists, just return true
if (file_exists($name)) {
return true;
}
// if more than one level, try parent first
if (dirname($name) != ".") {
$return = makeDir(dirname($name));
// if creating parent fails, we can abort immediately
if (!$return) {
return false;
}
}
if ($mode === null) {
$mode_dec = '0777';
} else {
$mode_dec = octdec($mode);
}
$oldumask = umask(0);
$return = mkdir($name, $mode_dec);
chmod($name, $mode_dec);
umask($oldumask);
return $return;
}
/**
* return list of dir and files without "." && ".."
*
* @param String $dir directory
* @param Boolean $recursive
*
* @return Array
*/
function dir_scan($dir, $recursive = false)
{
$f = array();
if (is_dir($dir) && $dh = opendir($dir)) {
while ($fn = readdir($dh)) {
if ($fn != '.' && $fn != '..') {
$f[] = $dir . '/' . $fn;
if ($recursive === true) {
$sub_dir = $dir . '/' . $fn;
if (is_dir($sub_dir)) {
$f = array_merge($f, dir_scan($sub_dir));
}
}
}
}
}
return $f;
}
/**
* copy a file and correct the permissions
*
* @param string $source source file
* @param string $dest destination file
*
* @return bool
*/
function file_copy($source, $dest)
{
$return = false;
if (is_file($source)) {
$return = copy($source, $dest);
chmod($dest, fileperms($source));
}
return $return;
}
/**
* Copy all the content of a directory
*
* @param string $source source directory
* @param string $dest destination directory
*/
function dir_copy($source, $dest)
{
if (is_file($source)) {
file_copy($source, $dest);
} else {
if (!is_dir($dest)) {
makeDir($dest);
}
$l = dir_scan($source);
if ($l) {
foreach ($l as $f) {
dir_copy("$source/$f", "$dest/$f");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment