Delete all files inside a folder but the last by time?
<p>I have asked the same question before and I found this solution :</p>

<pre><code>if ($handle = opendir('/path/to/your/folder')) 
{
$files = array();
while (false !== ($file = readdir($handle))) 
{
    if (!is_dir($file))
    {
        // You'll want to check the return value here rather than just blindly adding to the array
        $files[$file] = filemtime($file);
    }
}

// Now sort by timestamp (just an integer) from oldest to newest
asort($files, SORT_NUMERIC);

// Loop over all but the 5 newest files and delete them
// Only need the array keys (filenames) since we don't care about timestamps now as the array will be in order
$files = array_keys($files);
for ($i = 0; $i &lt; (count($files) - 5); $i++)
{
    // You'll probably want to check the return value of this too
    unlink($files[$i]);
}
}
</code></pre>

<p>And I have edited to fit my needs like this:</p>

<pre><code>public function cleanup() {
    $files = glob("$this-&gt;location/*.sql");
    $count = count($files);
    if($count &gt;= $this-&gt;maxbackups) {
        $timestamps = array();
        foreach( $files as $value) {
            $timestamps[$value] = filemtime($value);
        }
        asort($timestamps, SORT_NUMERIC);
        $timestamps = array_keys($timestamps);
        for ($i = 0; $i &lt; (count($timestamps) - 1); $i++) {
            unlink($timestamps[$i]);
        }
            return $this-&gt;message-&gt;error(false,'Backups successfuly cleaned');
        } else {
            return $this-&gt;message-&gt;error(true,'Backups could not be cleaned');
        }
}
</code></pre>

<p>But the problem is that it deletes all files but the first, not the last created, why is that ?</p>
