Copy Entire Contents of a Directory to Another Using PHP

PHP: Copy entire contents of a directory

It's not tested but I think the issue might be that the target directory is not necessarily being created before attempting to copy files to it. The piece of code that creates the target directory would require a folder path rather than a full filepath - hence using dirname( $dst )

if( !defined('DS') ) define( 'DS', DIRECTORY_SEPARATOR );

function recurse_copy( $src, $dst ) {

$dir = opendir( $src );
@mkdir( dirname( $dst ) );

while( false !== ( $file = readdir( $dir ) ) ) {
if( $file != '.' && $file != '..' ) {
if( is_dir( $src . DS . $file ) ) {
recurse_copy( $src . DS . $file, $dst . DS . $file );
} else {
copy( $src . DS . $file, $dst . DS . $file );
}
}
}
closedir( $dir );
}

Copy all files from one folder to another Folder using PHP scripts?


// images folder creation using php
$mydir = dirname( __FILE__ )."/html/images";
if(!is_dir($mydir)){
mkdir("html/images");
}
// Move all images files
$files = glob("images/*.*");
foreach($files as $file){
$file_to_go = str_replace("images/","html/images/",$file);
copy($file, $file_to_go);
}

How to copy a file from one directory to another using PHP?

You could use the copy() function :

// Will copy foo/test.php to bar/test.php
// overwritting it if necessary
copy('foo/test.php', 'bar/test.php');



Quoting a couple of relevant sentences from its manual page :

Makes a copy of the file source to
dest.

If the destination
file already exists, it will be
overwritten.



Related Topics



Leave a reply



Submit