Jump to content


Photo

Show files in a specific folder


  • Please log in to reply
8 replies to this topic

#1 markspec87

markspec87
  • Members
  • PipPipPip
  • Advanced Member
  • 63 posts

Posted 06 September 2006 - 02:51 PM

Is there anyway PHP can output the filenames of files in a specific folder on my site?

:)



#2 ronverdonk

ronverdonk
  • Members
  • PipPipPip
  • Advanced Member
  • 277 posts
  • LocationNetherlands

Posted 06 September 2006 - 02:54 PM

Sure you can. Following lists 3 types of html files.
<?php
//
// An example if you want all of a specific file type in a directory. 
//
$Gdir = "mydir/";
foreach (glob("$Gdir/{*.htm,*.html,*.shtml}", GLOB_BRACE) as $file)
    echo $file.'<br>';
?>

Ronald  8)
RTFM is an almost extinct art form, it should be subsidized.

#3 Daniel0

Daniel0
  • Staff Alumni
  • Advanced Member
  • 11,956 posts

Posted 06 September 2006 - 02:54 PM

<?php
print_r(scandir("/etc"));
?>


#4 markspec87

markspec87
  • Members
  • PipPipPip
  • Advanced Member
  • 63 posts

Posted 06 September 2006 - 03:29 PM

Is there anyway i can error catch with that?

i.e If no files are found echo "no files were found" ?



#5 Daniel0

Daniel0
  • Staff Alumni
  • Advanced Member
  • 11,956 posts

Posted 06 September 2006 - 04:09 PM

<?php
$items = scandir("/path/to/whatever");
if(count($items) < 2)
{
	echo "No files found";
}
else {
	foreach($items as $item)
	{
		if($item != '.' && $item != '..')
		{
			echo "{$item}<br />\n";
		}
	}
}
?>


#6 markspec87

markspec87
  • Members
  • PipPipPip
  • Advanced Member
  • 63 posts

Posted 06 September 2006 - 05:18 PM

oo sigh.

My host has php4

says that command is php5 :(

Is there an alternative?

#7 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 06 September 2006 - 05:26 PM

You'll have to scan the directory manually using opendir and readdir.

#8 Daniel0

Daniel0
  • Staff Alumni
  • Advanced Member
  • 11,956 posts

Posted 06 September 2006 - 05:35 PM

<?php
$dir		= "/var/www";
$dh		= @opendir($dir);
$content	= array(); // to prevent an E_NOTICE
while($item	= @readdir($dh))
{
	if($item != '.' && $item != '..')
	{
		$content[] = $item;
	}
}

if(count($content) < 1)
{
	echo "Directory is empty or do not exist";
}
else {
	foreach($content as $item)
	{
		if(is_dir("{$dir}/{$item}"))
		{
			echo "[DIR] ";
		}
		echo "{$item}<br />\n";
	}
}
?>

Note that I put it in an array in the while loop so you could manipulate the array. Then I ran them through a loop again later to show you how to output it. You could of course just echo them directly from the while loop.

#9 markspec87

markspec87
  • Members
  • PipPipPip
  • Advanced Member
  • 63 posts

Posted 06 September 2006 - 05:44 PM

thanks for that.

Managed to get the files found to be links to them aswell.

Works a treat :)




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users