Saturday, March 30, 2013

PHP, copy entire folder



In PHP, we use recursive method to copy the entire folder file. We create a class CopyFile and create
a constructor CopyFile($fromFile,$toFile)
Code:
<?php
    class CopyFile{
        public $fromFile;
        public $toFile;
        function CopyFile($fromFile,$toFile){

           if(is_file($fromFile)){
                copy($fromFile,$toFile);
                return;
            }
            $this->CreateFolder($toFile);
            $folder1=opendir($fromFile);
            while($f1=readdir($folder1)){
                if($f1!="." && $f1!=".."){
                    $path2="{$fromFile}/{$f1}";
                    if(is_file($path2)){
                        $file = $path2;
                        $newfile = "{$toFile}/{$f1}";
                        copy($file, $newfile);
                    }elseif(is_dir($path2)){
                        $toFiles = $toFile.'/'.$f1;
                        $this->copyFile($path2,$toFiles);
                    }
                }
            }
        }

        function CreateFolder($dir, $mode = 0777){
            if (is_dir($dir) || @mkdir($dir,$mode)){
                return true;
            }
            if (!$this->CreateFolder(dirname($dir),$mode)){
                return false;
            }
            return @mkdir($dir, $mode);
        }
    }
    ?>

To apply this class
 $file = new CopyFile('C:/test','C:/test1');

1 comment:

  1. What would I need to change to make this work on a windows system?

    ReplyDelete