【问题标题】:PHP file_exists but rename fails "No such file or directory..."? [closed]PHP file_exists 但重命名失败“没有这样的文件或目录......”? [关闭]
【发布时间】:2013-01-02 18:47:04
【问题描述】:

考虑到有问题的文件的创建有点落后于有问题的函数,我尝试运行一个 while 循环以在调用重命名之前争取一点时间。

$no_file = 1;   
while($no_file && $no_file < 300)
{   // generation of Worksheet.xls may lag behind function -- WAIT FOR IT
    if(file_exists($old_path))
    {   $no_file = 0;
        rename($old_path, $new_path);
    }   else $no_file++;
}
if($no_file) die("Error: Worksheet.xls not found");

在这种配置中,我认为 rename() 只能在 file_exists() 返回 true 时调用,但对于我来说,我无法弄清楚 rename() 是如何/为什么被调用然后返回失败...

PHP 警告: 重命名(C:\wamp\www\demox/wp-content/plugins/cat-man/store-manager/summary/worksheets/Worksheet.xls,C:\wamp\www\demox/wp-content/plugins/cat- man/store-manager/summary/statements/TESTING/2012/Worksheet.xls) 没有这样的文件或目录...

【问题讨论】:

  • 我不确定这是否能解决问题,但请尝试用 DIRECTORY_SEPARATOR 常量替换正斜杠。

标签: php rename file-exists


【解决方案1】:

它可能告诉你statements/TESTING/2012/ 不存在。使用mkdir() 创建这些目录,以便保存文件。

mkdir( 'C:\wamp\www\demox/wp-content/plugins/cat-man/store-manager/summary/statements/TESTING/2012/', 777, true);

【讨论】:

  • 感谢您的跟进!奇怪......有时它有效......有时它没有,首先创建目录似乎只会使事情变得更加复杂。我刚刚在某个地方读到过(现在找不到哪里)关于在打开文件后在 Windows 平台上重命名的问题...阅读...在给定的会话中重命名过?我得做更多的挖掘工作。
【解决方案2】:

无论多么遥远,此代码都可能会出现竞争条件,您的文件可能会在检查它是否存在和尝试重命名它之间发生变化。最好从try/catch 块中立即尝试重命名并直接处理失败。

您应该在重命名后使用break 语句显式退出循环。在重命名之前设置$no_file = 0;是过早地庆祝胜利。

另外,如果你是为了延迟而循环,你需要休眠执行,否则循环将在 PHP 可以处理的最快速度完成。看看time_nanosleep。如果您对 while 循环计时,您会看到它非常非常快地完成:

$time_start = microtime(true);
$x = 0;
while ($x < 300) {
    file_exists("index.php");
    $x++;
}
echo sprintf("300 loops in %.9f seconds", microtime(true) - $time_start);

// 300 loops in 0.000626087 seconds

【讨论】:

    【解决方案3】:

    好的,mkdir() 确实解决了问题!这是上下文中的解决方案。

    $old_path = $smry_dir."worksheets/Worksheet.xls";
    if(@$store_options->paypal_live ==='false')
    {   $new_path = $smry_dir."statements/TESTING/$reporting_year";
    }   else $new_path = $smry_dir."statements/$reporting_year";
    if(!is_dir($new_path)) mkdir($new_path, 777, true);
    rename($old_path, $new_path."/Worksheet.xls");
    

    再次感谢大家的帮助!语句 DIR 始终存在,我发现虽然 rename() 会毫无怨言地写入单个新子目录 $reporting_year,但它不会/不能写入递归子目录“TESTING/$reporting_year”。

    mkdir 的递归参数救援!

    【讨论】:

      猜你喜欢
      • 2021-07-01
      • 2018-09-14
      • 1970-01-01
      • 2013-01-13
      • 2021-05-13
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      • 2013-08-29
      相关资源
      最近更新 更多