开发者

Moving files into directory in foreach loop?

i've no idea how to do that and need your help!

i have an array of filenames called $bundle. (file_one.jpg, file_two.pdf, file_three.etc) and i have the name of the folder stored in $folder. (my_directory)

i now would like to move all the files stored in $bundle to move to the directory $folder.

how can i do that?

    //print count($bundle); //(file_one.jpg, file_two.pdf, file_three.jpg)
    $folder = $folder = PATH . '/' . my_directory;
 foreach ($bundle as $value) {

  //rename(PATH.'/'.$value, $folder . '/' . $value);

 }

just so it's not confusing: PATH just stores the local file-path im using for my project. in my case it's just the folder i'm working in-so it's "files".

i have no idea which method i have to use for this and 开发者_JAVA技巧how i could solve that!

thank you for your help!


The code given by you should work with minor changes:

$folder = PATH . '/' . 'my_directory'; // enclose my_directory in quotes.
foreach ($bundle as $value) {
        $old = PATH.'/'.$value, $folder;
        $new = $folder . '/' . $value;
        if(rename($old,$new) !== false) {
                // renamed $old to $new
        }else{
                // rename failed.
        }
}


$folder = PATH . '/' . $folder;
foreach ($bundle as $value) {
        $old = PATH.'/'.$value;
        $new = $folder . '/' . $value;
        if(rename($old,$new) !== false) {
                // renamed $old to $new
        }else{
                // rename failed.
        }
}


Untested but should work:

function bulkMove($src, $dest) {
    foreach(new GlobIterator($src) as $fileObject) {
        if($fileObject->isFile()) {
            rename(
                $fileObject->getPathname(),
                rtrim($dest, '\\/') . DIRECTORY_SEPARATOR . $fileObject->getBasename()
            );
        }
    }
}
bulkMove('/path/to/folder/*', '/path/to/new/folder');

Could add some checks to see if the destination folder is writable. If you dont need wildcard matching, change the GlobIterator to DirectoryIterator. That would also eliminate the need for PHP5.3

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜