0

假设我们有以下树列表:

www _
     \_sources_
      \        \_dir1
       \        \_dir2
        \        \_file
         \_cache

我正在尝试递归解析“源”中的每个文件并将其复制到保存层次结构的“缓存”文件夹中,但在我的函数中 mkdir() 创建一个文件而不是目录。在函数之外, mkdir() 可以正常工作。这是我的功能:

function extract_contents ($path)  {
    $handle = opendir($path);
    while ( false !== ($file = readdir($handle)) ) {
    if ( $file !== ".." && $file !== "." ) {
        $source_file = $path."/".$file;
        $cached_file = "cache/".$source_file;
        if ( !file_exists($cached_file) || ( is_file($source_file) && (filemtime($source_file) > filemtime($cached_file)) ) ) {
            file_put_contents($cached_file, preg_replace('/<[^>]+>/','',file_get_contents($source_file)) ); }
        if ( is_dir($source_file) ) {
#  Tried to save umask to set permissions directly – no effect
#           $old_umask = umask(0);
            mkdir( $cached_file/*,0777*/ );
            if ( !is_dir( $cached_file ) ) {
                echo "S = ".$source_file."<br/>"."C = ".$cached_file."<br/>"."Cannot create a directory within cache folder.<br/><br/>"; 
                exit;
                }
# Setting umask back
#           umask($old_umask); 
            extract_contents ($source_file);
            }              
        }
    }
    closedir($handle);
}
extract_contents("sources");

PHP 调试什么也没给我,但
[phpBB Debug] PHP Notice: in file /var/srv/shalala-tralala.com/www/script.php on line 88: mkdir() [function.mkdir]: ???? ?????????? 没有其他行包含 mkdir()。

ls -l cache/sources看起来
-rw-r--r-- 1 apache apache 8 Mar 31 08:46 file
-rw-r--r-- 1 apache apache 0 Mar 31 08:46 dir1
很明显,mkdir() 创建了一个目录,但它没有为它设置“d”标志。我就是不明白,为什么。因此,第一次,有人可以帮助并告诉我,如何通过 chmod() 通过八进制权限设置该标志,而我没有看到更好的解决方案?(我已经看过man 2 chmodand man 2 mkdir,没有关于“d”标志的内容)

另外:
通过将第二个 if 条件更改为来解决
if ( (!file_exists($cached_file) && is_file($source_file)) || ( is_file($source_file) && (filemtime($source_file) > filemtime($cached_file)) ) )

4

1 回答 1

4

你正在使用这个:

file_put_contents($cached_file, preg_replace('/<[^>]+>/','',file_get_contents($source_file)) ); }

会创建一个名为$cached_file.


然后,调用它:

mkdir( $cached_file/*,0777*/ );

在那里,您尝试创建一个名为$cached_file.

但是已经有一个具有该名称的现有文件。
意思是 :

  • mkdir失败,因为有一个具有该名称的文件
  • 你有一个文件,你之前用file_put_contents.



在评论后编辑:作为测试,我将尝试创建一个文件和一个同名目录——使用命令行而不是 PHP,以确保 PHP 对此没有任何影响。

首先让我们创建一个文件:

squale@shark: ~/developpement/tests/temp/plop 
$ echo "file" > a.txt
squale@shark: ~/developpement/tests/temp/plop 
$ ls
a.txt

而且,现在,我尝试创建一个具有相同名称的目录a.txt

squale@shark: ~/developpement/tests/temp/plop 
$ mkdir a.txt
mkdir: impossible de créer le répertoire «a.txt»: Le fichier existe

错误消息(对不起,我的系统是法语)“不可能创建目录 a.txt:文件已经存在”

那么,您确定可以创建一个与现有文件同名的目录吗?

于 2011-03-31T05:38:28.397 回答