Forum Moderators: coopster

Message Too Old, No Replies

Displaying directory contents

         

jspeed

4:39 pm on Jan 6, 2010 (gmt 0)

10+ Year Member



The script below displays the contents of a directory, and generates a checkbox by each file. In this case it is images, then you can delete the images that have been checked.

The script works fine, but it also reads and displays the directories within the images directory, so it displays them as broken images with a checkbox by them. How do I exclude the directories from being listed?

$file_ary = isset($_POST['rfile']) ? $_POST['rfile'] : array();

if ($file_ary){header("Refresh: 2;");}

$image_path = dirname(__FILE__) . '/images';
$dir_handle = null;

if (!($dir_handle = opendir($image_path)))
{
//trigger_error('error, path not found');
return;
}
$html = '<html><form method="post">';
$file = readdir($dir_handle);

while ($file)
{
$html .= "<img src='images/{$file}' height='10%' width='10%'><input type=\"checkbox\" name=\"rfile[]\" value=\"{$file}\" />\r\n";
$file = readdir($dir_handle);
}
closedir($dir_handle);

$html .= '<br><br><input type="submit" name="submit" value="DELETE" />';
$html .= "</form></html>";
echo $html;

if (!empty($file_ary))
{

$dir = 'images/';

foreach ($file_ary as $key => $value) {

if (unlink($dir.$file_ary[$key])){}

}
echo "<br><DIV ALIGN='CENTER'><img src='load.gif'></DIV><br>";
}

Psychopsia

5:31 pm on Jan 6, 2010 (gmt 0)

10+ Year Member



Try something like:

if (is_dir($image_path . '/' . $file))
{
continue;
}

Put this code before this line:

$html .= "<img src= ...

Hope this helps.

jspeed

8:52 pm on Jan 6, 2010 (gmt 0)

10+ Year Member



Tried it, I get this error:

Fatal error: Maximum execution time of 30 seconds exceeded in /home/user/public_html/folder/index.php on line 20

which is the if statement line

jspeed

9:00 pm on Jan 6, 2010 (gmt 0)

10+ Year Member



If it helps, there isn't actually any directories within the images directory, it ends up trying to display images/. and images/..

Psychopsia

9:53 pm on Jan 6, 2010 (gmt 0)

10+ Year Member



Change it to: (instead of my last code)

if (substr($file, 0, 1) == '.')
{
continue;
}

jspeed

4:34 pm on Jan 7, 2010 (gmt 0)

10+ Year Member



Thanks for your help, I got it to work with this code in the loop:

while ($file)
{
if(ereg("(.*)\.(jpg¦bmp¦jpeg¦png¦gif)", $file)){
$html .= "<img src='{$dir}$file' alt=''><input type=\"checkbox\" name=\"rfile[]\" value=\"{$file}\" />\r\n";
}

$file = readdir($dir_handle);
}