【问题标题】:comparing two unix time files to delete old files比较两个unix时间文件以删除旧文件
【发布时间】:2011-03-20 23:02:28
【问题描述】:

我正在使用下面的代码来获取我的云服务器上的文件timestamps,然后删除任何超过一定年龄的文件。

目前,代码设置为删除任何超过 10 分钟的内容以进行测试。

但是它会删除所有内容,即使我上传了一些文件然后在 10 秒后运行脚本。

是否有一些我没有看到的小问题?

    $auth->authenticate();

    //connect
    $conn = new CF_Connection($auth);

    //create a handle for the CLOUD FILES container we want to delete from
    $daily_dose = $conn->get_container('daily_dose');

    //delete the obeject 
    $daily_packages = $daily_dose->list_objects();
    //print_r($daily_packages);
    //$public_container = $conn->get_container("public");   

    //$file_age = 86400; // 1 day in seconds
    $file_age = 600; // 10 minutes

    echo 'current time: ';
    echo $current_time = time();
    echo '<br>';
    echo 'time offset: ';
    echo $previous_day = $current_time - $file_age;
    echo '<br>';

    foreach($daily_packages as $package)
    {   
        echo $item = $daily_dose->get_object($package);
        $modified = $item->last_modified;
        echo ' ' . $modified;
        echo ' -> ' . strtotime($modified);
        echo '<br>';

        //If the modified time of the file is less the current time - 1 day in seconds (older than 1 day) delete it
        if ( $modified < $previous_day )
        {
            //delete the file
            $daily_dose->delete_object($item);
        }
    }

【问题讨论】:

  • 你能不能把echo的内容也包括在内,这对我们也很有用。
  • $item-&gt;last_modified 中到底是什么?事实上,它是与time() 返回的时间戳相同吗?假设您对代码进行更多检测:echo ' ' . $modified . ' -&gt; ' . strtotime($modified) . '; comparing ' . $modified . ' with ' . $previous_day . ' =&gt; ' . ($modified &lt; $previous_day) . &lt;br&gt;; 或类似的东西;输出亮了吗?
  • last_modified 是一个类变量,它将返回类似Sun, 20 Mar 2011 23:09:36 GMT 的内容,然后我将其转换为timestamps

标签: php datetime timestamp unix-timestamp


【解决方案1】:

如果您在 $modified 上调用 strtotime(),我猜它已经不是 UNIX 时间戳了。 time() 确实返回一个 UNIX 时间戳。

那么,检查不应该如下:

if(strtotime($modified) < $previous_day)

这样您就可以比较 UNIX 时间戳,并且鉴于 $item->last_modified 返回正确的值,您的代码应该可以工作。

如果不是,请确保 time() 返回的时间和软件在 $items 上设置 last_modified 值之间没有时间或时区差异(通过一些调试输出很容易检查)

【讨论】:

  • 在您对自己问题的评论中,您指出“last_modified 是一个类变量,它将返回类似于 Sun,2011 年 3 月 20 日 23:09:36 GMT”的内容,所以我确信您将不得不现在改变你的“如果”条件。但是确保没有时区差异总是好的:)
  • 谢谢威尔,两者都是。我只是输出了$modifiedtimestamp,没有将它放入变量中并进行比较,我的云服务器在伦敦时间,我的 PHP 服务器在丹佛时间,现在可以完美运行了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多