Jump to content

[SOLVED] Get list of files that created befor the current month


FD_F

Recommended Posts

i have log class and i need add function that zip files in the dir before the current month

 

the files saved in the format: 08.17.09.log

 

any guidelines how list all the files names  month before 08.17.09  ?

 

mean time i took the list of the files in the dir

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
	 if (($file != '.') && ($file != '..')) 
          
	   $FileToZip[] =  basename($file, ".log");
        }
        closedir($dh);
    }
}

Easier to use glob() if you're using PHP 5:

 

<?php
$FileToZip = array();
foreach (glob("$dir/*.log") as $path) {
list($m, $d, $y) = explode('.', basename($path, '.log'));
$stamp = strtotime("$y-$m-$d");
//if it's a past year or if it's this year and a past month, add the path to $FileToZip
if ((int) date('Y', $stamp) < (int) date('Y') || (date('Y', $stamp) == date('Y') && (int) date('m', $stamp) < (int) date('m'))) {
	$FileToZip[] = $path;
}
}
?>

 

If $dir has a trailing slash, just remove the one I put in the glob() parameter.

And I just realized we can optimize it by not creating a timestamp:

 

<?php
$FileToZip = array();
foreach (glob("$dir/*.log") as $path) {
list($m, $d, $y) = explode('.', basename($path, '.log'));
$y = (int) $y < 70 ? (int) "20$y" : (int) "19$y";
//if it's a past year or if it's this year and a past month, add the path to $FileToZip
if ($y < (int) date('Y') || ($y == (int) date('Y') && (int) $m < (int) date('m'))) {
	$FileToZip[] = $path;
}
}
?>

thanks works perfect (until year 3000 :))

 

How do you reckon you even could differentiate between 2009 and 2109, with those filenames? ;)

 

can you explain what  :    means in  (int) "20$y" : (int) "19$y"  ?

 

It's a ternary operator.

 

$y = (int) $y < 70 ? (int) "20$y" : (int) "19$y";

or in general

 

$variable = condition ? if true : if false

 

is the same as

 

if ((int) $y < 70) {
$y = (int) "20$y";
} else {
$y = (int) "19$y";
}

BTW, I'm doing that to simulate the strtotime() behavior, where two digit years between 00 and 69 are assumed to be in 2000, and two digit years between 70 and 99 are assumed to be in 1900.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.