Search code examples
phpunlinkfilemtime

Php delete all jpg but 20 newest


So.. I've been looking around, but not really found what I need, so here goes:

I got a webcam set to upload jpg's to a folder, but to avoid my server getting overflown with files, I want to clean out all jpg's but 20 newest when I load the page that shows the pictures. If the page loads, and there are only 20 jpg's in the folder, it should do nothing.


Solution

  • You could do something like this:

    1. Get last modified time of each file using filemtime($filename);
    2. Sort all filenames into an array based on this date.
    3. Delete all files except the first 20 using unlink()

    Some variations of what you need: 1, 2, 3