将所有文件和文件夹从一个目录复制到另一个目录PHP [英] Copy all files and folder from one directory to another directory PHP

查看:570
本文介绍了将所有文件和文件夹从一个目录复制到另一个目录PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为"mysourcedir"的目录,它具有音素文件和文件夹.所以我想使用PHP将这个目录中的所有内容复制到Linux服务器上的其他目标文件夹"中.

I have directory called "mysourcedir" it has sonme files and folders. so i want to copy all content from this directory to some other "destinationfolder" on Linux server using PHP.

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 );
}
}

我正在尝试此代码,但确实存在一些问题,它在目标位置创建目录"mysourcedir".我希望仅将所有文件和文件夹复制到目标位置.请建议

I am trying this code, but it does some problem, it creates directory "mysourcedir" at destination location. I am expecting to just copy all files and folders at destination,. Please suggest

推荐答案

您好,几乎没有PHP开发人员,这不是一个问题,而是一个有关如何将文件从一个文件夹复制到另一个文件夹的问题的答案.我在互联网上遇到过一些开发人员使用rename()而不是copy()将文件从一个目录移动到另一个目录的情况. 这是简单的工作代码.经过测试,像魅力一样工作.

Hello there little php developers this not a question but an answer to a question on how to copy files from one folder to another. I have come across over the internet that some developers use rename()instead of copy() to move files from one directory to another. Here is simple working code. Tested and work like charm.

< ==========================魔术师================ ============

<===========================The Magic============================>

<?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);
        }
    }


    ?>

这篇关于将所有文件和文件夹从一个目录复制到另一个目录PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆