PHP删除2个文件夹中超过x天的所有文件

时间:2014-03-11 04:58:38

标签: php

我想使用此代码删除2个文件夹中超过x天的所有文件但我收到错误:

  

PHP Parse错误:语法错误,第6行的E:\ home \ ca \ web \ cm \ cache.php中的意外T_PUBLIC

为什么?

<?php
$pastas = array("gallery-images/","resources/cache/");
foreach($pastas as $pasta){
   $this->deleteFrom($pasta);
}
public function deleteFrom($path){
$expiretime=10080; //expire time in minutes, 7 days = 7*24*60

$tmpFolder=$path.'/';
$fileTypes="*.*";

foreach (glob($tmpFolder . $fileTypes) as $Filename) {

// Read file creation time
$FileCreationTime = filectime($Filename);

// Calculate file age in seconds
$FileAge = time() - $FileCreationTime;

// Is the file older than the given time span?
if ($FileAge > ($expiretime * 0)){

// Now do something with the olders files...

echo "The file $Filename is older than $expiretime minutes\n";

//delete files:
unlink($Filename);
}

}
}
?>

3 个答案:

答案 0 :(得分:0)

您的函数定义不在类中,因此您需要删除PUBLIC

public function deleteFrom($path){

function deleteFrom($path){

同样$this->不正确您需要删除它们并将该函数称为

deleteFrom($pasta);

在此处查看PHP中如何使用Public,Private等 http://php.net/manual/en/language.oop5.visibility.php

答案 1 :(得分:0)

这是因为这里没有使用类,所以不需要使用$this来调用您的函数只需使用deleteFrom(),请参阅下面的代码

foreach($pastas as $pasta){
   deleteFrom($pasta);
}

答案 2 :(得分:0)

如果你想使用一个类,你可以这样写:

$pastas = array("gallery-images/", "resources/cache/");

$File = new File();
foreach ($pastas as $pasta)
{
   $File->deleteFrom($pasta);
}

class File
{
  public function deleteFrom($path)
  {
    $expiretime=10080; //expire time in minutes, 7 days = 7*24*60

    $tmpFolder=$path.'/';
    $fileTypes="*.*";

    foreach (glob($tmpFolder . $fileTypes) as $Filename)
    {
      // Read file creation time
      $FileCreationTime = filectime($Filename);

      // Calculate file age in seconds
      $FileAge = time() - $FileCreationTime;

      // Is the file older than the given time span?
      if ($FileAge > ($expiretime * 0))
      {
        // Now do something with the olders files...
        echo "The file $Filename is older than $expiretime minutes\n";

        //delete files:
        unlink($Filename);
      }
    }
  }
}