Hey everyone. I'm trying to write a script that will simply add all files in a directory called 'files' to a database, and also search each subfolder in the directory 'files' and add each file in each subfolder. I came up with the folowing script, and it doesn't work when it gets into the subfolders. It adds all the files in the root directory, but fails to add anything else.

Basically, all I'm doing is using scandir() to get an array of all the things in the current working directory. Then I go through each item in the array with a foreach, and if it's a directory, it recursively calls addFiles() with a new starting directory.

Here's what my code looks like....

To change this template, choose Tools | Templates
and open the template in the editor.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        include 'DBConnect.php';

        $db = new DBConnect() or die("Can't connect to DB");
        $conn = $db->getConn();
        mysql_select_db('download', $conn) or die("Can't select DB");
        $dir = getcwd();
        $dir = $dir . '\files' . "\\";
        $fid = 1;
        $files = scandir($dir);

        $dir = addslashes($dir);
//        foreach ($files as $a) {
        //          echo "<li> echo $a </li>";
        //    }

        echo $fid;
        echo $dir;

        function addFiles($aDir, $files, $fid, $conn) {
            foreach ($files as $aFile) {
                if (is_file($aDir.$aFile)) {
                    echo "<li> $aFile </li>";
                    $query = "INSERT INTO files (file_id, file_path, file_name) values ($fid, '$aDir', '$aFile')";
                    mysql_query($query, $conn) or die("Something wrong with query");
                    $fid = $fid + 1;
                } else if (is_dir($aDir.$aFile)) {
                    $new = scandir($aDir.$aFile);
                    echo $aDir.$aFile;
                    $fid = $fid + 1;
                    addFiles($aDir.$aFile."\\", $new, $fid, $conn);

        addFiles($dir, $files, $fid, $conn);

Thanks in advance for any ideas! Also, if there's a simpler way to do this, that's cool too. I just came up with this, as I'm sorta new to php