2011-03-31 136 views
0

假设我们有以下的树形列表:MKDIR创建一个文件,而不是目录

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 chmodman 2 mkdir,没有什么关于 “d” 标志)

另外:
由changind解决的第二个,如果条件
if ((!file_exists($cached_file) && is_file($source_file)) || (is_file($source_file) && (filemtime($source_file) > filemtime($cached_file))))

回答

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对此没有任何影响。

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

[email protected]: ~/developpement/tests/temp/plop 
$ echo "file" > a.txt 
[email protected]: ~/developpement/tests/temp/plop 
$ ls 
a.txt 

而且,现在,我尝试用相同的名字a.txt创建一个目录:

[email protected]: ~/developpement/tests/temp/plop 
$ mkdir a.txt 
mkdir: impossible de créer le répertoire «a.txt»: Le fichier existe 

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

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

+0

当mkdir失败时,它不会创建任何内容。但它会创建一个文件。在相同的目录中有一个文件和一个名称相同的文件夹没有问题。另外,该脚本现在停止在目录上,该目录在其自身附近没有具有相同名称的文件。正如我上面写的,我试图在函数外创建一个具有相同名称的目录,并且它可以工作。但它没有显示,但我是一个白痴。 – tijagi 2011-03-31 05:51:46

+0

对不起,你当然是对的。不能有一个文件和一个同名的目录。我只有像“abc.def”这样的文件和对应于它们的文件夹“abc”,这些文件都可以工作。看起来,你也是对的,这是file_put_contents生成一个以前的mkdir文件试图做到这一点。通过增加一个条件,它现在可以正常工作。谢谢! – tijagi 2011-03-31 06:50:09

+0

不客气:-)玩得开心! – 2011-03-31 07:06:04

相关问题