Log in

View Full Version : I need to improve on this code that displays all files in a folder



Geezer D
06-03-2009, 05:27 AM
Hi, all.
I currently have this PHP code on my site to display all the videos I have in one folder (so I don't have to update the HTML every time I add or delete one):


<?

$path = "/home/content/d/e/f/defensecenter/html/videos/student002";

$dir_handle = @opendir($path) or die("Unable to open $path");

while ($file = readdir($dir_handle)) {

if($file == "." || $file == ".." || $file == "index.php" )

continue;
echo "<div class='vidlink'><a href=\"$file\">$file</a></div>";

}

closedir($dir_handle);
?>

But it has 2 problems:
1. It displays the .htaccess file which I have there for password protection (not a big deal, it opens to an error page, but I'd prefer it not show at all).

2. It doesn't put them in alphanumerical order, it seams to just spit them up randomly (though the files are in the same order every time I visit/refresh the page).

Any help would be appreciated. I know little to nothing about PHP, I got that code off the web.

I could also use a good video tutorial on beginning PHP. I tried Lynda.com and a couple others, but found them very confusing, and I'm not dense, I do OK with HTML and CSS, but I can't get my head around PHP from any tutorial I've found.

Thanks a lot!
-Geezer

techietim
06-03-2009, 09:59 AM
$path = '/home/content/d/e/f/defensecenter/html/videos/student002';
$dir_handle = @scandir($path);
if($dir_handle){
foreach($dir_handle as $file){
if(!in_array($file, array('..', '.', '.htaccess', 'index.php'))){
echo "<div class='vidlink'><a href=\"$file\">$file</a></div>";
}
}
}

Geezer D
06-03-2009, 10:13 PM
Worked like a charm, thanks a million.

Any suggestions on video tutorials for PHP would also be appreciated.

traq
06-04-2009, 03:15 AM
PHP 101 (http://devzone.zend.com/node/view/id/627) is easy to follow, humorous, and engaging. That said, however, there are typos in some lines of script, and pieces from earlier lessons (or prerequisite html code) are sometimes omitted, so I would only recommend it if you're okay with problem solving. I actually ended up learning quite a bit from the mistakes. The other issue is that it was written quite a while ago, so while it covers PHP5, most stuff is PHP4-oriented.

Tzag (http://www.tizag.com/phpT/) is a good tutorial also. It covers more aspects of PHP in a more typical "tutorial" manner, meaning it was written "for beginners" by people who are definitely not beginners and can't quite think like beginners. I've heard PHP guys offer complaints about missing/inaccurate stuff in these tutorials, but I haven't run across any problems myself.

sorry, I didn't see that you wanted video tutorials.