Listing files in current directory

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
partiallynothing
Forum Commoner
Posts: 61
Joined: Fri Nov 21, 2003 5:02 pm
Location: connecticut, usa

Listing files in current directory

Post 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!
Illusionist
Forum Regular
Posts: 903
Joined: Mon Jan 12, 2004 9:32 pm

Post 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++) {
User avatar
EvilWalrus
Site Admin
Posts: 209
Joined: Thu Apr 18, 2002 3:21 pm
Location: Springmont, PA USA

Post by EvilWalrus »

how bout just using http://php.net/glob?
User avatar
partiallynothing
Forum Commoner
Posts: 61
Joined: Fri Nov 21, 2003 5:02 pm
Location: connecticut, usa

Post 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.
Post Reply