Skip to content
Advertisement

readdir function is not reading the whole directory on linux system

On my hosting provider i have a directory called hosts that has a structure like this

   .
├── hosts.php
├── ma_man_com.php
└── ma_women_com.php

0 directories, 3 files

the content of hosts.php file is this

<?php

$folderhost = opendir ( "./" );
$hosy = readdir ( $folderhost );
while ( $hostname = readdir ( $folderhost ) ) {
    echo $hostname.PHP_EOL;

}
closedir ( $folderhost );
?>

when i run hosts.php i get this output

 .
..
hosts.php
ma_man_com.php

so php doesn’t show ma_women_com.php !

if i removed this useless line from hosts.php

$hosy = readdir ( $folderhost );

the output goes fine and it can read ma_women_com.php

in addition if i removed on letter from one of the files like renaming ma_women_com.php to ma_women_co.php

then the output goes fine too

the strangest thing is that this behavior does not exist on my local host machine with windows 7 and xampp server

I know that the line that i removed from the code is useless and i can simply remove it and the problem will be solved but i’m curious why did this behavior happen and why it happened only on openshift linux servers ?

Advertisement

Answer

Your code with the extra readdir skips the first entry read; since readdir reads files in arbitrary order and it is platform dependent what the order is, this means that on one platform you may skip ., on others a particular file; also note that the order of files may change if you change something in the directory, e.g. rename a file, which is apparently what happened when you removed one letter from the filename.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement