Forum Moderators: coopster
<?php
$dir = "page/to/images";
$good_ext = [url=http://us3.php.net/manual/en/function.array.php]array[/url](".jpg",".gif");
if ($handle = [url=http://us3.php.net/manual/en/function.opendir.php]opendir[/url]($dir)) {
while (false!== ($file = [url=http://us3.php.net/manual/en/function.readdir.php]readdir[/url]($handle))) {
$loc = [url=http://us2.php.net/manual/en/function.strrchr.php]strrchr[/url]($file,".");
$ext = [url=http://us2.php.net/substr]substr[/url]($file,$loc);
if([url=http://us3.php.net/in_array]in_array[/url]($ext,$good_ext)
{
//do something with file
echo "Good image file: ".$file."<br>";
}
else
{
echo "BAD IMAGE...BAD: ".$file."<br>";
}
}
closedir($handle);
}
else
{
echo "Directory does not exist!";
}
?>
**Note, this is the long way of checking for file extensions. You can just as easily use other methods, but you wouldn't learn as much would you ;) Here's a thread on other methods of doing so [webmasterworld.com]. Good luck (btw, this code was not tested)
BAD IMAGE...BAD: .
BAD IMAGE...BAD: ..
BAD IMAGE...BAD: index.php
BAD IMAGE...BAD: jus jumping.jpg
BAD IMAGE...BAD: jus leaning back.jpg
BAD IMAGE...BAD: jus pizza.jpg
BAD IMAGE...BAD: jus sears.jpg
BAD IMAGE...BAD: jus sepia.jpg
BAD IMAGE...BAD: jus_poster-edges.jpg
BAD IMAGE...BAD: error_log
Also, I don't really understand how this works:
if ($handle = opendir($dir)) {
while (false!== ($file = readdir($handle))) {
$loc = strrchr($file,".");
$ext = substr($file,$loc);
if(in_array($ext,$good_ext))
I mean, I understand that it gets the filename, seperates the extension from it, and checks to see if it's jpg or gif. But how does it actually *work*? Would you mind explaining? Thanks a lot :)
Btw, I'm the same person as above.
$dir = "Lana_Naoum/images";
$good_ext = array(".jpg",".gif");
if ($handle = opendir($dir)) {
while (false!== ($file = readdir($handle))) {
$ext = strrchr($file,".");
echo $ext."<br>";
if(in_array($ext,$good_ext))
{
//do something with file
echo "Good image file: ".$file."<br>";
}
else
{
echo "BAD IMAGE...BAD: ".$file."<br>";
}
}
closedir($handle);
}
else
{
echo "Directory does not exist!";
}
Basically the directory is opened and $handle is the resource for that directory. Then while $file does NOT equal (!==) false (readdir Returns the filename of the next file from the directory.) the script uses some string functions to find the extension. So if the extension is after the last period, then we can use strrchr to find the last occurrence of a character(the period) in a string(the file name) each time we find a file. Then we check to see if the extension is in the array of good extensions, if it is we do something, if not something else. Hope this explains it a little better.
Sorry for that error, I'll make sure my script is working next time ;)
Good luck!