susanv
1
Good afternoon everyone,
I need to display files in a directory and have the following code, which works great:
<?php
$dir = “documents/”;
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
echo ‘<a href="documents/’.$file.‘">’.$file.‘</a><br />’;
}
closedir($dh);
?>
The results I get is:
De Beer 01.doc
De Beer 02.doc
.
…
Engelbrecht 01.doc
Can anyone please tell me how to remove the . and … ?
Any help would be much appreciated.
Try this:
<?php
function read_dir($dir, $array = array())
{
$dh = opendir($dir);
$files = array();
while (($file = readdir($dh)) !== false)
{
$flag = false;
if($file !== '.' && $file !== '..' && !in_array($file, $array))
{
$files[] = $file;
}
}
return $files;
}
?>
susanv
3
Thanks for replying John, but it is still not working… any other ideas? I don’t know what else to try. 
What is not working? Please keep everyone up-to-date with the code that you’re trying, so we can explain why it might not be working.
susanv
5
I am very new to PHP Salathe, so I have tried a couple of things. This being the last:
<?php
function read_dir($dir, $array = array())
{
$dir = “documents/”;
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
$flag = false;
if($file !== ‘.’ && $file !== ‘…’ && !in_array($file, $array))
{
$files = $file;
}
}
return $files;
}
echo ‘<a href="documents/’.$file.‘">’.$file.‘</a><br />’;
}
closedir($dh);
?>
The output is still:
De Beer 01.doc
De Beer 02.doc
.
…
Engelbrecht 01.doc
I think your problem was that you were still using your script and not calling the function read_dir()
Try this and once working delete or remark “echo jj,”:
#debug stuff - saves typing
define('jj', '<br />DEBUG: ');
define('jk', ' - ');
echo jj, __LINE__, jk, 'START';
echo jj, __LINE__, jk,
$dir = "documents/";
# make sure directory exists to prevent endless loop
if( is_dir( $dir ) )
{
echo jj, __LINE__, jk,
$dh = opendir($dir);
while (($file = readdir($dh)) !== false)
{
if( $file === '.' OR $file === '..')
{
# echo '<br />DO NOT ECHO: ' .$file;
}
else
{
echo '<br /><a href="documents/'.$file.'">'.$file.'</a>';
}
}
}
echo jj, __LINE__, jk, 'FINISH';
Are you really using a version of PHP below 5?
If using a good version (PHP 5+) then:
$files = scandir( '/path/to/dir/' );
foreach ( $files as $file ) {
if ( $file === '.' || $file === '..' )
continue;
echo $file;
}
# Or
$files = array_diff( scandir( $dir ), array( '..', '.' ) );
foreach ( $files as $file )
echo $file;
susanv
8
Thank you so much John, that worked!! 