3

以下のコードは、フォルダー「 Images 」内のファイルを60秒ごとに削除しますが、機能しますが、フォルダーが空の場合、次のように表示されます。その警告の代わりに「フォルダが空です..

<?php
$expiretime=1; 

$tmpFolder="Images/";
$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 * 60)){

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

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

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

}
?>
4

1 に答える 1

8

glob() は空の一致に対して空の配列を確実に返さない可能性があるため (ドキュメントの Return セクションの「注」を参照)if 、次のようにループを保護するステートメントが必要です。

$files = glob($tmpFolder . $fileTypes);
if (is_array($files) && count($files) > 0) {
    foreach($files 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 * 60)){

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

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

        //delete files:
        unlink($Filename);
    }
} else {
    echo 'Your error here...';
}
于 2012-07-07T20:08:30.500 に答える