Create a text file of a directory listing?

This has probably been covered, but an hour of searching hasn't helped me yet...

What I'd like to do is have a php script that would read the contents of a directory, and then write the result to "list.txt" in the same directory. However, I have two requirements of the text file:

(1) it must list only .jpg, .gif. or .png files.
(2) it must generate the list alphabtically. (I thought this would have been automatic, but oddly enough it doesn't seem to that way on my server.)

For example, when I call "the_script_i_require.php" it will hunt throgh this:

directory
|_some_directory_here
|                            |_apple.jpg
|_awesome.jpg
|_bathtub.gif
|_index.html
|_index.php
|_racer.png
|_the_script_i_require.php
|_toyboat.txt

...and leave "list.txt" containing only:

awesome.jpg
bathtub.gif
racer.png

Thanks in advance for any assistance.
TunaMaxxAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

EmielElgersmaCommented:
this will make the list
<?
$handle=opendir($thedir);
clearstatcache();
while ($filename = readdir($handle))
{
      if ($file != "." && $file != "..") {
      
            $ext=substr($filename,-4);
            

            if (($ext == ".gif" OR $ext == ".png" OR $ext == ".jpg") AND file_exists($link))
                                   echo $filename . '\n';
                         
      }

  }
?>
InsolenceCommented:
Eh, I'm too lazy to write the line or two that needs to be added to that script, but the author did ask for it to be written to list.txt in that directory.  =)

 - Insolence
show_sourceCommented:
Try this.

<?php

$dir_to_read = dirname($_SERVER['DOCUMENT_ROOT'] . $_SERVER['PHP_SELF']) ."/"; // read the dir where this file is, fullpath is used, instead of ./ in case of safe_mode or open_basedir restrictions

$filetypes = array("jpg", "gif", "jpeg", "png"); // extension of files

$path = opendir($dir_to_read);

$file_list = array();
while (false !== ($files = readdir($path))) {

if($files == "." || $files == ".." || is_dir($dir_to_read . $files)) {
continue;
}

      $ext = pathinfo($files); // used to check file-extension

      if(in_array(@strtolower($ext["extension"]), $filetypes)) { // used @ to avoid error-message, if file has no extension
      $file_list[] = $files;
      }

}
closedir($path);

if(count($file_list) > 0) {
sort($file_list);

$filenames = "";

foreach($file_list as $x) {
$filenames .= $x ."\n";
      }
$file_to_write = $dir_to_read ."list.txt";

$fp = fopen($file_to_write, "w+"); // w+ == create file if it doesn't exists. You may have to use chmod, if you are on a unix system
//chmod($file_to_write, 0777);
if ($fp) {
fputs($fp, $filenames);
fclose($fp);
      }

// Just display filenames to be written
echo $filenames;

}else{
echo"No files found";
}
?>

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Why Diversity in Tech Matters

Kesha Williams, certified professional and software developer, explores the imbalance of diversity in the world of technology -- especially when it comes to hiring women. She showcases ways she's making a difference through the Colors of STEM program.

TunaMaxxAuthor Commented:
EmielElgersma: I don't know what I was doing wrong, but I couldn't get your script to work. The best I could get was a half a second or so of page load, and then a blank page. Also, as  Insolence pointed out, there was no text file written anywhere.

show_source: Awesome! Works like a charm, and you even commented everything so I could follow along. The fact that you made the list of names also print out on screen was a bonus I hadn't even considered. However, now that it's there, is there a way to have each filename on a separate line? Right now the display is just a continuous list. I took a wild stab and added a beak to what I *thought* was the right place, but it doesn't seem to work:

I changed:
  // Just display filenames to be written
  echo $filenames;

To:
  // Just display filenames to be written
  echo $filenames . '<br>';

I'll award you the points even if you can't show me how to accomplish that, but I am interested in finding out why I couldn't make it work.

Thanks!
show_sourceCommented:
well, you just put a linebreak after $filenames, but to list the names, put the <br> in the foreach

foreach($file_list as $x) {
$filenames .= $x ."\n";
echo $x ."<br>\n";
     }
TunaMaxxAuthor Commented:
Thank you very much. Great job!
EmielElgersmaCommented:
Sorry I didn't work for you, I didn't have much time to test it.. but I toke it from an  old script of mine which made a gallery of all images that where in a spec. directory.

Good you got an alternative....
Emiel
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.