Hey all!
I'm writing a simple script to scan a local directory named 'files' and all sub directories of 'files', adding each file to a database in the same table. To do this, I'm using scandir on the current working directory/files to start, and iterating over each file in a loop, but if the file is a directory, I append the directory name to the cwd/files and call scandir on that, creating a list of files in the subfolder, and then I call my addFiles() function recursively, with this as the argument.
As of now, it just stops at the second call to addFiles. It adds all the top level files fine, stops there. That's where all my print_r() lines have gotten me.
Here's my code...
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php
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;
$dir = addslashes($dir);
$files = scandir($dir);
echo $fid . " ";
echo $dir;
function addFiles($files) {
global $dir;
global $conn;
global $fid;
unset($files[0]);
unset($files[1]);
print_r($files);
foreach ($files as $aFile) {
if (is_file($dir.$aFile)) {
echo "<li> $aFile </li>";
$query = "INSERT INTO files (file_id, file_path, file_name) values ($fid, '$dir', '$aFile')";
mysql_query($query, $conn) or die("Something wrong with query");
$fid = $fid + 1;
} else if (is_dir($dir.$aFile)) {
$fid = $fid + 1;
$aDir = $dir . $aFile . "\\";
echo $dir;
addFiles(scandir($dir.$aFile));
}
}
}
addFiles($files);
?>
</body>
</html>
Thanks in advance for any ideas. Also, if I'm approaching this problem completely wrong, let me know! I just came up with this and I feel like it should work...