Hello …I just was trying to output the file names of different folders in my PC using PHP code…But I found that it outputs actually more than visible files in that particular folder…So what did I mean by visible that when I count the number of files in my folder it appears 18 but when i output it appears that the numer is 20. That two files are not visible. One if the is “Folder.jpg” and the second of them is a “.doc” file i opened and think it is inserted by “Administrator”…This is the code
<?php
function getDirectoryList ($directory)
{
// create an array to hold directory list
$results = array();
// create a handler for the directory
$handler = opendir($directory);
// open directory and walk through the filenames
while ($file = readdir($handler)) {
// if file isn't this directory or its parent, add it to the results
if ($file != "." && $file != "..") {
$results[] = $file;
}
}
// tidy up: close the handler
closedir($handler);
// done!
return $results;
}
$array_1=getDirectoryList("C:\\Documents and Settings\\Администратор\\Мои документы\\Downloads");
foreach($array_1 as $value)
{
echo "<br/>".$value;
}
?>
So here is my question …how can I output only that 18 files and not that invisible files ? Since I want to work only with files that I see.
You could use FilterIterator and DirectoryIterator here, let’s say your filter is call HiddenFileFilter, this would be the code you need to loop through the directory.
$directory = new DirectoryIterator('/');
foreach(new HiddenFileFilter($directory) as $file){
echo $file->getFilename(), PHP_EOL ;
}
The code that filters out hidden files would look something similar to
class HiddenFileFilter extends FilterIterator
{
public function accept(){
return ! $this->isCurrentFileHidden();
}
protected function isCurrentFileHidden(){
$path = $this->getCurrentFullFilePath();
if($this->isRunningOnWindows()){
return $this->isFileHiddenOnWindows($path);
}
return $this->isFileHiddenOnUnix($path);
}
protected function isRunningOnWindows(){
return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
}
protected function getCurrentFullFilePath(){
$file = $this->current();
return $file->getPathname() . DIRECTORY_SEPARATOR . $file->getFilename();
}
protected function isFileHiddenOnUnix($path){
# execute bash to determine file is hidden
return true;
}
protected function isFileHiddenOnWindows($path){
# execute cmd to determine file is hidden
return true;
}
}
The HiddenFileFilter::accept() method should return either true or false; true to display the file and false if not.
I did spot this over at the manual though, it might be of interest.