Page 1 of 1

generating an array which contains filenames of a dir

Posted: Thu Jun 01, 2006 2:39 am
by hanhao
generating an array which contains filenames of a dir


ok i have this dir called "images"
in it contain .jpg and .txt files

something like:
abc.txt
def.txt
qwe.jpg
kwe.jpg
now what i need to do is to enter .jpg only into my array such that the resultant array is

array_of_jpg_filenames[0] = qwe.jpg
array_of_jpg_filenames[1] = kwe.jpg

anyone knows how can i do that?
thanks

Posted: Thu Jun 01, 2006 3:11 am
by hanhao
thnx for help

this is the solution

Code: Select all

<?php
$dh = opendir($folder); 
if(!$dh) { 
	exit('Open dir function failed!'); 
} 
          
$file_array = array(); 
while (($file = readdir($dh)) !== false ){ 
	if ($file != "." && $file != ".."){
		$bits = explode(".", $file);
		if($bits[1] == "jpg"){
			$file_array[] = $file;
		}
  } 
}
print_r($file_array);
?>

Posted: Thu Jun 01, 2006 4:41 am
by onion2k
hanhao wrote:

Code: Select all

$bits = explode(".", $file);
		if($bits[1] == "jpg"){
That's a very unreliable way to check the file type unless you're in complete control of the files in the directory. It would assume that a file called image.jpg.exe is a jpg, and that a file called image.001.jpg isn't. If you're looking specifically for jpeg files, try checking getimagesize() for each file .. the 3rd parameter of the returned array tells you the type if the file is an image.

Posted: Thu Jun 01, 2006 6:36 am
by Oren

Posted: Thu Jun 01, 2006 8:51 am
by ok
Do this instead:

Code: Select all

$bits = explode(".", $file);
$ext = count($bits)-1;
if($bits[$ext] == "jpg"){ 
...

Posted: Thu Jun 01, 2006 10:21 am
by Oren
ok wrote:Do this instead:

Code: Select all

$bits = explode(".", $file);
$ext = count($bits)-1;
if($bits[$ext] == "jpg"){ 
...
I wouldn't count on this, see onion2k's post.

Posted: Sat Jun 03, 2006 1:35 pm
by ok
It's different... in my way you always get the ext, i.e: file called "myFile.jpg.exe.bmp". In my way you will get "bmp" as the file ext!!!

Posted: Sat Jun 03, 2006 2:36 pm
by nickvd
ok wrote:It's different... in my way you always get the ext, i.e: file called "myFile.jpg.exe.bmp". In my way you will get "bmp" as the file ext!!!
create a zip file... name it lmaohax.jpg ... you will still be able to unzip it. why? the programs read the file header to tell the type, not the ext.

Just because the file has .jpg .gif .... at the end of it, that doesn't mean it is an image.

Using onion's example of getimagesize() it will either return the type of image as the 3rd element of the return array, or false, if it is not an image.

Posted: Sat Jun 03, 2006 2:39 pm
by ok
OK :D