<html>
<body>
<?
$dir = "."; // current directory (from file system point of view)
// figure out link path for files
$php_self = $_SERVER['PHP_SELF'];
$web_path = substr($php_self, 0, strrpos($php_self, "/")+1);
// Open the directory, and proceed to read its contents
if (is_dir($dir))
{
if ($dh = opendir($dir))
{
while (($file = readdir($dh)) !== false)
{
if ($file == "." || $file == "..")
{
continue;
}
$file_array[] = $file;
}
closedir($dh);
}
}
sort($file_array);
?>
<h2><?=$web_path?></h2>
<ul>
<?
foreach ($file_array AS $file)
{
?>
<li><a href='<?=$web_path?><?=rawurlencode($file)?>'><?=$file?></a>
<?
}
?>
</ul>
</body>
</html>>
Friday, May 25, 2007
Simple PHP directory listing
I needed a SIMPLE directory listing script written in PHP for a large number of files I had to import to a web site. I found a lot of fancy css-styled file viewers, but I just wanted a simple one that would generate html and links for me. So, I wrote one. Here it is:
Subscribe to:
Post Comments (Atom)
4 comments:
Hi!
I have trouble figuring out the link path for my files.
I cleaned it up a bit and made it work with newer PHP. For simple string literals, always use single quotes, otherwise the entire string get's evaluated for special escape characters. A small thing but good practice for scaling up.
<html>
<body>
<?php
$dir = '.'; // current directory (from file system point of view)
// figure out link path for files
$php_self = $_SERVER['PHP_SELF'];
$web_path = substr($php_self, 0, strrpos($php_self, '/')+1);
// Open the directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if ($file == '.' || $file == '..') {
continue;
}
$file_array[] = $file;
}
closedir($dh);
}
}
sort($file_array);
?>
<h2><?php $web_path?></h2>
<ul>
<?php
foreach ($file_array AS $file) {
?>
<li><a href='<?php echo $web_path; ?><?php echo rawurlencode($file); ?>'><?php echo $file; ?></a>
<?php
}
?>
</ul>
</body>
</html>
Thanks mate!
Simple and efficient. Took so long to find such easy script...
tx very much for this script, simple and working well
Post a Comment