Jump to content

Getting all file names in a directory


Lamez

Recommended Posts

How can I get all the file names in a directory?

 

The reason is because I am using Java script to load images from a drop down box, but the you have to enter the image names, but I have tons and tons of images in my Helmet directory, so is there a for loop or something to find all the image names?

 

<form name="<?php echo $path; ?>/main/style/img/Helmets/"><p>
<select name="picture" size="1" onChange="showimage()">
<option value="img.gif">Picture 1</option>
<option value="img_2.gif">Picture 2</option>
<option value="img_3.gif">Picture 3</option>
</select>
</form>

Link to comment
Share on other sites

Hi, and thank you for the link I did not know that existed (not the manual).

 

But could you walk me trough this example code? I have commented some lines

 

<?php
$dir = "/etc/php5/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if ($dh = opendir($dir)) { //what is $dh?
        while (($file = readdir($dh)) !== false) {
            echo "filename: $file : filetype: " . filetype($dir . $file) . "\n"; //what is $file, filename? 
        }
        closedir($dh); 
    }
}
?>

Link to comment
Share on other sites

Your setting $dh to directory resource handle. It's in an if statement, because it can return false if it fails to open the directory.

 

For $file, if you look in the loop it's setting $file to the name of a file. So basically the loop is looping through all the files and after each loop sets $file to the new filename.

Link to comment
Share on other sites

I prefer glob, so here is one way.

 

<?php
$allowed = array("jpg", "jpeg", "gif", "png"); //allowed file extensions

$subDir = array();
$files = array();

foreach(glob("./dir/*") as $f){
if(filetype($f) == "dir"){
	foreach(glob($f."/*") as $s){
		if(filetype($s) == "file"){
			$ext = explode(".", basename($s));
			if(in_array($ext[count($ext)-1], $allowed)){
				$files[] = $s;
			}
		}
	}
}elseif(filetype($f) == "file"){
	$ext = explode(".", basename($f));
		if(in_array($ext[count($ext)-1], $allowed)){
			$files[] = $f;
		}
}
}

echo "<pre>";
print_r($files);
echo "</pre>";
?>

Link to comment
Share on other sites

When you echo them out, do it like this:

 

echo basename($files[0]);

 

Or, you can change the code to this:

 

<?php
$allowed = array("jpg", "jpeg", "gif", "png"); //allowed file extensions

$subDir = array();
$files = array();

foreach(glob("./dir/*") as $f){
if(filetype($f) == "dir"){
	foreach(glob($f."/*") as $s){
		if(filetype($s) == "file"){
			$ext = explode(".", basename($s));
			if(in_array($ext[count($ext)-1], $allowed)){
				$files[] = basename($s);
			}
		}
	}
}elseif(filetype($f) == "file"){
	$ext = explode(".", basename($f));
		if(in_array($ext[count($ext)-1], $allowed)){
			$files[] = basename($f);
		}
}
}

echo "<pre>";
print_r($files);
echo "</pre>";
?>

 

I wouldn't recommend the last option, because it's good to have the directory in case you need to link it. I'd just use basename() on the file you want.

 

Actually, here is a better version.

<?php
$allowed = array("jpg", "jpeg", "gif", "png"); //allowed file extensions

$subDir = array();
$files = array();

foreach(glob("./dir/*") as $f){
if(filetype($f) == "dir"){
	foreach(glob($f."/*") as $s){
		if(filetype($s) == "file"){
			$ext = explode(".", basename($s));
			if(in_array($ext[count($ext)-1], $allowed)){
				$files[] = array($s, basename($s, ".".$ext[count($ext)-1]));
			}
		}
	}
}elseif(filetype($f) == "file"){
	$ext = explode(".", basename($f));
		if(in_array($ext[count($ext)-1], $allowed)){
			$files[] = array($f, basename($f, ".".$ext[count($ext)-1]));
		}
}
}

echo "<pre>";
print_r($files);
echo "</pre>";
?>

Link to comment
Share on other sites

I am a bit confused by your code.

 

could I do something like this:

 

<?php
function getExt($str) {

       $i = strrpos($str,".");
       if (!$i) { return ""; }

       $l = strlen($str) - $i;
       $ext = substr($str,$i+1,$l);

       return $ext;

}
$dir = $path."main/style/img/Helmets";

if (is_dir($dir)) {
   if ($dh = opendir($dir)) {
       while (($file = readdir($dh)) !== false) {
        if($file !== (".")){
           if($file !== ("..")){
             if($file !== ("index.html")){
                echo'<option value="'.$file.'">'.$n_file.'</option>';
                 }//close index
             }//close .
          }//close .
       }//close while loop
       closedir($dh);
   }//close open dir $dh
}//close is dir
?>

 

but then all I get listed is dir, could I add this

 

<?php
if(is_dir($file){
echo "is dir?";
}else{
echo "is file?";
?>

Link to comment
Share on other sites

Lamez... Google is your friend; so is php.net. Don't simply keep firing off questions, it get's annoying. If you're going to ask a question make sure you have the willingness to lookup side questions that you have. Otherwise it just get's tedious for anyone to help anyone - cause they have to keep re-explaining the basics over and over.

 

[0] => ../../main/style/img/Helmets/Atlantic Coast Conference/Boston College.jpeg

 

That's 90% of what you're trying to do. So now would be a great opportunity for you to use google and lookup how to strip filenames, or even to make dynamic PHP links.

Link to comment
Share on other sites

that is not the problem, I am here to learn, and I can strip the file names, but I want to make the code my own, so I know exactly how it works.

 

I just figured it would be easier to do a nested loop. And I am asking if my code would be correct.

Link to comment
Share on other sites

I just figured it would be easier to do a nested loop. And I am asking if my code would be correct.

 

Ahh, sorry. :) Misunderstanding on my part. :)

 

Nested loop... No, but the overall code would indeed be correct in the sense that it would work. There really is no such thing as "correct" in programming. If you can get it to work, it works; nothing else really matters. :)

Link to comment
Share on other sites

If you can get it to work, it works; nothing else really matters.

 

Err...Efficiency not in your dictionary then? :P Not to mention how easy something is to maintain etc...

 

To answer your question Lamez, a nested loop will only work if you have a known level of subdirectories. For example, projectfear's code (which does indeed use a nested loop) is only able to retrieve files from directories one level deep. For this to work with a more complex structure, you'll need a recursive function.

Link to comment
Share on other sites

Okay, not very good with recursive functions but you can try this.. It works for unlimited amounts of sub-directories, I hope.

 

<?php

$subDir = array();
$files = array();

function getFiles($dir){
$allowed = array("jpg", "jpeg", "gif", "png"); //allowed file extensions

if(substr($dir, -1, 1) != "/"){
	$dir .= "/";
}
foreach(glob($dir."*") as $f){
	if(filetype($f) == "dir"){
		$files[] = getFiles($f);
	}elseif(filetype($f) == "file"){
		$ext = explode(".", basename($f));
			if(in_array($ext[count($ext)-1], $allowed)){
				$files[] = array($f, basename($f, ".".$ext[count($ext)-1]));
			}
	}
}

return $files;
}

$files = getFiles("./dir/");
echo "<pre>";
print_r($files);
echo "</pre>";

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.