Cool Engineering

Info on some cool engineering projects

Saturday, June 09, 2007

PHP is your friend

Recently for a website that I manage I wanted to make a section where details of the files within a folder are dynamically displayed, showing their size along with some formatted details garnered from the file name (date, speaker and topic).
For these sort of exercises PHP is really handy and my first preference - possibly as I grew up with C and the formatting is a little similar. It has some really neat file parsing options - like fill an array with all the filenames in a directory we go:

$dir = "./Sermons/Sermon_Audio/";
$dir_handle = opendir($dir);
$i = 0;
while (false !== ($file_name = readdir($dir_handle))){
if ($file_name != ".." and $file_name != ".") {
$dir_array[$i] = $file_name;
$i = $i + 1;
}
}

To sort them just do
rsort($dir_array);
or
sort($dir_array);
depending if you want to sort in reverse or not.

It has some great splitting functions to tokenise strings like to remove the file extension:
$removed_extension = explode(".", $dir_array[$i]);

And reading the filesize is dead easy (the 1024*1024 is to convert the size to MB - the function returns filesize in bytes)
$file_size = filesize($dir . $dir_array[$i])/(1024*1024);

0 Comments:

Post a Comment

<< Home