0

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?

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

oh ok, so by saying readdir('.') it's going to read everything - even itself? So I wouldn't run into either case if I declared a directory such as readdir('test_directory')
Please see @tomhallam's response. That's the way it is in Unix filesystem. See this for example <ugrad.cs.ubc.ca/~cs219/CourseNotes/Unix/unix-fileStructure.html>.
1

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';
  }
}

Comments

0

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!

Comments

0

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.

1 Comment

because php is a cpp based language, you can get the first character more quickly using $entry[0]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.