Reputation: 1
I want to copy all files from one folder to another folder using PHP scripts. So if I have a file demo/index.php
then I would like to copy index.php
to test/index.php
Upvotes: 0
Views: 2122
Reputation: 2995
Use scandir() to scan all the files in directory and then foreach file copy them into new directory using copy()
Here is the code to copy all the files, try this...
<?php
$dir = 'img';
$files = scandir($dir);
///path to new directory..
$new_dir = 'img2';
foreach($files as $file)
{
if(!empty($file) && $file != '.' && $file != '..')
{
$source = $dir.'/'.$file;
$destination = $new_dir.'/'.$file;
if(copy($source, $destination))
{
echo "Copied $file...\n";
}
}
}
?>
Upvotes: 0
Reputation: 429
You can use this function to recursively copy files and folders:
function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755))
{
$result=false;
if (is_file($source)) {
if ($dest[strlen($dest)-1]=='/') {
if (!file_exists($dest)) {
cmfcDirectory::makeAll($dest,$options['folderPermission'],true);
}
$__dest=$dest."/".basename($source);
} else {
$__dest=$dest;
}
$result=copy($source, $__dest);
@chmod($__dest,$options['filePermission']);
} elseif(is_dir($source)) {
if ($dest[strlen($dest)-1]=='/') {
if ($source[strlen($source)-1]=='/') {
//Copy only contents
} else {
//Change parent itself and its contents
$dest=$dest.basename($source);
if(!file_exists($dest)) mkdir($dest);
@chmod($dest,$options['filePermission']);
}
} else {
if ($source[strlen($source)-1]=='/') {
//Copy parent directory with new name and all its content
if(!file_exists($dest)) mkdir($dest,$options['folderPermission']);
@chmod($dest,$options['filePermission']);
} else {
//Copy parent directory with new name and all its content
if(!file_exists($dest)) mkdir($dest,$options['folderPermission']);
@chmod($dest,$options['filePermission']);
}
}
$dirHandle=opendir($source);
while($file=readdir($dirHandle))
{
if($file!="." && $file!="..")
{
if(!is_dir($source."/".$file)) {
$__dest=$dest."/".$file;
} else {
$__dest=$dest."/".$file;
}
//echo "$source/$file ||| $__dest<br />";
$result=smartCopy($source."/".$file, $__dest, $options);
}
}
closedir($dirHandle);
} else {
$result=false;
}
return $result;
}
Then execute in this way, for files:
smartCopy('demo/index.php', 'test/index.php');
or for folders:
smartCopy('demo/', 'test/');
Upvotes: 1