Forum Moderators: coopster
I'm trying to find out how to get PHP to create an array of a given directory's structure.
E.g
Structure Array =
1 - Blue Images
2 - Red Images
3 - Pink Images
4 - Brown Images
The above strucutre will be changing daily, so I need this to be dynamic. Any ideas how to do this? I don't really know what to search for!
Thanks in advance if anyone can help.
To read from a directory, try opendir(), readdir() & closedir(). That should get you started.
[uk.php.net...]
Example:
$open = opendir("files/");while ($read = readdir($open))
{
if ($read!= "." && $read!= "..")
{
echo $read . '<br>';
}
}
closedir($open);
Hope that gets you started.
dc
I don`t think its actually possible to get the file types from reading the file, although I could be wrong. Some of the more experienced guys will know. ;)
What you can do is get the file extension from the file and build data from there. To get the file extension use the strrchr() [uk.php.net] function. So, for example first build an array of file types:
$types = array(
'JPeg Image File',
'Gif Image File'
);
Then when you loop your code do something like:
$open = opendir("files/");
while ($read = readdir($open))
{
if ($read!= "." && $read!= "..")
{echo '(' . $read . ') File Type: ';
switch (strrchr(strtolower($read), '.'))
{
case ".jpg":
echo $types[0];
break;case ".gif":
echo $types[1];
break;
}
echo '<br>';}
}
closedir($open);
Something like that would work. Add as many types to the array and switch as you need. Just make sure they match. I`ve also used strtolower to eliminate any case issues. I`m sure there is something simpler, but its hot and sunny in the UK and thats all I can think of right now. LOL.
dc
If you want to find the MIME type of the file you can do a number of things, one of which you have already shown, read the extension. Another option is mime_content_type [php.net]. If memory serves me correctly, the Image functions also have a couple of MIME-type functions that prove useful.