Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate folder with PHP

Tags:

php

I've been searching all morning for this.

Is there a simple PHP function that will duplicate a folder on my server, changing permissions temporarily along the way if needs be? Basically a PHP alternative to me using FTP to copy an entire folder down and then back up again?

I've tried the function below that I found online, but it does nothing I think probably due to permissions. I have tried it with error_reporting(E_ALL); and also checked the return value of each copy(), they all return false.

copy_directory('/directory1','/directory2') 

function copy_directory($src,$dst) { 
    $dir = opendir($src); 
    @mkdir($dst); 
    while(false !== ( $file = readdir($dir)) ) { 
        if (( $file != '.' ) && ( $file != '..' )) { 
            if ( is_dir($src . '/' . $file) ) { 
                copy_directory($src . '/' . $file,$dst . '/' . $file); 
            } 
            else { 
                copy($src . '/' . $file,$dst . '/' . $file); 
            } 
        } 
    } 
    closedir($dir); 
}  
like image 598
bbeckford Avatar asked Nov 15 '12 10:11

bbeckford


2 Answers

After posting the bounty I received a reply to a server support ticket that confirmed my belief that permissions were the problem.

A simple change on the server side to give PHP copy permission solved this issue.

like image 50
bbeckford Avatar answered Nov 18 '22 23:11

bbeckford


How about checking for the duplicate in your code someway along these lines?

<?php
if(!file_exists($dst)) {
    mkdir($dst);
}
else {
    $i = 1;
    $duplicate_folder = true;
    while ($duplicate_folder == true) {
        if(file_exist($dst) {
            $new_dst = $dst."_".$i;
            mkdir($new_dst);
            $i++;
        }
        else {
            $duplicate_folder = false;
        }
    }
}
?>
like image 45
art2 Avatar answered Nov 18 '22 21:11

art2