Howdy_McGee
Howdy_McGee

Reputation: 10673

PHP Reading Directories

So I'm going through reading and writing to files in PHP via PHP Docs and there's an example I didn't quite understand:

http://php.net/manual/en/function.readdir.php

if toward the end it shows an example like this:

<?php
if ($handle = opendir('.')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "$entry\n";
        }
    }
    closedir($handle);
}
?>

In what case would . or .. ever be read?

Upvotes: 0

Views: 312

Answers (4)

Steel Brain
Steel Brain

Reputation: 4461

If you want to read directories using PHP, I would recommend you use the scandir function. Below is a demonstration of scandir

$path = __DIR__.'/images';
$contents = scandir($path);
foreach($contents as $current){
  if($current === '.' || $current === '..') continue ;
  if(is_dir("$path/$current")){
    echo 'I am a directory';
  } elseif($path[0] == '.'){
    echo "I am a file with a name starting with dot";
  } else {
    echo 'I am a file';
  }
}

Upvotes: 1

Mr Griever
Mr Griever

Reputation: 4023

In *nix . is the present working directory and .. is the directory parent. However any file or directory preceded by a '.' is considered hidden so I prefer something like the following:

...
if ($entry[0] !== '.') {
    echo "$entry\n";
}
...

This ensures that you don't parse "up" the directory tree, that you don't endlessly loop the present directory, and that any hidden files/folders are ignored.

Upvotes: 0

Tom Hallam
Tom Hallam

Reputation: 1950

Because in a UNIX filesystem, . and .. are like signposts, as far as I know. Certainly to this PHP function, anyway.

Keep them in there, you'll get some weird results (like endless loops, etc.) otherwise!

Upvotes: 0

g13n
g13n

Reputation: 3246

The readdir API call iterates over all of the directories. So assuming you loop over the current directory (denoted by ".") then you get into an endless loop. Also, iterating over the parent directory (denoted by "..") is avoided to restrict the list to the current directory and beneath.

Hope that helps.

Upvotes: 3

Related Questions