PHP has some great functions to handle files withing a specified directory. The following custom functions and code examples show how to use them is real cases.
Write filenames from a directory to MySQL
This script is an example how to import all filenames from a single directory into a MySQL database table. Extra features are:
- The last modification date is stored 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.
Establish a database connection
$db = new mysqli('localhost', 'username', 'password', 'databasename');
This function will open a selected 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; } } }
Next insert 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 ($db->query($sql)) { return true; } else { return false; } }
Create the table structure if not exists
$db->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;");
Create the current file path
$path = dirname(__FILE__);
Check for the trailing slash (Windows or Linux type)
$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"; }
Order and remove files from a directory
Use this function to take care of the amount of files in a public map. Every time a new file is uploaded the oldest one must be removed (using the unlink() function) if a maximum limit is already reached. The second parameter is optional and will set the limit whenever the check should happen or not.
Demo: My PHP upload and download demo is using this function too.
<?php function get_oldest_file($directory) { if ($handle = opendir($directory)) { while (false !== ($file = readdir($handle))) { if (is_file($directory.$file)) { // add only files to the array (ver. 1.01) $files[] = $file; } } if (count($files) <= 12) { return; } else { foreach ($files as $val) { if (is_file($directory.$val)) { $file_date[$val] = filemtime($directory.$val); } } } } closedir($handle); asort($file_date, SORT_NUMERIC); reset($file_date); $oldest = key($file_date); return $oldest; }
How to use this PHP directory and file function?
This example will show you the oldest file if there are more then 8 in the directory.
echo get_oldest_file("/path/to/your/directory/", 8);