 |
opendir (PHP 3, PHP 4, PHP 5) opendir -- 打开目录句柄 参数
- path
要打开的目录路径
- context
context 参数的说明见手册中的
Streams API 一章。
返回值
如果成功则返回目录句柄的 resource,失败则返回 FALSE。
如果 path
不是一个合法的目录或者因为权限限制或文件系统错误而不能打开目录,opendir()
返回 FALSE 并产生一个 E_WARNING
级别的 PHP 错误信息。可以在 opendir()
前面加上“@”符号来抑制错误信息的输出。
范例
例子 1. opendir() 例子
<?php $dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { echo "filename: $file : filetype: " . filetype($dir . $file) . "\n"; } closedir($dh); } } ?>
|
上例的输出类似于: filename: . : filetype: dir
filename: .. : filetype: dir
filename: apache : filetype: dir
filename: cgi : filetype: dir
filename: cli : filetype: dir |
|
tim2005
13-May-2006 08:04
Hello,
A friend of mine is running a webhost, I think i found a security leak with this script:
<?php
function select_files($dir, $label = "", $select_name, $curr_val = "", $char_length = 30) {
$teller = 0;
if ($handle = opendir($dir)) {
$mydir = ($label != "") ? "<label for=\"".$select_name."\">".$label."</label>\n" : "";
$mydir .= "<select name=\"".$select_name."\">\n";
$curr_val = (isset($_REQUEST[$select_name])) ? $_REQUEST[$select_name] : $curr_val;
$mydir .= ($curr_val == "") ? " <option value=\"\" selected>...\n" : "<option value=\"\">...\n";
while (false !== ($file = readdir($handle))) {
$files[] = $file;
}
closedir($handle);
sort($files);
foreach ($files as $val) {
if (is_file($dir.$val)) { // show only real files (ver. 1.01)
$mydir .= " <option value=\"".$val."\"";
$mydir .= ($val == $curr_val) ? " selected>" : ">";
$mydir .= (strlen($val) > $char_length) ? substr($val, 0, $char_length)."...\n" : $val."\n";
$teller++;
}
}
$mydir .= "</select>";
}
if ($teller == 0) {
$mydir = "No files!";
} else {
return $mydir;
}
}
echo select_files("C:/winnt/", "", "", "", "60");
?>
Now i can see hist files in his windows dir. Is this a leak? and is it fixable? I'll report this as bug too!
Tim2005
tozeiler
15-Apr-2006 04:34
"opendir" said:
------------------------------------------------------------------
23-Jan-2006 08:04
I Just wanted a directory list and a clickable link to download the files
<snip>
------
<?
echo ("<h1>Directory Overzicht:</h1>");
function getFiles($path) {
<snip complicated function contents>
------------------------------------------------------------------
Here's a more straightforward way to linkify $path/files:
<?php
echo "<h1>Directory Overzicht:</h1>";
$dh = opendir($path);
while (($file = readdir($dh)) !== false) {
echo "<a href='$path/$file'>$file</a><br />";
}
closedir($dh);
?>
23-Jan-2006 11:04
I Just wanted a directory list and a clickable link to download the files because my plesk server does not give me this function. I edited the script a little bit.
Many thanks from a script-noob
------
<?
echo ("<h1>Directory Overzicht:</h1>");
function getFiles($path) {
//Function takes a path, and returns a numerically indexed array of associative arrays containing file information,
//sorted by the file name (case insensitive). If two files are identical when compared without case, they will sort
//relative to each other in the order presented by readdir()
$files = array();
$fileNames = array();
$i = 0;
if (is_dir($path)) {
if ($dh = opendir($path)) {
while (($file = readdir($dh)) !== false) {
if ($file == "." || $file == "..") continue;
$fullpath = $path . "/" . $file;
$fkey = strtolower($file);
while (array_key_exists($fkey,$fileNames)) $fkey .= " ";
$a = stat($fullpath);
$files[$fkey]['size'] = $a['size'];
if ($a['size'] == 0) $files[$fkey]['sizetext'] = "-";
else if ($a['size'] > 1024) $files[$fkey]['sizetext'] = (ceil($a['size']/1024*100)/100) . " K";
else if ($a['size'] > 1024*1024) $files[$fkey]['sizetext'] = (ceil($a['size']/(1024*1024)*100)/100) . " Mb";
else $files[$fkey]['sizetext'] = $a['size'] . " bytes";
$files[$fkey]['name'] = $file;
$files[$fkey]['type'] = filetype($fullpath);
$fileNames[$i++] = $fkey;
}
closedir($dh);
} else die ("Cannot open directory: $path");
} else die ("Path is not a directory: $path");
sort($fileNames,SORT_STRING);
$sortedFiles = array();
$i = 0;
foreach($fileNames as $f) $sortedFiles[$i++] = $files[$f];
return $sortedFiles;
}
$files = getFiles("./");
foreach ($files as $file) print " <b><a href=\"$file[name]\">$file[name]</a></b><br>\n";
?>
mstabile75 at gmail dot com
29-Dec-2005 12:26
In my previous post I ran into a problem with the "global" definition of $directorylist. If I called the function more than once on the same page it would combine the file lists. I looked at Lasse Dalegaard's example and used the following solution.
remove global definition
global $directorylist;
REPLACE
<?
if ((($maxlevel) == "all") or ($maxlevel > $level)) {
filelist($startdir . $file . "/", $searchSubdirs, $directoriesonly, $maxlevel, $level + 1);
}
?>
WITH
<?
if ((($maxlevel) == "all") or ($maxlevel > $level)) {
$list2 = filelist($startdir . $file . "/", $searchSubdirs, $directoriesonly, $maxlevel, $level + 1);
if(is_array($list2)) {
$directorylist = array_merge($directorylist, $list2);
}
}
?>
mstabile75 at gmail dot com
27-Dec-2005 11:04
<?php
/* The below function will list all folders and files within a directory
It is a recursive function that uses a global array. The global array was the easiest
way for me to work with an array in a recursive function
*This function has no limit on the number of levels down you can search.
*The array structure was one that worked for me.
ARGUMENTS:
$startdir => specify the directory to start from; format: must end in a "/"
$searchSubdirs => True/false; True if you want to search subdirectories
$directoriesonly => True/false; True if you want to only return directories
$maxlevel => "all" or a number; specifes the number of directories down that you want to search
$level => integer; directory level that the function is currently searching
*/
function filelist ($startdir="./", $searchSubdirs=1, $directoriesonly=0, $maxlevel="all", $level=1) {
//list the directory/file names that you want to ignore
$ignoredDirectory[] = ".";
$ignoredDirectory[] = "..";
$ignoredDirectory[] = "_vti_cnf";
global $directorylist; //initialize global array
if (is_dir($startdir)) {
if ($dh = opendir($startdir)) {
while (($file = readdir($dh)) !== false) {
if (!(array_search($file,$ignoredDirectory) > -1)) {
if (filetype($startdir . $file) == "dir") {
//build your directory array however you choose;
//add other file details that you want.
$directorylist[$startdir . $file]['level'] = $level;
$directorylist[$startdir . $file]['dir'] = 1;
$directorylist[$startdir . $file]['name'] = $file;
$directorylist[$startdir . $file]['path'] = $startdir;
if ($searchSubdirs) {
if ((($maxlevel) == "all") or ($maxlevel > $level)) {
filelist($startdir . $file . "/", $searchSubdirs, $directoriesonly, $maxlevel, $level + 1);
}
}
} else {
if (!$directoriesonly) {
//if you want to include files; build your file array
//however you choose; add other file details that you want.
$directorylist[$startdir . $file]['level'] = $level;
$directorylist[$startdir . $file]['dir'] = 0;
$directorylist[$startdir . $file]['name'] = $file;
$directorylist[$startdir . $file]['path'] = $startdir;
}}}}
closedir($dh);
}}
return($directorylist);
}
$files = filelist("./",1,1); // call the function
foreach ($files as $list) {//print array
echo "Directory: " . $list['dir'] . " => Level: " . $list['level'] . " => Name: " . $list['name'] . " => Path: " . $list['path'] ."<br>";
}?>
chrys at mytechjournal dot com
11-Dec-2005 03:16
I wrote a function to recursively delete files from a starting directory. I had to do this because my server doesn't allow me to delete files that apache writes because I don't have permissions, so... I let apache do the work.
<?php
$dir = "/path/to/base/dir";
recursive_delete($dir);
function recursive_delete( $dir )
{
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false ) {
if( $file != "." && $file != ".." )
{
if( is_dir( $dir . $file ) )
{
echo "Entering Directory: $dir$file<br/>";
recursive_delete( $dir . $file . "/" );
echo "Removing Directory: $dir$file<br/><br/>";
rmdir( $dir . $file );
}
else
{
echo "Deleting file: $dir$file<br/>";
unlink( $dir . $file );
}
}
}
closedir($dh);
}
}
}
?>
neale-php at woozle dot org
01-Dec-2005 01:41
oryan's example is still sub-optimal, even if people using it never ever substitute a variable for directory.
Just use PHP's glob() function, which will be faster and more efficient anyway since it doesn't have to launch a shell and run the ls program (that's what the shell_exec does).
$result = glob("directory/*");
oryan at zareste dot com
01-Nov-2005 07:19
There might be a bit of truth to that. If, by chance, the webmaster made a form saying "type a random directory name here" and used that in the function, there'd be a problem. So let's eliminate the 'function' part
$files=shell_exec("ls directory");
$result=explode("\n",$files);
'$result' will now be an array of the directory files. You can use variables in the shell_exec command, but don't use anything that could be user-sent.
aligma at gmail dot com
01-Nov-2005 11:54
The example given by oryan at zareste dot com may also be a "simpler faster way" of creating security holes in your code. The function listed above prevents risking execution of abitrary shell commands listed after a semicolon (;) in your directory name.
Example: $directory = '.;rm -rf /';
Result: List this directory, erase contents of filesystem.
oryan at zareste dot com
31-Oct-2005 09:33
There's a simpler faster way to get a whole directory if you're using PHP 4. This function uses shell_exec - http://us3.php.net/shell_exec - and assumes you're using Unix/Linux and have shell access -
function dir($directory){
$files=shell_exec("ls ".$directory);
return explode("\n",$files);
}
This returns an array with all the files.
This way, you can use modifiers like -t, which shows files in order of modification time ($files=shell_exec("ls -t ".$directory);). Enough tweaking and you can use it on Windows, though I can't say how since I don't have a Windows server to try it on
asharm4 at ilstu dot edu
08-Oct-2005 12:56
//this is a function I wrote to sort out the contents of the directory date wise for display.
$content_array = array();
//set current working directory
$dirname = "C:\temp";
//Load Directory Into Array
$handle=opendir($dirname);
$i=0;
while ($file = readdir($handle))
if ($file != "." && $file != "..")
{
$content_array[$i][0] = $file;
$content_array[$i][1] = date ("Y m d", filemtime($dirname."/".$file));
$i++;
}
//close the directory handle
closedir($handle);
//these lines sort the contents of the directory by the date
foreach($content_array as $res)
$sortAux[] = $res[1];
array_multisort($sortAux, SORT_ASC, $content_array);
06-Oct-2005 12:40
This function sorts files by name as strings, but without regard to case. It also does some handy string formatting of the file size information.
<?
function getFiles($path) {
//Function takes a path, and returns a numerically indexed array of associative arrays containing file information,
//sorted by the file name (case insensitive). If two files are identical when compared without case, they will sort
//relative to each other in the order presented by readdir()
$files = array();
$fileNames = array();
$i = 0;
if (is_dir($path)) {
if ($dh = opendir($path)) {
while (($file = readdir($dh)) !== false) {
if ($file == "." || $file == "..") continue;
$fullpath = $path . "/" . $file;
$fkey = strtolower($file);
while (array_key_exists($fkey,$fileNames)) $fkey .= " ";
$a = stat($fullpath);
$files[$fkey]['size'] = $a['size'];
if ($a['size'] == 0) $files[$fkey]['sizetext'] = "-";
else if ($a['size'] > 1024) $files[$fkey]['sizetext'] = (ceil($a['size']/1024*100)/100) . " K";
else if ($a['size'] > 1024*1024) $files[$fkey]['sizetext'] = (ceil($a['size']/(1024*1024)*100)/100) . " Mb";
else $files[$fkey]['sizetext'] = $a['size'] . " bytes";
$files[$fkey]['name'] = $file;
$files[$fkey]['type'] = filetype($fullpath);
$fileNames[$i++] = $fkey;
}
closedir($dh);
} else die ("Cannot open directory: $path");
} else die ("Path is not a directory: $path");
sort($fileNames,SORT_STRING);
$sortedFiles = array();
$i = 0;
foreach($fileNames as $f) $sortedFiles[$i++] = $files[$f];
return $sortedFiles;
}
$files = getFiles("C:");
foreach ($files as $file) print "$file[name]<br>\n";
?>
Lasse Dalegaard
22-May-2005 03:25
I made a function for finding all files in a specified directory and all subdirectories. It can be quite usefull when searching in alot of files in alot subdirectories. The function returns an array with the path of all the files found.
<?
function getFiles($directory) {
// Try to open the directory
if($dir = opendir($directory)) {
// Create an array for all files found
$tmp = Array();
// Add the files
while($file = readdir($dir)) {
// Make sure the file exists
if($file != "." && $file != ".." && $file[0] != '.') {
// If it's a directiry, list all files within it
if(is_dir($directory . "/" . $file)) {
$tmp2 = getFiles($directory . "/" . $file);
if(is_array($tmp2)) {
$tmp = array_merge($tmp, $tmp2);
}
} else {
array_push($tmp, $directory . "/" . $file);
}
}
}
// Finish off the function
closedir($dir);
return $tmp;
}
}
// Example of use
print_r(getFiles('.')); // This will find all files in the current directory and all subdirectories
?>
brett at medeaproject dot co dot za
11-May-2005 03:02
This is a little script i wrote to generate a home page on my dev box by parsing the contents of my htdocs directory. It is encapsulated in a html table
Arb but useful if you are as lazy as I am ;)
<?
$handle = opendir("./");
while (($file = readdir($handle))!==false) {
if(is_dir($file)){
if($file != "." && $file != ".."){?>
<tr>
<td align="center" bgcolor="FFFFFF"><a href="<?= $file;?>"><?php echo ucwords($file)?></a></strong></td>
</tr>
<?php
}
}
}
closedir($handle);
$handle = opendir("./");
while (($file = readdir($handle))!==false) {
if(is_file($file)){
if($file != "." && $file != ".."){?>
<tr>
<td align="center" bgcolor="FFFFFF"><a href="<?= $file?>"><?php echo ucwords($file)?></a></strong></td>
</tr>
<?php
}
}
}
closedir($handle);
?>
brett at medeaproject dot co dot za
11-May-2005 03:01
This is a little script i wrote to generate a home page on my dev box by parsing the contents of my htdocs directory. It is encapsulated in a html table
Arb but useful if you are as lazy as I am ;)
<?
$handle = opendir("./");
while (($file = readdir($handle))!==false) {
if(is_dir($file)){
if($file != "." && $file != ".."){?>
<tr>
<td align="center" bgcolor="FFFFFF"><a href="<?= $file;?>"><?php echo ucwords($file)?></a></strong></td>
</tr>
<?php
}
}
}
closedir($handle);
$handle = opendir("./");
while (($file = readdir($handle))!==false) {
if(is_file($file)){
if($file != "." && $file != ".."){?>
<tr>
<td align="center" bgcolor="FFFFFF"><a href="<?= $file?>"><?php echo ucwords($file)?></a></strong></td>
</tr>
<?php
}
}
}
closedir($handle);
?>
iamnotanerd
30-Mar-2005 01:38
Here is a snippet of the code that I created to search for a file..recursively open the directories and search for a match..
<?
function search($target, $directory){
if(is_dir($directory)){
$direc = opendir($directory);
while(false !== ($file = readdir($direc))){
if($file !="." && $file != ".."){
if(is_file($directory."/".$file)){
if(preg_match("/$target/i", $file)){
echo "<a href=\"$directory/$file\">$file</a><br>";
}
}else if(is_dir($directory."/".$file)){
search($target,$directory."/".$file);
}
}
}
closedir($direc);
}
return ;
}
?>
hendrik dot wermer at gmx dot de
08-Feb-2005 09:06
Here's another version of directory listing, since I had some problems using the examples below. It will display the content of the current directory, sorted by directories and files.
You can also search subdirectories by setting $maxDepth > 0. There's a link to other directories, so you can easily switch to the parent directory or to other directories in the current directory.
Hope it helps!
<?php
// show directory content
function showDir($dir, $i, $maxDepth){
$i++;
if($checkDir = opendir($dir)){
$cDir = 0;
$cFile = 0;
// check all files in $dir, add to array listDir or listFile
while($file = readdir($checkDir)){
if($file != "." && $file != ".."){
if(is_dir($dir . "/" . $file)){
$listDir[$cDir] = $file;
$cDir++;
}
else{
$listFile[$cFile] = $file;
$cFile++;
}
}
}
// show directories
if(count($listDir) > 0){
sort($listDir);
for($j = 0; $j < count($listDir); $j++){
echo "
<tr>";
$spacer = "";
for($l = 0; $l < $i; $l++) $spacer .= " ";
// create link
$link = "<a href=\"" . $_SERVER["PHP_SELF"] . "?dir=" . $dir . "/" . $listDir[$j] . "\">$listDir[$j]</a>";
echo "<td>" . $spacer . $link . "</td>
</tr>";
// list all subdirectories up to maxDepth
if($i < $maxDepth) showDir($dir . "/" . $listDir[$j], $i, $maxDepth);
}
}
// show files
if(count($listFile) > 0){
sort($listFile);
for($k = 0; $k < count($listFile); $k++){
$spacer = "";
for($l = 0; $l < $i; $l++) $spacer .= " ";
echo "
<tr>
<td>" . $spacer . $listFile[$k] . "</td>
</tr>";
}
}
closedir($checkDir);
}
}
if($_GET["dir"] == "" || !is_dir($_GET["dir"])) $dir = getcwd();
else $dir = $_GET["dir"];
// replace backslashes, not necessary, but better to look at
$dir = str_replace("\\", "/", $dir);
// show parent path
$pDir = pathinfo($dir);
$parentDir = $pDir["dirname"];
echo "<a href=\"" . $_SERVER["PHP_SELF"] . "\"><h3>Home</h3></a>";
echo "Current directory: " . $dir;
echo "<a href=\"" . $_SERVER["PHP_SELF"] . "?dir=$parentDir\"><h4>Parent directory: $parentDir</h4></a>";
// Display directory content
echo"<table border=1 cellspacing=0 cellpadding=2>
<tr><th align=left>File / Dir</th>";
// specifies the maxDepth of included subdirectories
// set maxDepth to 0 if u want to display the current directory
$maxDepth = 0;
showDir($dir, -1, $maxDepth);
?>
sandy at montana-riverboats dot com
30-Sep-2004 12:08
<?php
/*
** This recursive file lister only slurps in one page at time,
** so it doesn't take forever to load when operating over
** a large system.....comes with an "Up" link for every page too.
*/
$PHP_SELF = $_SERVER['PHP_SELF'];
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
# activate the next line (and deactivate the last) to
# use this script in a $DOCUMENT_ROOT/~anybody
# environment.
#$DOCUMENT_ROOT="/home/sandy/public_html/";
$tdir = $_GET['dir'];
echo "tdir==$tdir<br>";
$tparent_path = $_GET['parent_path'];
$dbg = $_GET['dbg'];
if(!strstr($tdir, $DOCUMENT_ROOT))
$tdir = getcwd();
if(!strstr($tparent_path, $DOCUMENT_ROOT))
$tparent_path = $tdir;
if (!isset ($tdir))
{
$dir = getcwd ();
}
else
$dir = $tdir;
if (!isset ($tparent_path))
{
$parent_path = $dir;
}
else
$parent_path = $tparent_path;
echo "<br>";
if (!isset ($tdir))
{
$upurl = $PHP_SELF;
}
else
{
if ($parent_path == $DOCUMENT_ROOT)
$parent_parent_path = $parent_path;
else
$parent_parent_path = dirname ($parent_path);
$upurl = $PHP_SELF."?dir=".$parent_path."&parent_path=".
$parent_parent_path;
}
if($dbg==1)
{
echo "PHP_SELF: $PHP_SELF<br>\n";
echo "DOCUMENT_ROOT: $DOCUMENT_ROOT<br>\n";
echo "dir: $dir<br>\n";
echo "parent_path: $parent_path<br>\n";
echo "upurl: $upurl<br>\n";
}
echo "<a href=\"$upurl\"> <h3>Up</h3> </a>\n";
echo "<h2>$dir</h2>\n";
create_tree ($dir, $parent_path);
function
urlFromPath ($path)
{
global $PHP_SELF;
global $DOCUMENT_ROOT;
$prefix = "";
if (substr ($path, 0, 1) != "/")
$prefix = "/";
$url = $prefix.ereg_replace ($DOCUMENT_ROOT, "", $path);
return $url;
}
function
create_tree ($dir, $parent_path)
{
if ($handle = opendir ($dir))
{
$i = 0;
while (false !== ($file = @readdir ($handle)))
{
if ($file != "." && $file != "..")
{
$list[$i] = $file;
$i++;
}
}
$dir_length = count ($list);
echo "<ul>";
for ($i = 0; $i < $dir_length; $i++)
{
global $PHP_SELF;
global $DOCUMENT_ROOT;
$label = $list[$i];
$test = $dir."/".$label;
$alink = $dir."/".ereg_replace(" ","%20",$label);
if (!strstr ($PHP_SELF, $label))
{
if (is_dir ($test))
{
$tmp = $PHP_SELF. "?dir=".$alink."&parent_path=".$dir;
$url = ereg_replace(" ", "%20", $tmp);
echo "$url<br>\n";
echo "<a href=\"$url\"><b>$label</b>/</a><br>\n";
}
else
{
$link = urlFromPath ($alink);
$label = $list[$i];
echo
"<a href=\"$link\">".$label."</a><br>\n";
}
}
}
echo "</ul>";
closedir ($handle);
}
}
?>
cnichols at nmu dot edu
18-Sep-2004 02:03
Here's another recursive function that prints out everything from the starting path to the end. It doesn't have any search function, but just another example. I wrote it for getting a quick hierarchial view of websites (even through Dreamweaver will show it to me, it'd be a chore to go through each folder and expand it).
<?php
// map_dirs(path,level)
// path, level to start (start at 0)
map_dirs("/var/ww/html/",0);
function map_dirs($path,$level) {
if(is_dir($path)) {
if($contents = opendir($path)) {
while(($node = readdir($contents)) !== false) {
if($node!="." && $node!="..") {
for($i=0;$i<$level;$i++) echo " ";
if(is_dir($path."/".$node)) echo "+"; else echo " ";
echo $node."\n";
map_dirs("$path/$node",$level+1);
}
}
}
}
}
?>
MagicalTux at FF.st
09-Aug-2004 09:32
Note that the opendir() function will use ISO8859-1 characterset under windows...
If you have korean, japanese, etc.. filenames, you won't be able to open them. I still didn't find any solution to workaround that.
dale dot liszka at gmail dot com
07-Aug-2004 11:17
I whipped up a little recursive directory searching function that has been very useful. I figured it belonged here. I'm sure its not the most robust or creative code, but it works for me.
Note, you can use strpos for simple matches or preg_match if you want the power of regular expressions (however it is a bit slower). I also have it set to use double quotes "\\" for WIN32. change to "/" if necessary.
It returns an array of all matching files with full path.
function search_dir($mask,$dir,$level){
if($level > 3){
return "Exceeded max level (3)";
}
$return_me = array();
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
#echo "filename: $file : filetype: " . filetype($dir . $file) . " level: $level\n";
if(is_dir($dir."\\".$file) and $file != '.' and $file != '..'){
$test_return = search_dir($mask,$dir."\\".$file,$level+1);
if(is_array($test_return)){
$temp = array_merge($test_return,$return_me);
$return_me = $temp;
}
if(is_string($test_return)){
array_push($return_me,$test_return);
}
#} else if(strpos($file,$mask) !== FALSE){ #A bit faster, but you can't use regexs!
} else if(preg_match($mask,$file)){
array_push($return_me,$dir."\\".$file);
}
}
closedir($dh);
}
}
return $return_me;
}
Cabal at CnCWorld dot org
28-Mar-2004 10:21
I had problems getting it to work because I'm not the best at PHP, but there IS a way to use opendir to list things in alphabetical order. I'm using it for my university project. All you have to do is read the filenames into an array, sort the array and then do what you want with the filenames.... like this....
So that you know what all my variables mean in this - $stats is the folder that it looks in for the files - for example
?stats=images
would look in the images folder
Obviously you will want to modify it so it fits your needs, but I thought you guys would want this - especially if your server doesnt have the latest version of php.
===========================
<?php
$i = 0;
$arraycount = 0;
$home="/home/cabal/public_html/b146/admin/$stats";
if ($stats)
{
$dircheck="/home/cabal/public_html/b146/admin/$stats";
if (is_dir($dircheck))
{
if ($handle = opendir($home))
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$path = "$home/$file";
$extension = array_pop(explode('.', basename($path)));
$filearray[$i] = $file;
$i++;
}
}
}
closedir($handle);
}
else
{
echo "INCORRECT SELECTION";
}
}
else
{
echo "NOTHING SELECTED";
}
echo " ";
echo("<table width='100%' border='1'><tr><td><b><font color='#ff0000'>");
echo("$stats : Log File");
echo("</b></font></td><td><font color='#FF0000'><b>Page Views</b></font></td></tr>");
sort($filearray);
reset($filearray);
while (list($key, $val) = each($filearray))
{
$includearray = "$home/$filearray[$key]";
echo("<tr><td>");
echo("$val");
echo("</td><td>");
include($includearray);
echo("</td></tr>");
}
echo("</table>");
?>
dieck at gmx dot de
26-Feb-2004 08:47
If you have problems like "failed to open dir: Invalid argument"
when using IIS and trying to access windows/smb network shares, try
//servername/share/directory
instead of
\\servername\share
micklweiss at gmx dot net
20-Nov-2003 05:12
I ran into a little snag in example 1. opendir() lists files by the last time the file was accessed. I was trying to print the files numerically in a directory.
Solution: Use scandir() instead (php5) or store the files in an array and sort it.
Hope this helps someone.
- Mick
(o> Web / software developer
( ) UNIX Systems Admin
--- ~ www.mickweiss.com ~
info at 4design dot nu
23-Aug-2003 09:31
In addition to notes above about IIS & PHP reading network shares, here's one solution that works better for me.
in the management console I created a folder where my "read_dir" script runs. click on properties then select the security tab. here you can set the anonymous account to the standard IUSR_$computername% , BUT.. in this case I chose another account that I set up for reading my shares. (make sure login name and password match the credantials you set on the remote machin ;-))
I use this to read a dir and it's contents into a searchable database. and it works like a charm...
Matt Grimm
07-Jun-2003 04:25
Thought I could help clarify something with accessing network shares on a Windows network (2000 in this case), running PHP 4.3.2 under Apache 2.0.44.
However you are logged into the Windows box, your Apache service must be running under an account which has access to the share. The easiest (and probably least safe) way for me was to change the user for the Apache service to the computer administrator (do this in the service properties, under the "Log On" tab). After restarting Apache, I could access mapped drives by their assigned drive letter ("z:\\") or regular shares by their UNC path ("\\\\shareDrive\\shareDir").
kcgt at go dot com
30-Aug-2002 10:14
I don't know if this will work the same, but I was working with copy() in order to copy a file to a network drive using IIS.
In order to be able to copy to a network drive, you have to have permissions for the user IUSR_computername where computername is the name of the computer that is running PHP. Once permissions were set up on the remote machine, PHP was able to access the remote files. I don't know if this will work the same with opendir, but it might be worth a try......
|  |