简体   繁体   中英

copy a file into all sub directories php

I have a text file that I want to copy into all sub directories which have the following structure.

S000314/0000356/data folder  
/0000357/data folder  
/0000358/data folder 

So, I am reading all the sub directories and trying to copy the text file into all of them..But, rename function can copy only once.its copying the text file into 0000356->data folder

if ($handle = opendir('S000314')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..")
        {
            rename("sdata.txt" , "/S000314/$entry/data/sdata.txt");
        }       
    }
    closedir($handle); 
}   

I have no clue on how to copy the same file into all of the sub directories.Please take a look at the code below.

I'd recommend using copy() instead of rename() because that is the actual operation you want (the code will be easier to read).

A problem could be the directory separator - I tested it on Windows where both / and \\ seems to be working, but that shouldn't be your concern, as PHP has DIRECTORY_SEPARATOR .

Now this code worked on my machine:

$topdir = 'S000314';
if ($handle = opendir($topdir)) {
    print "in\n";
    while (FALSE !== ($subdir = readdir($handle))) {
        if ($subdir != '.' && $subdir != '..') {
            $dest = $topdir . DIRECTORY_SEPARATOR . 
                $subdir . DIRECTORY_SEPARATOR 
                'data' . DIRECTORY_SEPARATOR;
            copy('data.txt', $dest.'data.txt');
        }
    }
}
@copy($yourSource_file, $yourFile_element . '/youPage.html');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM