A simple script to copy the filenames of a directory into a database table


Share Directories filenames to database ver. 1.00

released: 2006-07-28
This script is an example how to import all filenames of a single directory into a database table. Extra features are: the last modification date is saved in the database too; all filenames that are not imported to the database are stored in an error array. The script is very easy to use: just place the script into the folder where you want to copy the files and modify the database connection string and then run the script via the browser. The script is working on windows/linux, PHP 4 and MySQL 3.23 (or higher)

Viewed 8792 times

Rating: script rated with stars
 

<?php
// a sinple function to create a database connection
function db_connect() {
    $conn = mysql_connect("localhost", "user", "pass");
    mysql_select_db("dbname", $conn);
}
// this function will open the chosen directory and returns and array with all filenames
function select_files($dir) {
    if (is_dir($dir)) {
        if ($handle = opendir($dir)) {
            $files = array();
            while (false !== ($file = readdir($handle))) {
                if (is_file($dir.$file) && $file != basename($_SERVER['PHP_SELF'])) $files[] = $file;
            }
            closedir($handle);
            if (is_array($files)) sort($files);
            return $files;
        }
    }
}
// this function inserts the filename and the modification date of the current file
function insert_record($name, $mod_date) {
    $sql = sprintf("INSERT INTO example SET filename = '%s', lastdate = '%s'", $name, $mod_date);
    if (mysql_query($sql)) {
        return true;
    } else {
        return false;
    }
}
// establish database connection
db_connect();
// enter the table structure if not exists
mysql_query("
CREATE TABLE IF NOT EXISTS example (
  id bigint(20) unsigned NOT NULL auto_increment,
  filename varchar(255) NOT NULL default '',
  lastdate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (id),
  FULLTEXT KEY domain (filename)
) TYPE=MyISAM;"
);

// creating the current path
$path = dirname(__FILE__);
// the trailing slash for windows or linux
$path .= (substr($path, 0, 1) == "/") ? "/" : "\\";
// get the filenames from the directory
$file_array = select_files($path);
// creating some controle variables and arrays
$num_files = count($file_array);
$success = 0;
$error_array = array();
// if the file array is not empty the loop will start
if ($num_files > 0) {
    foreach ($file_array as $val) {
        $fdate = date("Y-m-d", filectime($path.$val));
        if (insert_record($val, $fdate)) {
            $success++;
        } else {
            $error_array[] = $val;
        }   
    }
    echo "Copied ".$success." van ".$num_files." files...";
    if (count($error_array) > 0) echo "\n\n<blockquote>\n".print_r($error_array)."\n</blockquote>";
} else {
    echo "No files or error while opening directory";
}
?>