简体   繁体   中英

Copy entire directory and content from one location to another using PHP

I am trying to copy an entire folder from one location to another using PHP, but it doesn't seem to work:

$username = "peter" //this is just an example.
$userdir = "../Users/".$username."/";
mkdir($userdir);// create folder 

// copy image folder
$source = "templates/template1/images/";//copy image folder -source
$dest = $userdir;

function copyr($source, $dest){
// Simple copy for a file
if (is_file($source)) {
$c = copy($source, $dest);
chmod($dest, 0777);
return $c;
}

// Make destination directory
if (!is_dir($dest)) {
$oldumask = umask(0);
mkdir($dest, 0777);
umask($oldumask);
}

// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == "." || $entry == "..") {
continue;
}

}

// Clean up
$dir->close();
return true;
}

I have also tried other solutions I saw online without success. Would appreciate any help possible


I also just tried this script without any luck.

I just tried another script and still no luck :(.

$template_homepage = "templates/template1/index.php";//path to default template homepage
$homepage = file_get_contents($template_homepage);//get default homepage structure


$username = testuser;// folder name for store


if (trim($username) == '') {
die("An error occured.");
} else {
$userdir = "../Users/".$username."/";
mkdir($userdir);// create folder for new website

// copy image folder
$src = 'templates/template1/images';//copy image folder -source
$dst = $userdir;

   function rcopy($src, $dst) {
  if (file_exists($dst)) rrmdir($dst);
  if (is_dir($src)) {
mkdir($dst);
$files = scandir($src);
foreach ($files as $file)
if ($file != "." && $file != "..") rcopy("$src/$file", "$dst/$file"); 
}
  else if (file_exists($src)) copy($src, $dst);

}




$fh = fopen($userdir."index.php", 'w') or die("An error occured. ");// create home page in users folder

   // $stringData = $title; //."\n";//
   fwrite($fh, $homepage);// write homepage structure into new homepage file.
    fclose($fh);// close new homepage file.
 $launchpage = "../Users/".$username."/"; // launch new homepage file.
header("Location: $launchpage");
   }

为什么不使用exec并使用OS命令将文件夹复制过来?

exec('cp -r sourcedir destdir');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM