Copy all files and folders from one directory to another PHP
I have a directory called “mysourcedir” that contains sonme files and folders. So I want to use PHP to copy everything in this directory to some other “destination folder” on the Linux server.
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’m trying this code, but it does have some issues, it creates the directory “mysourcedir” in the target location. I want to copy only all files and folders in the destination location. Please suggest
Solution
Hello little php developer, this is not a question, but an answer to an answer about how to copy files from one folder to another. I’ve found some developers on the internet using rename() instead of copy() to move files from one directory to another.
This is simple working code. Tested and works like a charm.
<========================================================================================================>============================================
==================================================================================
<?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);
}
}
?>