[英]PHP Delete all files older than x days in 2 folders
我正在嘗試使用此代碼刪除2個文件夾中所有超過x天的文件,但出現錯誤:
PHP解析錯誤:語法錯誤,第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);
}
}
}
?>
您的函數定義不在類中,因此您需要刪除PUBLIC
public function deleteFrom($path){
至
function deleteFrom($path){
另外$this->
是不正確的,您需要刪除它們並以
deleteFrom($pasta);
檢查此處如何在PHP中使用“公共”,“私人”等http://php.net/manual/zh/language.oop5.visibility.php
這是因為這里沒有使用class,所以不需要使用$this
來調用函數,只需使用deleteFrom()
請參見下面的代碼
foreach($pastas as $pasta){
deleteFrom($pasta);
}
如果要使用一個類,可以編寫如下內容:
$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);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.