简体   繁体   English

在给定文件夹的所有子文件夹中递归创建一个php文件

[英]Recursively create a php file in all subfolder in a given folder

I want to create an empty index.php file in all subfolder of a given folder path i specify. 我想在我指定的给定文件夹路径的所有子文件夹中创建一个空的index.php文件。

That is, say given folder is /dir/content , with many sub folders, I want index.php to be added to all the sub folders. 也就是说,假设给定的文件夹是/dir/content ,并且有很多子文件夹,我希望将index.php添加到所有子文件夹中。 If one exist already, skip. 如果已经存在,请跳过。

A php function to achieve this is what I want. 我想要的是一个实现此功能的PHP函数。

use php copy function. 使用php复制功能。 here is the documentation, 这是文档,

php copy function php复制功能

here is an example, 这是一个例子

function recurse_copy($src,$dst) {  
    $dir = opendir($src); 
    while(false !== ( $file = readdir($dir)) ) { 
        if (( $file != '.' ) && ( $file != '..' )) { 
            if ( is_dir($src . '/' . $file) ) { 
                recurse_copy($src . '/' . $file,$dst . '/' . $file); 
            } 
            else { 
                copy($src . '/' . $file,$dst . '/' . $file); 
            } 
        } 
    } 
    closedir($dir); 
    //echo "$src"; 
} 
$src = "/home/user/public_html/dir/subdir/source_folder/";  
$dst = "/home/user/public_html/dir/subdir/destination_folder/";  
recurse_copy($src,$dst);

You must use the scandir function: 您必须使用scandir函数:

putFiles('/startDir');

function putFiles($path)
{
    fopen("$path/index.php", "w");

    $files = scandir($path);
    unset($files[0]); // remove .
    unset($files[1]); // remove ..

    foreach($files as $filePath)
    {
        if(is_dir("$path/$filePath"))
        {
            putFiles("$path/$filePath");
        }
    }
}

You can use RecursiveIteratorIterator and RecursiveDirectoryIterator . 您可以使用RecursiveIteratorIteratorRecursiveDirectoryIterator

The following code will create an empty index.php file in each directory, if one does not exist. 以下代码将在每个目录(如果不存在)中创建一个空的index.php文件。

<?php
$root = './';

$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
    $file = realpath($file);
    if (is_dir($file) === true) {
        if (!file_exists($file.'/index.php')) {
            echo 'CREATED: '.$file.'/index.php</br>'.PHP_EOL;
            file_put_contents('', $file.'/index.php');
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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