filtering folders and files

General discussions related to php

Moderators: macek, egami, gesf

jasonfarrell
New php-forum User
New php-forum User
Posts: 4
Joined: Thu Jul 10, 2003 11:34 am

filtering folders and files

Postby jasonfarrell » Thu Jul 10, 2003 11:35 am

what i want to do is display all the folders in my directory. what i'm doing is filtering out all files with periods in them (the period before the extention). for some reason, this isn't working; it's filtering out everything.

here's the code:

<?php
$dp = opendir(".");
while($file = readdir($dp)) $filenames[] = $file;
closedir($dp);
for($i=0;$i<count($filenames);$i++)
if($filenames[$i] != '.' && $filenames[$i] != '..')
if (ereg(".", $filenames[$i])) {}
else{echo '<A href="'.$filenames[$i].'">'.$filenames[$i].'</A></b><br>';}
?>

User avatar
swirlee
Moderator
Moderator
Posts: 2272
Joined: Sat Jul 05, 2003 1:18 pm
Location: A bunk in the back
Contact:

Postby swirlee » Thu Jul 10, 2003 12:53 pm

The function to tell if a file is a directory is is_dir(). Use it well. Also, when you're doing simple matching, ereg functions are massive overkill, and if you're just iterating through an array, use foreach(). Anyway, I made your code work and also cleaned it up a ton. I recommend you read some articles on conventions and code readability in PHP programming.

Code: Select all

<?php
   $dp = opendir(".");
   
   while($file = readdir($dp)) {
      $filenames[] = $file;
   }
   closedir($dp);
   
   foreach($filenames as $filename) {
      if(   is_dir($filename) &&
            $filename != '..' &&
            $filename != '.'
      ) {
         echo '<a href="' . $filename . '">' . $filename . "</a><br>\n";
      }
   }
?>


Return to “PHP General”

Who is online

Users browsing this forum: No registered users and 1 guest

cron