copy recursive files and folders but skip parent - php

function copy_directory( $source, $destination ) {
if ( is_dir( $source ) ) {
#mkdir( $destination );
$directory = dir( $source );
while ( FALSE !== ( $readdirectory = $directory->read() ) ) {
if ( $readdirectory == '.' || $readdirectory == '..' ) {
continue;
}
$PathDir = $source . '/' . $readdirectory;
if ( is_dir( $PathDir ) ) {
copy_directory( $PathDir, $destination . '/' . $readdirectory );
continue;
}
copy( $PathDir, $destination . '/' . $readdirectory );
}
$directory->close();
}else {
copy( $source, $destination );
}
}
this is my script for copy whole dirs and files to another destination. But i have small problem
My folders are like:
cinch.v2.1.1\cinch\cinch\other folders and files
loopy.v2.1.3\loopy\loopy\other folders and files
musy.v3.1.4\musy\musy\other folders and files
...
i need to copy just last (depth 3) cinch, loopy, musy folder with subfolders and files and not whole structure. How to change the script.
and copy structure should looks like this:
cinch\other folders and files
loopy\other folders and files
musy\other folders and files
I start with
if (strpos($readdirectory, '.') === false && strpos($readdirectory, '_') === false) {
but this not working as it must.

You must first look for level 3 directories and then copy these to your destination:
function copy_directory(...) {
...
}
function copy_depth_dirs($source, $destination $level)
{
$dir = dir($source);
while (($entry = $dir->read()) !== FALSE) {
if ($entry != '.' && $entry != '..' && is_dir($entry)) {
if ($level == 0) {
copy_directory($source . '/' . $entry, $destination);
} else {
copy_depth_dirs($source . '/' . $entry, $destination, $level - 1);
}
}
}
}
copy_depth_dirs('cinch.v2.1.1', $destination, 3);

Related

how to check in a loop for a folder or a file in php

For copying a folder and a file in php i use this loop:
if(is_dir($_POST['copyfile'])) {
$copyfolder = recurse_copy($src_folder,$dest_folder);
if( $copyfolder) {
echo 'succeed-folder';
exit;
}
else {
echo 'failed-folder';
exit;
}
}
else {
$copy = copy( $src_file_url, $dest_file );
if($copy) {
echo 'succeed-file';
exit;
}
else {
echo 'failed-file';
exit;
}
}
When copying a folder instead of a file, i check it with: if(is_dir($_POST['copyfile']))
In the case that it is really a folder, it copies the files in the folder correctly but gives me this echo: failed-folder
So there must be something wrong with the loop. What is wrong with the loop? I only want to distinguish if a folder or a file was copied with an echo
This is the function:
function recurse_copy($src_folder,$dest_folder ) {
$copydir = opendir($src_folder);
while(false !== ( $folder = readdir($copydir)) ) {
if (( $folder != '.' ) && ( $folder != '..' )) {
if ( is_dir($src_folder . '/' . $folder) ) {
recurse_copy($src_folder. '/' . $folder,$dest_folder . '/' . $folder);
}
else {
copy($src_folder. '/' . $folder , $dest_folder . '/' . $folder);
}
}
}
closedir($copydir);
}
You do not have a return statement at all. Therefore the function returns "void" which is evaluated to false. You need to return a bool value indicating if an error occurred.
This version does not stop the copy process, it just tracks if all operations were successful:
function recurse_copy($src_folder,$dest_folder ) {
$success = true;
$copydir = opendir($src_folder);
if(!$copydir)
return false;
while(false !== ( $folder = readdir($copydir)) ) {
if (( $folder != '.' ) && ( $folder != '..' )) {
if ( is_dir($src_folder . '/' . $folder) ) {
$success = recurse_copy($src_folder. '/' . $folder,$dest_folder . '/' . $folder) && $success;
}
else {
$success = copy($src_folder. '/' . $folder , $dest_folder . '/' . $folder) && $success;
}
}
}
closedir($copydir);
return $success;
}
An example of how you could alter the recurse_copy() function is to test each point which can be a problem - opendir(), mkdir() and copy() and they return false if any step fails. So this value is checked to stop the loop on failure and then returned at the end...
function recurse_copy($src,$dst) {
$dir = opendir($src);
// As long as opendir is OK, then mkdir, or set failure
$success = ($dir)?mkdir($dst):false;
while($success && (false !== ( $file = readdir($dir))) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
$success = recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
$success = copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
if ( $dir ) {
closedir($dir);
}
return $success;
}

recursively copy a specific file extension php

I am writing a function to recursively copy a specific file type from one folder to the other, but the function copies all the files in the folder.
function recurse_copy($src, $dst) {
$dir = opendir($src);
#mkdir($dst);
while (false !== ( $file = readdir($dir))) {
if (( $file != '.' ) && ( $file != '..' )) {
if (is_dir($src . '/' . $file)) {
if ($file->getExtension() == "pdf") {
recurse_copy($src . '/' . $file, $dst . '/' . $file);
}
} else {
copy($src . '/' . $file, $dst . '/' . $file);
}
}
} closedir($dir);
}
// if statements for
$itp = new RecursiveDirectoryIterator("foldername/", > FilesystemIterator::SKIP_DOTS);
$displayp = Array('pdf');
$i = 0;
foreach (new RecursiveIteratorIterator($itp) as $filepop) {
if (in_array(strtolower(array_pop(explode('.', $filepop))), $displayp))
if ($filepop->getExtension() == "pdf") {
echo >
recurse_copy("a", "b");
}
}
$itcopy = new RecursiveDirectoryIterator("foldername/", FilesystemIterator::SKIP_DOTS);
$displayp = Array ( 'pdf' );
foreach(new RecursiveIteratorIterator($itcopy) as $filecopy)
{
if (in_array(strtolower(array_pop(explode('.', $filecopy))), $displayp))
if ($filecopy->getExtension()=="pdf"){
copy($filecopy->getrealPath(),'pdf_folder/'.$filecopy->getFilename()) ;
}
}

move all files and folders in a folder to another?

I want to move all files and folders inside a folder to another folder. I found a code to copy all files inside a folder to another folder.
move all files in a folder to another
// Get array of all source files
$files = scandir("source");
// Identify directories
$source = "source/";
$destination = "destination/";
// Cycle through all source files
foreach ($files as $file) {
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
}
}
// Delete all successfully-copied files
foreach ($delete as $file) {
unlink($file);
}
How do I change this to move all folders and files inside this folder to another folder.
This is what i use
// Function to remove folders and files
function rrmdir($dir) {
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file)
if ($file != "." && $file != "..") rrmdir("$dir/$file");
rmdir($dir);
}
else if (file_exists($dir)) unlink($dir);
}
// Function to Copy folders and files
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 );
}
Usage
rcopy($source , $destination );
Another example without deleting destination file or folder
function recurse_copy($src,$dst) {
$dir = opendir($src);
#mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
Please See: http://php.net/manual/en/function.copy.php for more juicy examples
Thanks
:)
Use rename instead of copy.
Unlike the C function with the same name, rename can move a file from one file system to another (since PHP 4.3.3 on Unix and since PHP 5.3.1 on Windows).
You need the custom function:
Move_Folder_To("./path/old_folder_name", "./path/new_folder_name");
function code:
function Move_Folder_To($source, $target){
if( !is_dir($target) ) mkdir(dirname($target),null,true);
rename( $source, $target);
}
Think this should do the trick:
http://php.net/manual/en/function.shell-exec.php
shell_exec("mv sourcedirectory path_to_destination");
Hope this help.
I think the answers are not complete for me, beacuse DIRECTORY_SEPARATOR are not defined on any answer (thans to Edgar Aivars for remember that!), but I want to write my solution for move (rename), copy and delete directory structures (based on this post info, the credits are for yours!).
defined('DS') ? NULL : define('DS',DIRECTORY_SEPARATOR);
function full_move($src, $dst){
full_copy($src, $dst);
full_remove($src);
}
function full_copy($src, $dst) {
if (is_dir($src)) {
#mkdir( $dst, 0777 ,TRUE);
$files = scandir($src);
foreach($files as $file){
if ($file != "." && $file != ".."){
full_copy("$src".DS."$file", "$dst".DS."$file");
}
}
} else if (file_exists($src)){
copy($src, $dst);
}
}
function full_remove($dir) {
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file){
if ($file != "." && $file != ".."){
full_remove("$dir".DS."$file");
}
}
rmdir($dir);
}else if (file_exists($dir)){
unlink($dir);
}
}
I hope this hepls anyone! (lile me in the future :D )
EDIT: Spell corrections... :(
My attempt at a recursive move function, after days of research and going through other excellent examples out there.
It provides for an overwriteExisting flag for choice. Consequently, if the overwriteExisting flag is false, the file will not be moved and the folder containing the file would not be removed.
function moveRecursive($sourcePath, $targetPath, $overwriteExisting) {
clearstatcache(); // not sure if this helps, or is even required.
$dir = opendir($sourcePath);
while (($file = readdir($dir)) !== false) {
echo nl2br($file . "\n");
if ($file != "." && $file != "..") {
if (is_dir($sourcePath . "/" . $file) == true) {
if (is_dir($targetPath. "/" . $file) == false) {
// I believe rename would be faster than copying and unlinking.
rename($sourcePath . "/" . $file, $targetPath. "/" . $file);
} else {
moveRecursive($sourcePath . "/" . $file, $targetPath ."/" . $file, $overwriteExisting);
if ($files = glob($sourcePath . "/*")) {
// remove the empty directory.
if (#rmdir($sourcePath . "/" . $file) == false) {
echo nl2br("rmdir has not removed empty directory " . $sourcePath . "/" . $file . "\n");
}
} else {
// when overwriteExisting flag is false, there would be some files leftover.
echo nl2br("cannot remove. not empty, count = " . count(glob($sourcePath . "/*")) . " -> " . $sourcePath . "/" . $file . "\n");
}
}
} else {
if (file_exists($targetPath. "/" . $file)) {
if ($overwriteExisting == true) {
// overwrite the file.
rename($sourcePath . "/" . $file, $targetPath. "/" . $file);
}
} else {
// if the target file does not exist, simply move the file.
rename($sourcePath . "/" . $file, $targetPath. "/" . $file);
}
}
}
}
closedir($dir);
}
I have spent about 3 hours testing this in many different scenarios, and it works most of the time. Although, sometimes, it gives me an Access denied code(5) error on Windows, which I have been unable to figure out. This is why I have put the clearstatcache() function up at the top, after reading up on its documentation. I don't know whether this is its appropriate usage. I can definitely imagine that it would slow down the function.
I can also imagine that this method may be faster than the copy -> unlink cycle, because if a target sub-folder does not exist, the whole folder tree below would be just moved. However, I am not sure and don't have the experience to conduct exhaustive tests, yet.
$src = 'user_data/company_2/T1/';
$dst = 'user_data/company_2/T2/T1/';
rcopy($src, $dst); // Call function
// Function to Copy folders and files
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 );
rrmdir ( $src );
}
// Function to remove folders and files
function rrmdir($dir) {
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file)
if ($file != "." && $file != "..") rrmdir("$dir/$file");
rmdir($dir);
}
else if (file_exists($dir)) unlink($dir);
}
I use it
// function used to copy full directory structure from source to target
function full_copy( $source, $target )
{
if ( is_dir( $source ) )
{
mkdir( $target, 0777 );
$d = dir( $source );
while ( FALSE !== ( $entry = $d->read() ) )
{
if ( $entry == '.' || $entry == '..' )
{
continue;
}
$Entry = $source . '/' . $entry;
if ( is_dir( $Entry ) )
{
full_copy( $Entry, $target . '/' . $entry );
continue;
}
copy( $Entry, $target . '/' . $entry );
}
$d->close();
} else {
copy( $source, $target );
}
}

Copy entire contents of a directory to another using php

I tried to copy the entire contents of the directory to another location using
copy ("old_location/*.*","new_location/");
but it says it cannot find stream, true *.* is not found.
Any other way
Thanks
Dave
that worked for a one level directory. for a folder with multi-level directories I used this:
function recurseCopy(
string $sourceDirectory,
string $destinationDirectory,
string $childFolder = ''
): void {
$directory = opendir($sourceDirectory);
if (is_dir($destinationDirectory) === false) {
mkdir($destinationDirectory);
}
if ($childFolder !== '') {
if (is_dir("$destinationDirectory/$childFolder") === false) {
mkdir("$destinationDirectory/$childFolder");
}
while (($file = readdir($directory)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
if (is_dir("$sourceDirectory/$file") === true) {
recurseCopy("$sourceDirectory/$file", "$destinationDirectory/$childFolder/$file");
} else {
copy("$sourceDirectory/$file", "$destinationDirectory/$childFolder/$file");
}
}
closedir($directory);
return;
}
while (($file = readdir($directory)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
if (is_dir("$sourceDirectory/$file") === true) {
recurseCopy("$sourceDirectory/$file", "$destinationDirectory/$file");
}
else {
copy("$sourceDirectory/$file", "$destinationDirectory/$file");
}
}
closedir($directory);
}
As described here, this is another approach that takes care of symlinks too:
/**
* Copy a file, or recursively copy a folder and its contents
* #author Aidan Lister <aidan#php.net>
* #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
* #param int $permissions New folder creation permissions
* #return bool Returns true on success, false on failure
*/
function xcopy($source, $dest, $permissions = 0755)
{
$sourceHash = hashDirectory($source);
// 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, $permissions);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Deep copy directories
if($sourceHash != hashDirectory($source."/".$entry)){
xcopy("$source/$entry", "$dest/$entry", $permissions);
}
}
// Clean up
$dir->close();
return true;
}
// In case of coping a directory inside itself, there is a need to hash check the directory otherwise and infinite loop of coping is generated
function hashDirectory($directory){
if (! is_dir($directory)){ return false; }
$files = array();
$dir = dir($directory);
while (false !== ($file = $dir->read())){
if ($file != '.' and $file != '..') {
if (is_dir($directory . '/' . $file)) { $files[] = hashDirectory($directory . '/' . $file); }
else { $files[] = md5_file($directory . '/' . $file); }
}
}
$dir->close();
return md5(implode('', $files));
}
copy() only works with files.
Both the DOS copy and Unix cp commands will copy recursively - so the quickest solution is just to shell out and use these. e.g.
`cp -r $src $dest`;
Otherwise you'll need to use the opendir/readdir or scandir to read the contents of the directory, iterate through the results and if is_dir returns true for each one, recurse into it.
e.g.
function xcopy($src, $dest) {
foreach (scandir($src) as $file) {
if (!is_readable($src . '/' . $file)) continue;
if (is_dir($src .'/' . $file) && ($file != '.') && ($file != '..') ) {
mkdir($dest . '/' . $file);
xcopy($src . '/' . $file, $dest . '/' . $file);
} else {
copy($src . '/' . $file, $dest . '/' . $file);
}
}
}
The best solution is!
<?php
$src = "/home/www/domain-name.com/source/folders/123456";
$dest = "/home/www/domain-name.com/test/123456";
shell_exec("cp -r $src $dest");
echo "<H3>Copy Paste completed!</H3>"; //output when done
?>
With Symfony this is very easy to accomplish:
$fileSystem = new Symfony\Component\Filesystem\Filesystem();
$fileSystem->mirror($from, $to);
See https://symfony.com/doc/current/components/filesystem.html
function full_copy( $source, $target ) {
if ( is_dir( $source ) ) {
#mkdir( $target );
$d = dir( $source );
while ( FALSE !== ( $entry = $d->read() ) ) {
if ( $entry == '.' || $entry == '..' ) {
continue;
}
$Entry = $source . '/' . $entry;
if ( is_dir( $Entry ) ) {
full_copy( $Entry, $target . '/' . $entry );
continue;
}
copy( $Entry, $target . '/' . $entry );
}
$d->close();
}else {
copy( $source, $target );
}
}
Like said elsewhere, copy only works with a single file for source and not a pattern. If you want to copy by pattern, use glob to determine the files, then run copy. This will not copy subdirectories though, nor will it create the destination directory.
function copyToDir($pattern, $dir)
{
foreach (glob($pattern) as $file) {
if(!is_dir($file) && is_readable($file)) {
$dest = realpath($dir . DIRECTORY_SEPARATOR) . basename($file);
copy($file, $dest);
}
}
}
copyToDir('./test/foo/*.txt', './test/bar'); // copies all txt files
<?php
function copy_directory( $source, $destination ) {
if ( is_dir( $source ) ) {
#mkdir( $destination );
$directory = dir( $source );
while ( FALSE !== ( $readdirectory = $directory->read() ) ) {
if ( $readdirectory == '.' || $readdirectory == '..' ) {
continue;
}
$PathDir = $source . '/' . $readdirectory;
if ( is_dir( $PathDir ) ) {
copy_directory( $PathDir, $destination . '/' . $readdirectory );
continue;
}
copy( $PathDir, $destination . '/' . $readdirectory );
}
$directory->close();
}else {
copy( $source, $destination );
}
}
?>
from the last 4th line , make this
$source = 'wordpress';//i.e. your source path
and
$destination ='b';
Full thanks must go to Felix Kling for his excellent answer which I have gratefully used in my code. I offer a small enhancement of a boolean return value to report success or failure:
function recurse_copy($src, $dst) {
$dir = opendir($src);
$result = ($dir === false ? false : true);
if ($result !== false) {
$result = #mkdir($dst);
if ($result === true) {
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' ) && $result) {
if ( is_dir($src . '/' . $file) ) {
$result = recurse_copy($src . '/' . $file,$dst . '/' . $file);
} else {
$result = copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
}
return $result;
}
My pruned version of #Kzoty answer.
Thank you Kzoty.
Usage
Helper::copy($sourcePath, $targetPath);
class Helper {
static function copy($source, $target) {
if (!is_dir($source)) {//it is a file, do a normal copy
copy($source, $target);
return;
}
//it is a folder, copy its files & sub-folders
#mkdir($target);
$d = dir($source);
$navFolders = array('.', '..');
while (false !== ($fileEntry=$d->read() )) {//copy one by one
//skip if it is navigation folder . or ..
if (in_array($fileEntry, $navFolders) ) {
continue;
}
//do copy
$s = "$source/$fileEntry";
$t = "$target/$fileEntry";
self::copy($s, $t);
}
$d->close();
}
}
I clone entire directory by SPL Directory Iterator.
function recursiveCopy($source, $destination)
{
if (!file_exists($destination)) {
mkdir($destination);
}
$splFileInfoArr = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($splFileInfoArr as $fullPath => $splFileinfo) {
//skip . ..
if (in_array($splFileinfo->getBasename(), [".", ".."])) {
continue;
}
//get relative path of source file or folder
$path = str_replace($source, "", $splFileinfo->getPathname());
if ($splFileinfo->isDir()) {
mkdir($destination . "/" . $path);
} else {
copy($fullPath, $destination . "/" . $path);
}
}
}
#calling the function
recursiveCopy(__DIR__ . "/source", __DIR__ . "/destination");
For Linux servers you just need one line of code to copy recursively while preserving permission:
exec('cp -a '.$source.' '.$dest);
Another way of doing it is:
mkdir($dest);
foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $item)
{
if ($item->isDir())
mkdir($dest.DIRECTORY_SEPARATOR.$iterator->getSubPathName());
else
copy($item, $dest.DIRECTORY_SEPARATOR.$iterator->getSubPathName());
}
but it's slower and does not preserve permissions.
I had a similar situation where I needed to copy from one domain to another on the same server, Here is exactly what worked in my case, you can as well adjust to suit yours:
foreach(glob('../folder/*.php') as $file) {
$adjust = substr($file,3);
copy($file, '/home/user/abcde.com/'.$adjust);
Notice the use of "substr()", without it, the destination becomes '/home/user/abcde.com/../folder/', which might be something you don't want. So, I used substr() to eliminate the first 3 characters(../) in order to get the desired destination which is '/home/user/abcde.com/folder/'. So, you can adjust the substr() function and also the glob() function until it fits your personal needs. Hope this helps.
Long-winded, commented example with return logging, based on parts of most of the answers here:
It is presented as a static class method, but could work as a simple function also:
/**
* Recursive copy directories and content
*
* #link https://stackoverflow.com/a/2050909/591486
* #since 4.7.2
*/
public static function copy_recursive( $source = null, $destination = null, &$log = [] ) {
// is directory ##
if ( is_dir( $source ) ) {
$log[] = 'is_dir: '.$source;
// log results of mkdir call ##
$log[] = '#mkdir( "'.$destination.'" ): '.#mkdir( $destination );
// get source directory contents ##
$source_directory = dir( $source );
// loop over items in source directory ##
while ( FALSE !== ( $entry = $source_directory->read() ) ) {
// skip hidden ##
if ( $entry == '.' || $entry == '..' ) {
$log[] = 'skip hidden entry: '.$entry;
continue;
}
// get full source "entry" path ##
$source_entry = $source . '/' . $entry;
// recurse for directories ##
if ( is_dir( $source_entry ) ) {
$log[] = 'is_dir: '.$source_entry;
// return to self, with new arguments ##
self::copy_recursive( $source_entry, $destination.'/'.$entry, $log );
// break out of loop, to stop processing ##
continue;
}
$log[] = 'copy: "'.$source_entry.'" --> "'.$destination.'/'.$entry.'"';
// copy single files ##
copy( $source_entry, $destination.'/'.$entry );
}
// close connection ##
$source_directory->close();
} else {
$log[] = 'copy: "'.$source.'" --> "'.$destination.'"';
// plain copy, as $destination is a file ##
copy( $source, $destination );
}
// clean up log ##
$log = array_unique( $log );
// kick back log for debugging ##
return $log;
}
Call like:
// call method ##
$log = \namespace\to\method::copy_recursive( $source, $destination );
// write log to error file - you can also just dump it on the screen ##
error_log( var_export( $log, true ) );
I find this to be way simpler, more easily customizable, and to not require any dependency:
foreach(glob("old_location/*") as $file) {
copy($file, "new_location/" . basename($file));
}
// using exec
function rCopy($directory, $destination)
{
$command = sprintf('cp -r %s/* %s', $directory, $destination);
exec($command);
}
For copy entire contents from a directory to another, first you should sure about transfer files that they were transfer correctly. for this reason, we use copy files one by one! in correct directories. we copy a file and check it if true go to next file and continue...
1- I check the safe process of transferring each file with this function:
function checksum($src,$dest)
{
if(file_exists($src) and file_exists($dest)){
return md5_file($src) == md5_file($dest) ? true : false;
}else{
return false;
}
}
2- Now i copy files one by one from src into dest, check it and then continue. (For separate the folders that i don't want to copy them, use exclude array)
$src = __DIR__ . '/src';
$dest = __DIR__ . '/dest';
$exclude = ['.', '..'];
function copyDir($src, $dest, $exclude)
{
!is_dir($dest) ? mkdir($dest) : '';
foreach (scandir($src) as $item) {
$srcPath = $src . '/' . $item;
$destPath = $dest . '/' . $item;
if (!in_array($item, $exclude)) {
if (is_dir($srcPath)) {
copyDir($srcPath, $destPath, $exclude);
} else {
copy($srcPath, $destPath);
if (checksum($srcPath, $destPath)) {
echo 'Success transfer for:' . $srcPath . '<br>';
}else{
echo 'Failed transfer for:' . $srcPath . '<br>';
}
}
}
}
}

Copy all files and folder from one directory to another directory PHP

I have directory called "mysourcedir" it has sonme files and folders. so i want to copy all content from this directory to some other "destinationfolder" on Linux server using PHP.
function full_copy( $source, $target ) {
if ( is_dir( $source ) ) {
#mkdir( $target );
$d = dir( $source );
while ( FALSE !== ( $entry = $d->read() ) ) {
if ( $entry == '.' || $entry == '..' ) {
continue;
}
$Entry = $source . '/' . $entry;
if ( is_dir( $Entry ) ) {
$this->full_copy( $Entry, $target . '/' . $entry );
continue;
}
copy( $Entry, $target . '/' . $entry );
}
$d->close();
}else {
copy( $source, $target );
}
}
I am trying this code, but it does some problem, it creates directory "mysourcedir" at destination location. I am expecting to just copy all files and folders at destination,. Please suggest
Hello there little php developers this not a question but an answer to a question on how to copy files from one folder to another. I have come across over the internet that some developers use rename()instead of copy() to move files from one directory to another.
Here is simple working code. Tested and work like charm.
<===========================The Magic============================>
<?php
$dir = "path/to/targetFiles/";
$dirNew="path/to/newFilesFolder/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
//exclude unwanted
if ($file==".") continue;
if ($file=="..")continue;
//if ($file=="index.php") continue; for example if you have index.php in the folder
if (copy("$dir/$file","$dirNew/$file"))
{
echo "Files Copyed Successfully";
//echo "<img src=$dirNew/$file />";
//if files you are moving are images you can print it from
//new folder to be sure they are there
}
else {echo "File Not Copy";}
}
closedir($dh);
}
}
?>
class FolderCopy {
public static function copyFolder($src, $dest) {
$path = realpath($src);
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
/** SplFileInfo $object*/
foreach($objects as $name => $object)
{
$startsAt = substr(dirname($name), strlen($src));
self::mkDir($dest.$startsAt);
if(is_writable($dest.$startsAt) and $object->isFile())
{
copy((string)$name, $dest.$startsAt.DIRECTORY_SEPARATOR.basename($name));
}
}
}
private static function mkDir($folder, $perm=0777) {
if(!is_dir($folder)) {
mkdir($folder, $perm);
}
}
}
FolderCopy::copyFolder(dirname(dirname(FILE))."/images", dirname(FILE)."/test");
This is my suggestion.
<?php
/**
* Copy a file, or recursively copy a folder and its contents
*
* #author Aidan Lister <aidan#php.net>
* #version 1.0.1
* #param string $source Source path
* #param string $dest Destination path
* #return bool Returns TRUE on success, FALSE on failure
*/
function copyr($source, $dest)
{
// Simple copy for a file
if (is_file($source)) {
chmod($dest, 777);
return copy($source, $dest);
}
// Make destination directory
if (!is_dir($dest)) {
mkdir($dest);
}
chmod($dest, 777);
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Deep copy directories
if ($dest !== "$source/$entry") {
copyr("$source/$entry", "$dest/$entry");
}
}
// Clean up
$dir->close();
return true;
}
?>
You probably just want to move that line down, like this:
function full_copy( $source, $target ) {
if ( is_dir( $source ) ) {
$d = dir( $source );
while ( FALSE !== ( $entry = $d->read() ) ) {
if ( $entry == '.' || $entry == '..' ) {
continue;
}
$Entry = $source . '/' . $entry;
if ( is_dir( $Entry ) ) {
#mkdir( $Entry );
$this->full_copy( $Entry, $target . '/' . $entry );
continue;
}
copy( $Entry, $target . '/' . $entry );
}
$d->close();
}else {
copy( $source, $target );
}
Although personally I would avoid using 2 variables with the same name with only captilisation to differentiate them. Check the user comments on http://www.php.net/copy for other possibilities.
I think taht the $d->read() will return also the name of the parent and hat is why you are creating it again in the target directory.
try running cp -a. That takes care of preserving mod times and permissions, and all that. cp -al will make a hardlink farm.
for windows server:
shell_exec('xcopy \\old\\folder \\new\\folder /s /e /y /i');
for linux server:
shell_exec('cp -R /old/folder /new/folder');
I have tried all the examples but no one is copying sub folders and its data. Finally I got the answer:
<?php
$dir = "/var/www/html/json/";
$dirNew = "/var/www/html/json1/";
// Open a known directory, and proceed to read its contents
recurse_copy($dir, $dirNew);
function recurse_copy($src, $dst) {
$dir = opendir($src);
#mkdir($dst);
while (false !== ( $file = readdir($dir))) {
if (( $file != '.' ) && ( $file != '..' )) {
if (is_dir($src . '/' . $file)) {
recurse_copy($src . '/' . $file, $dst . '/' . $file);
} else {
copy($src . '/' . $file, $dst . '/' . $file);
}
}
}
closedir($dir);
}

Categories