循环读取文件php,PHP读取子目录和循环文件如何?

本文介绍了一个使用PHP编写的脚本,该脚本能够批量复制文件夹内的所有子文件到新的目标文件夹,并对这些文件进行统一的重命名处理。通过调整源文件夹和目标文件夹的路径,可以灵活地应用于不同的文件整理场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ini_set('max_execution_time', 300);  // increase the execution time of the file (in     case the number of files or file size is more).

class renameNewFile {

static function copyToNewFolder() {  // copies the file from one location to another.

$main = 'C:\xampp\htdocs\practice\demo';  // Source folder (inside this folder subfolders and inside each subfolder files are present.)

$main1 = 'C:\xampp\htdocs\practice\demomainfolder'; // Destination Folder

$dirHandle = opendir($main); // Open the source folder

while ($file = readdir($dirHandle)) { // Read what's there inside the source folder

if (basename($file) != '.' && basename($file) != '..') {   // Ignore if the folder name is '.' or '..'

$folderhandle = opendir($main . '\' . $file);   // Open the Sub Folders inside the Main Folder

while ($text = readdir($folderhandle)) {

if (basename($text) != '.' && basename($text) != '..') {     //  Ignore if the folder name is '.' or '..'

$filepath = $main . '\' . $file . '\' . $text;

if (!copy($filepath, $main1 . '\' . $text))           // Copy the files present inside the subfolders to destination folder

echo"Copy failed";

else {

$fh = fopen($main1 . '\' . 'log.txt', 'a');     // Write a log file to show the details of files copied.

$text1 = str_replace(' ', '_', $text);

$data = $file . ',' . strtolower($text1) ."

";

fwrite($fh, $data);

echo $text ." is copied";

}

}

}

}

}

}

static function renameNewFileInFolder() {                //Renames the files into desired name

$main1 = 'C:\xampp\htdocs\practice\demomainfolder';

$dirHandle = opendir($main1);

while ($file = readdir($dirHandle)) {

if (basename($file) != '.' && basename($file) != '..') {

$filepath = $main1 . '\' . $file;

$text1 = strtolower($filepath);

rename($filepath, $text1);

$text2 = str_replace(' ', '_', $text1);

if (rename($filepath, $text2))

echo $filepath ." is renamed to" . $text2 . '
';

}

}

}

}

renameNewFile::copyToNewFolder();

renameNewFile::renameNewFileInFolder();

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值