【问题标题】:Multiple file checking with php and create the file if does not exist使用php检查多个文件,如果不存在则创建文件
【发布时间】:2013-05-20 05:17:53
【问题描述】:

我有一个 php 脚本来检查这 5 个文件是否存在 文件1、文件2、文件3、文件4、文件5的顺序

如果 file1 存在则检查 file2 如果 file2 存在,则检查 file3 如果 file3 存在,则检查 file4 如果 file4 存在则检查 file5

如果任何文件不存在,则创建该文件,如果所有文件都存在,则休眠几秒钟,直到其中一个文件被删除,然后在执行代码之前创建该文件

我的逻辑很清楚,但我无法将代码付诸实施

下面是我的代码

while(file_exists("/var/tmp/test/" . $tempfile) && file_exists("/var/tmp/test/" . $tempfile2) && file_exists("/var/tmp/test/" . $tempfile3) && file_exists("/var/tmp/test/" . $tempfile4) && file_exists("/var/tmp/test/" . $tempfile5))
{
    sleep (3);
}

if file 1 exist
{
    if file 2
    {
        if file 3
        {
            if file 4
            {   
                create file 5
            }
            else
            {
                create file 4
            }
        }
        else
        {
            create file 1
        }
    }
    else
    {
        create file 1
    }
}
else
{
    create file 1
}

有没有更好的写法?

【问题讨论】:

  • 也许您应该准确解释您要完成的工作。我怀疑任何使用sleep() 的解决方案。
  • @Jonathon Reinhart:否则,您将如何等待来自第三方资源的某些数据?
  • @zerkms Well 目录通知,Windows 上的 FindFirstChangeNotification 或 Linux 上的 inotify 可能是理想的,但对于这个脚本来说可能是多余的。我并不是说sleep 无论如何都是错误的,但它至少总是值得再看一遍。
  • 我正在尝试将文件传递到我的服务器进行处理,但我不希望它在任何给定时间处理超过 5 个文件。

标签: php


【解决方案1】:
$files = array('f1', 'f2', ...);
while (true) {
    foreach ($files as $file) {
        if (!file_exists($file)) {
            break 2;
        }
    }

    sleep(3);
}

touch($file);

【讨论】:

  • 不会是 break 3 来突破 if、foreach 和 while 语句吗?
  • @user2280769: breakcontinue 专门用于循环结构
猜你喜欢
  • 2014-01-02
  • 2022-01-11
  • 1970-01-01
  • 2016-06-18
  • 2012-05-10
  • 2012-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多