Skip to content
</> Mücahit TopalA developer's notebook

Blog/PHP & MySQL

Copying an Entire Folder and Its File Contents with PHP

Mücahit Topal 2 min read 8,736 views TREN

Copying an Entire Folder and Its File Contents with PHP

There comes a time when, instead of copying files one by one, we need to copy a whole  folder together with everything inside it. Hoping it will be useful, I'm sharing with you the function whose explanations I wrote in between the lines of code.



function HerseyiKopyala($kaynak, $hedef) { 					// We pass two variables, kaynak (source) and hedef (destination), into the HerseyiKopyala function.
    if ( is_dir( $kaynak ) ) { 								// we verify that the location given as kaynak is a directory 
        if (!file_exists($hedef)) { @mkdir( $hedef ); }		// if the destination directory does not exist, we create it
        $Dizin = dir( $kaynak ); 							// we open the source directory
        while ( FALSE !== ( $giris = $Dizin->read() ) ) { 	// we loop through the directory and read its entries one by one
            if ( $giris == '.' || $giris == '..' ) {		// we check for the directory location entries
                continue;
            }
            $Giris = $kaynak . '/' . $giris; 				// we assign the resulting path to a variable
            if ( is_dir( $Giris ) ) {						// we verify that the location given as Giris is a directory
                HerseyiKopyala( $Giris, $hedef . '/' . $giris ); // we call the function again
                continue;
            }
            copy( $Giris, $hedef . '/' . $giris );			// we copy the files we read into the directory we checked
        }
        $Dizin->close();									// we finish reading the directory
    }else {
        copy( $kaynak, $hedef );							// if the given kaynak variable is not a directory, perform the copy
    }
}

That is how we created our function; to use it, simply follow the steps below;


$kaynak	="../css/style.css"; 		//copying a single file
$kaynak	="../css/"; 				//copying the whole folder
$hedef	="plugins/styles/";			//we specify the destination directory
 HerseyiKopyala($kaynak, $hedef); 	//we pass our variables to the function

Stay well...

,,,,

Share X Facebook LinkedIn WhatsApp

More from this category

Comments 3

Meraklı Kişi

Merhaba,ftp:// ile bir bağlantı açınca dosyaları okumuyor,ayrıca hem dosya hem klasörleri aynı anda okumuyor. Bunu nasıl düzeltebiliriz?

Merkalı Kişi

Merhaba, önceden attığım yorumdaki sorunlarımı çözdüm. Ancak kopyalama biraz yavaş. Bunu hızlandırabilmenin bir yolu var mı?

admin

@MeraklıKişi Kullanılan fonksiyon tüm dosya ve klasörleri tek tek kontrol ederek belirlenen durumuna göre işlem yapıyor yani ne kadar çok dosya ve klasör varsa o kadar uzun sürer döngü. 

Lakin pratik bir çözüm için shell komutu çalıştırabilirsiniz, örnek olarak :

$kaynak = "/home/www/example.com/*";
$hedef = "/home/www/website.com/";
shell_exec("cp -r $kaynak $hedef ");

 

Leave a comment

Comments appear after approval.