使用PHP遍历子目录


Iterating through sub-directories with PHP

初级PHP编码器。我写了这段代码来遍历目录并捕获一些数据,然后使用这些数据更新数据库。

<?php
$servername = "localhost";
$username = "popcorn";
$password = "**********";
$dbname = "professional_test123";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$path = "/home/professional/www/dan/myFiles";
if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
        if ('.' === $file) continue;
        if ('..' === $file) continue;
$title = pathinfo($file,PATHINFO_BASENAME);
$size = filesize($file);
$myFile[$title]['size'] = filesize($file);
$sql = "UPDATE Files SET Size = '$size' WHERE Name = '$title'";
if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
}
closedir($handle);
$conn->close();

我现在想做的是在根目录中迭代许多子目录,并从所有子目录中收集相同的数据。我读到我可以将RecursiveDirectoryTerator与RecursiveIteratorIterator结合使用来实现这一点,但我不知道如何将其合并到我的代码中。非常感谢你的帮助。

这里有一个开始-一个递归函数,如果遇到文件夹,它会调用自己,如果遇到文件,它会运行数据库查询$myFile是通过引用传入的,因此函数可以动态地向其中添加新项,而无需从函数中返回值。

$myFile = array();
$path = "/home/professional/www/dan/myFiles";
updateSize($path, $myFile);
function updateSize($path, &$myFile){
    if ($handle = opendir($path)) {
        while (false !== ($file = readdir($handle))) {
            if ('.' === $file) continue;
            if ('..' === $file) continue;
            $full_path = $path.'/'.$file;
            if(is_dir($full_path)){
                //function calls itself
                updateSize($full_path, $myFile); 
            } else {
                $title = pathinfo($file, PATHINFO_BASENAME);                
                $size = filesize($full_path);
                $myFile[$title]['size'] = $size;
                $sql = "UPDATE Files SET Size = '$size' WHERE Name = '$title'";
                if ($conn->query($sql) === TRUE) {
                    echo "Record updated successfully";
                } else {
                    echo "Error: " . $sql . "<br>" . $conn->error;
                }
            }
        }//while
    closedir($handle);
    }//if
}