php中$path=$dir.DS.$php is file is dir中的DS是什么意思

Folder & File & CakePHP Cookbook 2.x documentation
Folder & File
The Folder and File utilities are convenience classes to help you read from and
write/ list files within a folder and other common directory
related tasks.
Basic usage
Ensure the classes are loaded using :
App::uses('Folder', 'Utility');
App::uses('File', 'Utility');
Then we can setup a new folder instance:
$dir = new Folder('/path/to/folder');
and search for all .ctp files within that folder using regex:
$files = $dir-&find('.*\.ctp');
Now we can loop through the files and read from or write/append to the contents or
simply delete the file:
foreach ($files as $file) {
$file = new File($dir-&pwd() . DS . $file);
$contents = $file-&read();
// $file-&write('I am overwriting the contents of this file');
// $file-&append('I am adding to the bottom of this file.');
// $file-&delete(); // I am deleting this file
$file-&close(); // Be sure to close the file when you're done
Folder API
class Folder(string $path = false, boolean $create = false, string|boolean $mode = false)
// Create a new folder with 0755 permissions
$dir = new Folder('/path/to/folder', true, 0755);
property Folder::$path
Path of the current folder.
will return the same
information.
property Folder::$sort
Whether or not the list results should be sorted by name.
property Folder::$mode
Mode to be used when creating folders. Defaults to 0755. Does nothing on
Windows machines.
static Folder::addPathElement(string $path, string $element)
Return type:string
Returns $path with $element added, with correct slash in-between:
$path = Folder::addPathElement('/a/path/for', 'testing');
// $path equals /a/path/for/testing
$element can also be an array:
$path = Folder::addPathElement('/a/path/for', array('testing', 'another'));
// $path equals /a/path/for/testing/another
New in version 2.5: $element parameter accepts an array as of 2.5
Folder::cd(string $path)
Return type:string
Change directory to $path. Returns false on failure:
$folder = new Folder('/foo');
echo $folder-&path; // Prints /foo
$folder-&cd('/bar');
echo $folder-&path; // Prints /bar
$false = $folder-&cd('/non-existent-folder');
Folder::chmod(string $path, integer $mode = false, boolean $recursive = true, array $exceptions = array())
Return type:boolean
Change the mode on a directory structure recursively. This includes
changing the mode on files as well:
$dir = new Folder();
$dir-&chmod('/path/to/folder', 0755, true, array('skip_me.php'));
Folder::copy(array|string $options = array())
Return type:boolean
Copy a directory (recursively by default). The only parameter $options can either
be a path into copy to or an array of options:
$folder1 = new Folder('/path/to/folder1');
$folder1-&copy('/path/to/folder2');
// Will put folder1 and all its contents into folder2
$folder = new Folder('/path/to/folder');
$folder-&copy(array(
'to' =& '/path/to/new/folder',
'from' =& '/path/to/copy/from', // will cause a cd() to occur
'mode' =& 0755,
'skip' =& array('skip-me.php', '.git'),
'scheme' =& Folder::SKIP, // Skip directories/files that already exist.
'recursive' =& true //set false to disable recursive copy
There are 3 supported schemes:
Folder::SKIP skip copying/moving files & directories that exist in the
destination directory.
Folder::MERGE merge the source/destination directories. Files in the
source directory will replace files in the target directory. Directory
contents will be merged.
Folder::OVERWRITE overwrite existing files & directories in the target
directory with those in the source directory. If both the target and
destination contain the same subdirectory, the target directory’s contents
will be removed and replaced with the source’s.
Changed in version 2.3: The merge, skip and overwrite schemes were added to copy()
static Folder::correctSlashFor(string $path)
Return type:string
Returns a correct set of slashes for given $path (‘\’ for
Windows paths and ‘/’ for other paths).
Folder::create(string $pathname, integer $mode = false)
Return type:boolean
Create a directory structure recursively. Can be used to create
deep path structures like /foo/bar/baz/shoe/horn:
$folder = new Folder();
if ($folder-&create('foo' . DS . 'bar' . DS . 'baz' . DS . 'shoe' . DS . 'horn')) {
// Successfully created the nested folders
Folder::delete(string $path = null)
Return type:boolean
Recursively remove directories if the system allows:
$folder = new Folder('foo');
if ($folder-&delete()) {
// Successfully deleted foo and its nested folders
Folder::dirsize()
Return type:integer
Returns the size in bytes of this Folder and its contents.
Folder::errors()
Return type:array
Get the error from latest method.
Folder::find(string $regexpPattern = '.*', boolean $sort = false)
Return type:array
Returns an array of all matching files in the current directory:
// Find all .png in your app/webroot/img/ folder and sort the results
$dir = new Folder(WWW_ROOT . 'img');
$files = $dir-&find('.*\.png', true);
[0] =& cake.icon.png
[1] =& test-error-icon.png
[2] =& test-fail-icon.png
[3] =& test-pass-icon.png
[4] =& test-skip-icon.png
The folder find and findRecursive methods will only find files. If you
would like to get folders and files see
Folder::findRecursive(string $pattern = '.*', boolean $sort = false)
Return type:array
Returns an array of all matching files in and below the current directory:
// Recursively find files beginning with test or index
$dir = new Folder(WWW_ROOT);
$files = $dir-&findRecursive('(test|index).*');
[0] =& /var/www/cake/app/webroot/index.php
[1] =& /var/www/cake/app/webroot/test.php
[2] =& /var/www/cake/app/webroot/img/test-skip-icon.png
[3] =& /var/www/cake/app/webroot/img/test-fail-icon.png
[4] =& /var/www/cake/app/webroot/img/test-error-icon.png
[5] =& /var/www/cake/app/webroot/img/test-pass-icon.png
Folder::inCakePath(string $path = '')
Return type:boolean
Returns true if the file is in a given CakePath.
Folder::inPath(string $path = '', boolean $reverse = false)
Return type:boolean
Returns true if the file is in the given path:
$Folder = new Folder(WWW_ROOT);
$result = $Folder-&inPath(APP);
// $result = true, /var/www/example/app/ is in /var/www/example/app/webroot/
$result = $Folder-&inPath(WWW_ROOT . 'img' . DS, true);
// $result = true, /var/www/example/app/webroot/ is in /var/www/example/app/webroot/img/
static Folder::isAbsolute(string $path)
Return type:boolean
Returns true if the given $path is an absolute path.
static Folder::isSlashTerm(string $path)
Return type:boolean
Returns true if given $path ends in a slash (i.e. is slash-terminated):
$result = Folder::isSlashTerm('/my/test/path');
// $result = false
$result = Folder::isSlashTerm('/my/test/path/');
// $result = true
static Folder::isWindowsPath(string $path)
Return type:boolean
Returns true if the given $path is a Windows path.
Folder::messages()
Return type:array
Get the messages from the latest method.
Folder::move(array $options)
Return type:boolean
Move a directory (recursively by default). The only parameter $options is the same as for copy()
static Folder::normalizePath(string $path)
Return type:string
Returns a correct set of slashes for given $path (‘\’ for
Windows paths and ‘/’ for other paths).
Folder::pwd()
Return type:string
Return current path.
Folder::read(boolean $sort = true, array|boolean $exceptions = false, boolean $fullPath = false)
Return type:mixed
Parameters:
$sort (boolean) – If true will sort results.
$exceptions (mixed) – An array of files and folder names to ignore. If
true or ‘.’ this method will ignore hidden or dot files.
$fullPath (boolean) – If true will return results using absolute paths.
Returns an array of the contents of the current directory. The
returned array holds two sub arrays: One of directories and one of files:
$dir = new Folder(WWW_ROOT);
$files = $dir-&read(true, array('files', 'index.php'));
[0] =& Array // folders
[0] =& css
[1] =& img
[1] =& Array // files
[0] =& .htaccess
[1] =& favicon.ico
[2] =& test.php
Folder::realpath(string $path)
Return type:string
Get the real path (taking ”..” and such into account).
static Folder::slashTerm(string $path)
Return type:string
Returns $path with added terminating slash (corrected for
Windows or other OS).
Folder::tree(null|string $path = null, array|boolean $exceptions = true, null|string $type = null)
Return type:mixed
Returns an array of nested directories and files in each directory.
class File(string $path, boolean $create = false, integer $mode = 755)
// Create a new file with 0644 permissions
$file = new File('/path/to/file.php', true, 0644);
property File::$Folder
The Folder object of the file.
property File::$name
The name of the file with the extension. Differs from
which returns the name without the extension.
An array of file info. Use
property File::$handle
Holds the file handler resource if the file is opened.
property File::$lock
Enable locking for file reading and writing.
property File::$path
The current file’s absolute path.
File::append(string $data, boolean $force = false)
Return type:boolean
Append the given data string to the current file.
File::close()
Return type:boolean
Closes the current file if it is opened.
File::copy(string $dest, boolean $overwrite = true)
Return type:boolean
Copy the file to $dest.
File::create()
Return type:boolean
Creates the file.
File::delete()
Return type:boolean
Deletes the file.
File::executable()
Return type:boolean
Returns true if the file is executable.
File::exists()
Return type:boolean
Returns true if the file exists.
File::ext()
Return type:string
Returns the file extension.
File::Folder()
Return type:Folder
Returns the current folder.
File::group()
Return type:integer|false
Returns the file’s group, or false in case of an error.
Return type:array
Returns the file info.
Changed in version 2.1: File::info() now includes filesize & mimetype information.
File::lastAccess()
Return type:integer|false
Returns last access time, or false in case of an error.
File::lastChange()
Return type:integer|false
Returns last modified time, or false in case of an error.
File::md5(integer|boolean $maxsize = 5)
Return type:string
Get the MD5 Checksum of file with previous check of filesize,
or false in case of an error.
File::name()
Return type:string
Returns the file name without extension.
File::offset(integer|boolean $offset = false, integer $seek = 0)
Return type:mixed
Sets or gets the offset for the currently opened file.
File::open(string $mode = 'r', boolean $force = false)
Return type:boolean
Opens the current file with the given $mode.
File::owner()
Return type:integer
Returns the file’s owner.
File::perms()
Return type:string
Returns the “chmod” (permissions) of the file.
static File::prepare(string $data, boolean $forceWindows = false)
Return type:string
Prepares a ascii string for writing. Converts line endings to the
correct terminator for the current platform. For Windows “rn”
will be used, “n” for all other platforms.
File::pwd()
Return type:string
Returns the full path of the file.
File::read(string $bytes = false, string $mode = 'rb', boolean $force = false)
Return type:string|boolean
Return the contents of the current file as a string or return false on failure.
File::readable()
Return type:boolean
Returns true if the file is readable.
File::safe(string $name = null, string $ext = null)
Return type:string
Makes filename safe for saving.
File::size()
Return type:integer
Returns the filesize.
File::writable()
Return type:boolean
Returns true if the file is writable.
File::write(string $data, string $mode = 'w', boolean$force = false)
Return type:boolean
Write given data to the current file.
New in version 2.1: File::mime()
File::mime()
Return type:mixed
Get the file’s mimetype, returns false on failure.
File::replaceText($search, $replace)
Return type:boolean
Replaces text in a file. Returns false on failure and true on success.
New in version 2.5: File::replaceText()
Page contentsPHP手册 - 判断给定文件名是否是一个目录
在线手册:&
is_dir & 判断给定文件名是否是一个目录
bool is_dir
( string $filename
Note: 此函数的结果会被缓存。参见
以获得更多细节。
Example #1 is_dir() 例子
&?var_dump(is_dir('a_file.txt'))&.&"\n";var_dump(is_dir('bogus_dir/abc'))&.&"\n";var_dump(is_dir('..'));&//one&dir&up?&
以上例程会输出:
bool(false)
bool(false)
bool(true)
Tip自 PHP 5.0.0 起, 此函数也用于某些
URL 包装器。请参见 以获得支持
系列函数功能的包装器列表。
Path to the file. If filename is a relative
filename, it will be checked relative to the current working
directory. If filename is a symbolic or hard link
then the link will be resolved and checked. If you have enabled ,
restrictions may apply.
Returns TRUE if the filename exists and is a directory, FALSE
otherwise.
Example #2 is_dir() example
&?phpvar_dump(is_dir('a_file.txt'));var_dump(is_dir('bogus_dir/abc'));var_dump(is_dir('..'));&//one&dir&up?&
以上例程会输出:
bool(false)
bool(false)
bool(true)
失败时抛出E_WARNING警告.
Note: 此函数的结果会被缓存。参见
以获得更多细节。
Tip自 PHP 5.0.0 起, 此函数也用于某些
URL 包装器。请参见 以获得支持
系列函数功能的包装器列表。
- 改变目录
- Return an instance of the Directory class
- 打开目录句柄
- 判断给定文件名是否为一个正常的文件
- 判断给定文件名是否为一个符号连接
在线手册:&
PHP手册 - N: 判断给定文件名是否是一个目录
I encoutered an error returning false on a directory, my problem was not a bug, but a bad relative path error inside the script function is_dir(), maybe it can help someone having the same problem.
I am using Linux with the folowing structure:
/var/www//httpdocs/images/items_images/file1.jpg
/var/www//httpdocs/images/items_images/temp
$full_path = "/var/www//httpdocs/images/items_images";
if ($handle = opendir("$full_path")) {
&&& while (false !== ($file = readdir($handle))) {
&& & && if(is_dir($full_path."/".$file))
&& & && else echo $file;
$full_path = "/var/www//httpdocs/images/items_images";
if ($handle = opendir("$full_path")) {
&&& while (false !== ($file = readdir($handle))) {
&& & && if(is_dir($file))
&& & && else echo $file;
Just a note for anyone who encounters is_dir() returning false on CIFS mount points or directories within those mount points on 2.6.31 and newer kernels: Apparently in new kernels they've started using the CIFS serverino option by default.& With Windows shares this causes huge inode numbers and which apparently can cause is_dir() to return false.& Adding the noserverino option to the CIFS mount will prevent this.& This may only occur on 32 systems but I don't have a 64 bit install to test against.
When trying (no 'pear') to enumerate mounted drives on a win32& platform (Win XP SP3, Apache/2.2.11, PHP/5.2.9), I used:
function echo_win_drives() {
& for($c='A'; $c&='Z'; $c++)
&&& if(is_dir($c . ':'))
&& && echo $c . ': ';
which yielded:
A: C: D: E: F: G: H: I:
When I run a scandir I always run a simple filter to account for file system artifacts (especially from a simple ftp folder drop) and the "." ".." that shows up in every directory:
&&& if (is_dir($folder){
&& & && $contents = scandir($folder);
&& & && $bad = array(".", "..", ".DS_Store", "_notes", "Thumbs.db");
&& & && $files = array_diff($contents, $bad);
public static function isEmptyDir($dir){
&& & return (($files = @scandir($dir)) && count($files) &= 2);
An even better (PHP 5 only) alternative to "Davy Defaud's function":
function is_empty_dir($dir)
&&& if (($files = @scandir($dir)) && count($files) &= 2) {
&& & && return true;
&&& return false;
NOTE: you should obviously be checking beforehand if $dir is actually a directory, and that it is readable, as only relying on this you would assume that in both cases you have a non-empty readable directory.
@Anonymous:
If on Linux the suggested code does not work because '.' and '..' will allways be returned, it may be possible to subtract 2 from the amount of files found.
&&echo (count(glob("$dir/*") - 2) === 0) ? 'Empty' : 'Not
In that way, I think, you have solved the problem of two extra files that are counted.
Well, "John Doe's function" doesn't return the good value when $file != '.' && $file != '..' it must return false and not true !
Moreover, as the latest contributor told us, the directory have to be closed before returning.
function is_empty_dir($dir)
&&& if ($dh = @opendir($dir))
&& & && while ($file = readdir($dh))
&& & & & && if ($file != '.' && $file != '..') {
&& & & & & & && closedir($dh);
&& & & & & & && return false;
&& & & & && }
&& & && closedir($dh);
&& & && return true;
&&& else return false; }
On the previous example you may want to closedir() before returning, I tried the function and ran into some locking issues on windows when trying to delete the directory after I ran this function.
I altered the function below a bit. This implementation is simpler, faster and safer:
function is_empty_folder($folder) {
&&& if (! is_dir($folder))
&& & && return false; $files = opendir($folder);
&&& while ($file = readdir($files)) {
&& & && if ($file != '.' && $file != '..')
&& & && return true; }
I don't know much about implementation, however I think that passing through all the files is useless. This code returns false also in case that it's not even a folder plus it stops in three steps at most.
function is_empty_folder($folder){
&&& if(is_dir($folder) ){
&& & && $files = opendir($folder);
&& & && while ($file=readdir($files)){
&& & & & && $c++;
&& & & & && if ($c&2)
&& & & & & & & return false; }
&& & & & return true; }
&&& else return false; }
to check if folder is empty
function is_empty_folder($folder){
&&& if(is_dir($folder) ){
&& & && $files = opendir($folder);
&& & && while ($file=readdir($files)){$c++;}
&& & && if ($c&2){
&& & & & &&
&& & && }else{
&& & & & &&
&&& }& & & &
One note regarding checking for empty directories :
&&echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
This does not work correctly on Linux.
The '.' and '..' will always be returned even if no files are present in the directory.
Took a while to figure this out, but - DONT USE THIS IN A LOOP WITH READDIR()!& readdir() only gives the file/dir name and not the full path which is_dir apparently needs to be able to accurately evaluate the argument.
I had the same problem as others with not using the complete path to a folder when usin is_dir.
It's really important to use complete path.
$folder = "../pictures";
$dossier = opendir($folder);
while ($Fichier = readdir($dossier)) {
& if ($Fichier != "." && $Fichier != ".." && $Fichier != "Thumbs.db") {
//& & if(is_dir($Fichier)) { // Do not always works
&&& if(is_dir($folder."/".$Fichier)) { // Works always
echo "$Fichier";
&&& } // fin if is file
& } // fin if restriction des fichiers à ne pas afficher
} // fin while
closedir($dossier);
Running PHP 5.2.0 on Apache Windows, I had a problem (likely the same one as described by others) where is_dir returned a False for directories with certain permissions even though they were accessible.
Strangely, I was able to overcome the problem with a more complete path. For example, this only displays "Works" on subdirectories with particular permissions (in this directory about 1 out of 3):
$d = opendir("./albums/mydir");
while(false !== ($f = readdir($d))) {
&&& echo "&hr /&";
&& & && if(is_dir($f)) {
&& & & & && echo "&b&Works:" . $f . "&/b&";
However, this works properly for all directories:
$d = opendir("./albums/mydir");
while(false !== ($f = readdir($d))) {
&&& echo "&hr /&";
&& & && $dName = "./albums/mydir/" . $f;
&& & && if(is_dir($dName)) {
&& & & & && echo "&b&Works:" . $dName . "&/b&";
I don't understand the hit-and-miss of the first code, but maybe the second code can help others having this problem.
I had troubles at checking for the existance of a directory under the windows temporary path (usually c:\windows\temp\). I am using PHP 5.2.0
See also the bug tracker item:
Here below the replacement function which works under the Windows temporary directory. It is a bad hack, since it creates and then removes the directory to verify its existance! But I could not find an alternative solution, that bug should be fixed.
function temp_is_dir($dir) {
&&& if (!@mkdir($dir))
&& & && return true;
&&& rmdir($dir);
&&& return false;
As was said earlier by locataweb at hotmail dot com is_dir returns false on windows shares even if they exist and are accessible.
I found that is_readable provides about the same functionality and does return true. It might provide a sufficient replacement in most cases.
Here is another way to test if a directory is empty, which I think is much simpler than those posted below:
$dir = 'directory';
echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
Be aware that is_dir() and is_file() will not work on very large (for me &2gb) files (also see ).
You might try this approach - it works for me:
function isDir($dir) {
& $cwd = getcwd();
& $returnValue = false;
& if (@chdir($dir)) {
&&& chdir($cwd);
&&& $returnValue = true;
& return $returnValue;
Please keep in mind that isDir() will fail on directories which cannot be chdired due to permission settings for example.
Ah ha!& Maybe this is a bug, or limitation to be more precise, of php. See
A workaround is posted on the page (above) and seems to work for me:
function is_dir_LFS($path){
& return (('d'==substr(exec("ls -dl '$path'"),0,1))?(true):(false));
PS: I'm using PHP 4.3.10-16, posts report this problem up to 5.0
I'm not sure what is going on here... I have a function to return a listing of (sub)directories within a directory.& Works great until I ran into the directory given in the warning below... 87 characters seems too short to be running into a file/directory name length issue?
This is what I'm getting (though broken into a couple lines so this forum will accept it):
Warning: is_dir(): Stat failed for
/home/office/public_html/Library/1_NNHP-produced/4_Maps
/Peterson2003/BRTEreport_DVD.zip
(errno=75 - Value too large for defined data type) in /home/office/public_html/index.php on line 104
Here is line 104:
&if (is_dir($dir . "/" . $listing)) {
The function is_dir will always return false if the handle acquired with opendir is not from the current working directory (getcwd); exception applies to "." and "..". Thus, if you need a consistent dir listing from any directory other than the current one, you must change dir first. Example follows:
chdir( '..' );
$rep=opendir('.');
while (false != ($file = readdir($rep))){
& if (is_dir($file)){
&&& print("&a href='$file/' class='text1'&$file&/a&");
The above code will list all directories (with links) for the ".." directory, relative to the current working dir.
THE WRONG WAY TO DO IT FOLLOWS:
$rep=opendir('..');
while (false != ($file = readdir($rep))){
& if (is_dir($file)){
&&& print "&a href='$file/' class='text1'&$file&/a&&br&";
This code will turn into an empty list. If you want to make sure, uncomment the commented line...
Regards...
NOTE on Windows Shares (based on tests using PHP 5.1.1):
After many hours of head scratching and wondering why a script worked sometimes but not others, I discovered this revelation.
Be aware that base Windows shares are not recognised as dirs, so the following test will return false even if \\COMPUTER_NAME\SHARENAME exists.
if (is_dir('\\\\COMPUTER_NAME\\SHARENAME')) {
echo "TRUE\n";
echo "FALSE\n";
is_dir('\\\\COMPUTER_NAME\\SHARENAME\\SUBDIR') {
echo "TRUE\n";
echo "FALSE\n";
As a work round I replaced is_dir with is_readable() instead, which identifies if the share is readable and so must exist, but this is clearly dependent on whether the share is readable.
I hope this helps someone.& If there is a better work round or other purpose built solution to this problem with base windows shares, please post them so I'll know the next time.
regarding dmertens-php-note at zyprexia dot com's statement on 24-Sep-
Actually, is_dir is not affected by UID checks in safe_mode.& is_dir will even return true if you lack sufficient privileges to read said directory.
Remember that the owner of the directory has to be the same of the script user, otherwise this function will always return false when PHP is running in safe_mode..
I wrote an usefull function to check is directory exists in directory')
function dir_exists($dir_name = false, $path = './') {
&&& if(!$dir_name) return false;
&&& if(is_dir($path.$dir_name)) return true;
&&& $tree = glob($path.'*', GLOB_ONLYDIR);
&&& if($tree && count($tree)&0) {
&& & && foreach($tree as $dir)
&& & & & && if(dir_exists($dir_name, $dir.'/'))
&& & & & & & && return true;
&&& return false;
With error reporting set to all, and you attempt to do:
echo var_dump(is_dir('bogus_dir/abc'));
as output you will get:
Warning: stat failed for bogus_dir/abc (errno=2 - No such file or directory) in test.php on line 12
bool(false)
If you want to use this with an error reporting level set to all, you will need to use @ to supress the generated error
just a simple script to for those who dont have the IIS or Apache Dirlisting available , this will make onr for you
$DirPath=$_GET['DirPath'];
if($DirPath=="")
&&& $DirPath='./';
if (($handle=opendir($DirPath)))
&&& while ($node = readdir($handle))
&& & && $nodebase = basename($node);
&& & && if ($nodebase!="." && $nodebase!="..")
&& & & & && if(is_dir($DirPath.$node))
&& & & & && {
&& & & & & & && $nPath=$DirPath.$node."/";
&& & & & & & && echo "-& -& -& &a href='dir.php?DirPath=$nPath'&$node&/a&&br&";
&& & & & && }
&& & & & && else
&& & & & && {
&& & & & & & && echo "&a href='$node'&$node&/a&&br&";
&& & & & && }
Here goes a PHP5.0 link-to-directory listing function and examples
function list_dirs($path, $target)
&&& $list = scandir($path);
&&& foreach ($list as $number =& $filename)
&& & && if ( $filename !== '.' && $filename !== '..' && is_dir("$path/$filename") )
&& & & & && $dir = $filename;
&& & & & && $url = apache_request_headers();
&& & & & &&
&& & & & && if ($target == '')
&& & & & && {
&& & & & & & && print ("&a href=\"$url[Host]/$path/$dir\"&$dir&/a& &br&\n");
&& & & & && }
&& & & & && else
&& & & & && {
&& & & & & & && print ("&a href=\"$url[Host]$dir\" target=\"$target\"&$dir&/a& &br&\n");
&& & & & && }
&& & & & & & &&
1.- List current directory's directories with no target property.
list_dirs('.','')
2.- List "libraries" in "pma2" located at my dir with a "_blank" target set
list_dirs('pma2/libraries','_blank');
list_dirs('/var/www/html/pma2/libraries','_blank');
3.- List all the directories located at the "/Home" dir with "_me" as target.
list_dirs('/home', ''_me');
I hope you all like it!
Obviously, the links will now work if the're not in the apache dir... ("htdocs", "html", "www", whatever)
While working on a php project (my first one =( ).& I ran into a bug using is_dir() on my winxp w/ servicepack 2 system.& I'm using php 4.3.10.. the problem is whenever i pass is_dir() a pathname that is longer then 256 characters long it will ALWAYS return true.
$mpath = "E:\\armoury\\";
ls($mpath);
function ls ($curpath) {
&& $dir = dir($curpath);
&& echo("&b&$curpath&/b&");
&& echo "&blockquote&";
&& while ($file = $dir-&read()) {
&& & & & & & & & && echo(" &b&");
&& & & & & & & & && echo(strlen($curpath.$file));
&& & & & & & & & && echo("&/b& ");
&& & & & && if($file != "." && $file != "..") {
&& & & & & & && if (is_dir($curpath.$file)) {
&& & & & & & & & && ls($curpath.$file."\\");
&& & & & & & && } else {
&& & & & & & & & && echo(" $file&br&");
&& & & & & & && }
&& & & & && }
&& $dir-&close();
&& echo "&/blockquote&";
This is the output.. the number preceding the file/directory is the number of characters in it's full path name.& You can see where it trips up at:
&257 E:\armoury\[ hiphop - dub - reggae - soul ]\A Tribe Called Quest - 1990 - People's Instinctive Travels And The Paths Of Rhythm\A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 10 - Rhythm (Devoted To The Art Of Moving Butts).mp3
The pathname is greater then 256 characters.
229 A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 07 - Bonita Applebum.mp3
227 A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 08 - Can I Kick It.mp3
233 A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 09 - Youthful Expression.mp3
257 E:\armoury\[ hiphop - dub - reggae - soul ]\A Tribe Called Quest - 1990 - People's Instinctive Travels And The Paths Of Rhythm\A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 10 - Rhythm (Devoted To The Art Of Moving Butts).mp3\
259 260 267 E:\armoury\[ hiphop - dub - reggae - soul ]\A Tribe Called Quest - 1990 - People's Instinctive Travels And The Paths Of Rhythm\A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 10 - Rhythm (Devoted To The Art Of Moving Butts).mp3\index.php\
269 270 277 E:\armoury\[ hiphop - dub - reggae - soul ]\A Tribe Called Quest - 1990 - People's Instinctive Travels And The Paths Of Rhythm\A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 10 - Rhythm (Devoted To The Art Of Moving Butts).mp3\index.php\index.php\
Try it yourself on a large directory structure.
note: like the main example already shows. tooks me houres to understand und using chdir() to get a full dir scann (especilly on windows and "mounted" network drives)
never forget the tailing slash to find out if you have a directory or not.
function parse_dir($dir) {
&&& if ($dh = @opendir($dir)) {
&& & && while(($file = readdir($dh)) !== false) {
&& & & & && if( !preg_match('/^\./s', $file) )& {
&& & & & & & && if(is_dir($dir.$file)) {
&& & & & & & & & && $newdir = $dir.$file.'/'; chdir($newdir);
&& & & & & & & & && echo "IS DIR: $newdir\n";
&& & & & & & & & && echo parse_dir($newdir);
&& & & & & & && } else {
&& & & & & & & & && echo $dir.$file."\n";
&& & & & & & && }
&& & & & && }& & & & & &
&& & && chdir('..');
parse_dir('z:/myfolder/mysubfolder/');
this function bypasses open_basedir restrictions.
function my_is_dir($dir)
&&& // bypasses open_basedir restrictions of is_dir and fileperms
&&& $tmp_cmd = `ls -dl $dir`;
&&& $dir_flag = $tmp_cmd[0];
&&& if($dir_flag!="d")
&& & && // use next char (first char might be 's' and is still directory)
&& & && $dir_flag = $tmp_cmd[1];
&&& return ($dir_flag=="d");
echo is_dir("/somewhere/i/dont/have/access/to");
Warning: open_basedir restriction in effect
echo my_is_dir("/somewhere/i/dont/have/access/to");
true (or false, depending whether it is or not...)
visit puremango.co.uk for other such wonders
Unfortunately, the function posted by p dot marzec at bold-sg dot pl does not work.
The corrected version is:
// returns true if folder is empty or not existing
// false if folde is full
function is_empty_folder($dir) {
if (is_dir($dir)) {
&& $dl=opendir($dir);
&& if ($dl) {
&& & & while($name = readdir($dl)) {
&& if (!is_dir("$dir/$name")) { //&--- corrected here
&& & & closedir($dl);
use this function to get all files inside a directory (including subdirectories)
function scan_Dir($dir) {
&&& $arrfiles = array();
&&& if (is_dir($dir)) {
&& & && if ($handle = opendir($dir)) {
&& & & & && chdir($dir);
&& & & & && while (false !== ($file = readdir($handle))) {
&& & & & & & && if ($file != "." && $file != "..") {
&& & & & & & & & && if (is_dir($file)) {
&& & & & & & & & & & && $arr = scan_Dir($file);
&& & & & & & & & & & && foreach ($arr as $value) {
&& & & & & & & & & & & & && $arrfiles[] = $dir."/".$value;
&& & & & & & & & & & && }
&& & & & & & & & && } else {
&& & & & & & & & & & && $arrfiles[] = $dir."/".$file;
&& & & & & & & & && }
&& & & & & & && }
&& & & & && }
&& & & & && chdir("../");
&& & && closedir($handle);
&&& return $arrfiles;
This is the function that I use to test for an empty directory:
function is_emtpy_dir($dirname){
$result=false;& & & & & & & & & & & if(is_dir($dirname) ){
&& & & $result=true;& & & & & & & & && $handle = opendir($dirname);
&& & & while( ( $name = readdir($handle)) !== false){
&& & & & & & & if ($name!= "." && $name !=".."){
&& & & & & & $result=false;& & & & & & & & & & & & && }
&& & & closedir($handle);
&& return $result;
'Is_empty_folder' posted by andreas at rueping dot net is a nice function. It did give me some grief, though. I don't beleive that it actually closes the directory when it's done (closedir in the wrong spot). I changed it slightly to be the following:
// returns true if folder is empty or not existing
// false if folde is full
function is_emtpy_folder($folder){
&& if(is_dir($folder) ){
&& & & $handle = opendir($folder);
&& & & while( (gettype( $name = readdir($handle)) != "boolean")){
&& & & & & & & $name_array[] = $
&& & & foreach($name_array as $temp)
&& & & & & $folder_content .= $
&& & & closedir($handle);//&--------moved this
&& & & if($folder_content == "...") {
&& & & & &
&& & & } else {
&& & & & &
&& & & // folder doesnt exist
This is the "is_dir" function I use to solve the problems :
function Another_is_dir ($file)
&&& if ((fileperms("$file") & 0x4000) == 0x4000)
&& & && return TRUE;
&& & && return FALSE;
or, more simple :
function Another_is_dir ($file)
return ((fileperms("$file") & 0x4000) == 0x4000);
I can't remember where it comes from, but it works fine.
Simplest version 'is_empty_folder' posted by andreas at rueping dot net
// returns true if folder is empty or not existing
// false if folde is full
function is_empty_folder($dir) {
if (is_dir($dir)) {
&&& $dl=opendir($dir);
&&& if ($dl) {
&& & && while($name = readdir($dl)) {
&&& if (!is_dir($name)) {
&& & && closedir($dl);
function checks if a folder is empty or not. Retruns "true" if it is empty and "false" if it is full with data. Also if the folder doesnt even exist, function returns "true".
--------------------------------------------------
--------------------------------------------------
// returns true if folder is empty or not existing
// false if folde is full
function is_emtpy_folder($folder){
&&& if(is_dir($folder) ){
&& & && $handle = opendir($folder);
&& & && while( (gettype( $name = readdir($handle)) != "boolean")){
&& & & & & & && $name_array[] = $
&& & && foreach($name_array as $temp)
&& & & & && $folder_content .= $
&& & && if($folder_content == "...")
&& & & & &&
&& & && else
&& & & & &&
&& & && closedir($handle);
&& & && // folder doesnt exist

我要回帖

更多关于 os.path.isfile 的文章

 

随机推荐