Page 1 of 1

Listing files in current directory

Posted: Fri Apr 02, 2004 10:18 pm
by partiallynothing
I wrote a function to list every file in the current directory.

Here is the code:

Code: Select all

<?php

function ListDirContents($align)
{
   $dir_full = shell_exec("ls");
   $dir_files = explode("\n", $dir_full);
   for ($i=0; $i<count($dir_files); $i++) {
      $count = $i+1;
      ?>
      <div align="<?php echo $align; ?>">
      <p><?php echo $count; ?>. <a href="http://studentcenter.compbrain.net/~pn/<?php echo $dir_files[$i]; ?>"><?php echo $dir_files[$i]; ?></a></p>
      </div>
      <?php
   }
}
?>
In the directory it is in, there are two files, this one (functions.php) and index.php. When the above function is called, it lists those two files, but then lists a blank third one, so the output looks similar to this:

Code: Select all

1. functions.php

2. index.php

3.
Can someone figure out why I am getting this third empty array entry in $dir_files. Thanks for any help!

Posted: Fri Apr 02, 2004 11:09 pm
by Illusionist
its because your exploding on '\n'... if you looked at $dir_full it'd look like:

Code: Select all

functions.php\nindex.php\n
and splitting on \n will produce 3 elements.
To avoid this just change

Code: Select all

for ($i=0; $i<count($dir_files); $i++) {
to

Code: Select all

for ($i=0; $i<count($dir_files)-1; $i++) {

Posted: Fri Apr 02, 2004 11:21 pm
by EvilWalrus
how bout just using http://php.net/glob?

Posted: Fri Apr 02, 2004 11:46 pm
by partiallynothing
Thanks a lot Illusonist, that fixed everything!

EvilWalrus, did not know of that function, explode works similalary tho and what I have does the job. Thanks tho.