Jump to content
Larry Ullman's Book Forums

Listing Directories: Using Opendir() - Question


Recommended Posts

hi everyone,

 

In the last 4 weeks I've spent A LOT of time with Larry's book and Lynda.com videos (pertaining to PHP). I want to thank Larry for making such a clear and linear guide for PHP beginners.

 

But anyways, I'm working on a small script and I want to list the contents of a directory, make them into hyperlinks, and then edit those hyperlinks to look pretty (I.e. not show an ugly super long path name), then limit the number files echoed back to the browser.

 

 

I was thinking about using this:

 

<?php
$path = "/full/path/to/files";
if ($handle = opendir($path)) {
  while (false !== ($file = readdir($handle)))
     {
         if ($file != "." && $file != "..")
     {
             $files .= '<a href="'.$file.'">'.$file.'</a>';
         }
      }
 closedir($handle);
 }
?>

 

or this:

 

 

<?php
$sub = ($_GET['dir']);
$path = 'enter/your/directory/here/';
$path = $path . "$sub";
$dh = opendir($path);
$i=1;
while (($file = readdir($dh)) !== false) {
   if($file != "." && $file != "..") {
           if (substr($file, -4, -3) =="."){
           echo "$i. $file <br />";
           }else{            
       echo "$i. <a href='?dir=$sub/$file'>$file</a><br />";
         }
       $i++;
   }
}
closedir($dh);
?>

 

But I dont want to list the files like this:

 

C:/example/example2/Hello.pdf

 

I want to edit the variable. Is that possible? To make it say something as simple as "Hello."

 

I want to limit the amount of files listed as well. For example: only list the first 5 files, or last 5, etc. Is there a function or some kind of parameter for that?

 

I appreciate any help or push in the right direction. Thanks :)

Link to comment
Share on other sites

First issue is very easy. Add something like this to your while loop: (This will work)

 

$max = 5; // Max number to output
$count = 0; // The actuall count
while ( ($file = readdir($dh)) !== false && ($count++ < $max) ) {}

 

I'm not a devil on string splitting, but I'm guessing you could use substring, explode the string into parts, use ucwords and a lot of other functions to format it.

 

Please note $count is increased during the loop. If you want it to start $count on 1, use <= as comparison instead.

  • Upvote 2
Link to comment
Share on other sites

Antonio is right on the mark as usual.

Anyway, a simple regex would probably be the simplest solution, although you could also use the explode function, etc.

The main thing to watch out for is that file names (the strings stored in the $file variable) can contain more than one period.

As such, you have to be careful to only split on the last period in the string (whether there's more than one period or not).

The following regex will accomplish this:

 

<?php

 $dir = 'files/';

 $handle = opendir($dir);

 while (($file = readdir($handle)) !== false) {

   if (($file !== '.') && ($file !== '..')) {

     $pattern = '/(.*)\..*/';

     preg_match($pattern, $file, $match);

     echo $match[1] . '<br>';

   }

 }

 closedir($handle);

 

Hope that gets you what you want.

Thanks.

  • Upvote 1
Link to comment
Share on other sites

if (($file !== '.') && ($file !== '..')) {

 

This line is really bad, and won't work. You are basically checking if the filename is dot or double dot. I don't really understand why you'd ever need that. If you want to make sure your files has an extension, is hidden (.name-files) etc, you need another check. A very simple one for hidden files.

 

$max = 5; // Max number to output
$count = 0; // The actuall count
while (($file = readdir($handle)) !== false && ($count++ < $max) ) {

   if ($file[0] === ".") { $count--; continue; } /* If first char is "." (hidden file), continue loop */

Link to comment
Share on other sites

Haha. Ok. Guess PHP is really retarded sometimes. Good example on why I'm starting to hate PHP.

 

My new readir function:

/**
* Read entry from directory handle
*
* @param resource $handle        The directory handle resource previously opened with opendir().
* @return unsure		    Returns the entry name on success or FALSE on failure.
*                    (But if something weird happens, which we don't really know what is,
*                    you may expect "." or ".." as return values too.
*                    We don't really know why. DON'T ASK!!!)
* @see          	        http://stinky-code.com
*/

function readir( $handle )
{
   return iHaveNoIdeaWhatIamDoing("dog.jpg");
}

Link to comment
Share on other sites

My assumption is that this behavior comes from Unix and isn't to be blamed on PHP. Also, not to be blamed on anything. Also, Thomas, just so you know, "retarded" is considered to be more and more of an inappropriate word in the English language.

 

What I recommend is just checking for an initial period in the file's name. This would catch the current directory (.), the parent directory (..), and any hidden files (.htaccess).

  • Upvote 1
Link to comment
Share on other sites

Yeah, I should have stated in my previous post that the periods were most likely UNIX-legacy things, but I was in a hurry and couldn't be "arsed" to do it (as my Ozzie co-worker always says).

Anyway, the real question is: michaela, did we answer your questions with explanations that are understandable?

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...