PHP - Create a Clean Cache Script (Simple!)
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I am creating images on the fly using PHP and storing them on a cache folder.
Whenever I request an image from the cache folder, I use the fileExists() function which includes a touch command to update the last access time.

This is my current code:

/**
 * @param string $imageKey
 * @param string $imageExtension
 * @return bool
 */
public static function fileExists($imageKey, $imageExtension){
    $filePath = self::getImagesCacheFolderPath() . $imageKey . ".". $imageExtension;
    if(file_exists($filePath)){
        //Update access time.
        touch($filePath);
        return true;
    };

    return false;
}

Please code a cleanCache() function which simply deletes all files in the cache folder that were not "touched" in the last X days, and that have extension "jpg,gif, png"

function cleanCache($pathToCacheFolder, $notAccessedInXDays){
 ... // IMPLEMENT THIS FUNCTION
}

This function will run every day on a cronjob.

  • Please ensure you test this function carefully. I don't want to delete other files by mistake and I am afraid of making a critical mistake. You can run exec() or a php loop. Whatever is most efficient and safe.
  • Ensure that the function has some security involved, such as checking that $pathToCacheFolder is not null, and thus command is not run.
  • Ensure only .jpg, .gif, and .png files are deleted.
awarded to alv-c
Tags
PHP

Crowdsource coding tasks.

2 Solutions


edit; here my solution to your other answer, will update it to include this one when i have time & you have accepted/bountied the other question.

[email]
<link rel="stylesheet" type="text/css" href="http://yoursite.com/base.css">

<img class="imageB" src="http://yoursite.com/image.php" width="50px" height="60px" />
<div class="imageA"></div>

<br/>
<br/>
<br/>
<br/>
l33th@x0r

<h1>Oh hai</h1>
[/email]

;

[base.css]
.imageA {
    background-image: url("http://yoursite.com/image.php?v1");

    width:50px;
    height:60px; 
    top:0px;
    left:0px;
    position:absolute;
} 

.imageB {
    top:0px;
    left:0px;
    position:absolute;
} 

body {
    background-color: lightblue;
}

h1 {
    color: navy;
    margin-left: 20px;
}
[/base.css]

;

[image.php] 
<?php

//base64 encoded binary of png file containing the letter A in white on black BG
$A = 'iVBORw0KGgoAAAANSUhEUgAAADIAAAA8CAIAAACrV36WAAACV0lEQVRoge2XIejqQBjAZUGGjL/NICIGEcMYRqNBxGAQ08KQBRGTmMxmg4iI0WAQ4zAsGETGMCyIGE0LQ0REhhwGGdsLB8dQ33P6Nn087pe2u++7++2+ufN8PgwGg8FgMBjMP4uiKJaN+Xz+bSOfL5lMWnfE43FXBifezuQ47r6xWq3+hYwbqKoKV2g6na7Xa3h9OBz8fv/XnDKZDCpcqVTKZrPolmXZr2kNh0MocTwe4fLIsgxbFovFd5xIktR1HUoMBgPYWCwW0YIlEokvaLEsiwzS6TRqR29bp9P5gpYoinD67XZrb2+1WjeV/RyhUOh6vcLp2+22vSsWixmGAbsefj48pNFooApms9mbXkmSYJckSR/VWq1WcGIAwH2lKpUKkk4mkx9yomkazSqK4n3Az8/P5XKBAd1u90Na7XYbadXr9Ycxk8kEBpxOJ5IkP6GladrTGhUKBRRTLpc9d7LvMKqq/i6MIIj9fg/DZFn2XGs0GlmvQ9O0h06BQOB8Pr+h1ev1PNTiOO4NJ8vrF382m72nZVkWz/OeOIXDYbSrGIYRiUSepkSjUZSyXC490Wo2m+jRnZ8j5vM5ymIYxn2tzWbzRkV4nkdZ/X7fZadUKoVGBwBQFOUwkaIoAABM1HU9EAg4n/T5ycf+pRYEAQDgcGgAgCAI8DoYDLr5H58giN1uh1Yrl8u9lJ7P51GuoiiuadnH1TSNIF47V948VSqVcpr45257BcfjsWmaL2mZpjkej9FtrVZ7Kf0x9nfWend3YxgGjXA+n53/YjAYDAaDwWD+D34BA1bn3VhhiaEAAAAASUVORK5CYII8YnIgLz4KPGI+V2FybmluZzwvYj46ICBpbWFnZWRlc3Ryb3koKSBleHBlY3RzIHBhcmFtZXRlciAxIHRvIGJlIHJlc291cmNlLCBzdHJpbmcgZ2l2ZW4gaW4gPGI+L2hvbWUvaGJlMDAyMzEvZG9tYWlucy9kYWtsYW5kLmJlL3B1YmxpY19odG1sL2Rldi9pbmRleC5waHA8L2I+IG9uIGxpbmUgPGI+MzQ8L2I+PGJyIC8+Cg==';

//base64 encoded binary of png file containing the letter B in white on black BG
$B = 'iVBORw0KGgoAAAANSUhEUgAAADIAAAA8CAIAAACrV36WAAAB10lEQVRoge2WMYvyMBjHc6GUDk7FIYM4iIOzFAdxdHJwEkc/gJ9ARMRJHMSP4FA6+RE6OImDg5OIQxEnkY6llJAWcsMdQe59OUzvooV7flOg/6f50TxNghAAAAAAAACgkrcHc5zz7wNxHEdR5Pv+6XTabDar1epyufzU7hEtKRhj0+nUMIxsaX2w3W51Xc+cFufctu0naf37FGNsGAYhpFarDQaD6/V6n280Gq/R+gIhxPO8Z3wwKS2EULfbFXmFv6SsVj6fF3lKqex0WN7wIRhjYhyGoWy5Kq37Nt/tdopmkW754/Eo8p1O52VamqaZpmlZ1mQyud1uIrxer1U5obTb6X6/N00zQ1qU0vl8nvpMVNXyGONKpWJZlqL3f5JuETnni8XiSVr/DWCMc7lcuVxut9uO4zDGRH42m71M6wv1ej0Igo98kiTVajUTWgih4XAoSpbLZVa0SqWSKPE8Lytauq6LkiiKpKZTtUEghAqFghjLntYKtXq9nhirunLJLmKz2aSUipLxePwyLU3TCCGtVsu27SRJRJ5SWiwWlWvJMhqNlDj9RMtxHIyVdXAKId/3+/1+uum03/KO4zgMwyAIzufz4XBwXdd13fsbPQAAAAAAwN/kHW2Ci4FDVaDXAAAAAElFTkSuQmCC';


//Check if we are cache busting using version strings
$explode = explode("?v",$_SERVER["REQUEST_URI"]);


//if version string available show letter B
if (isset($explode[1])) 
    $image = imagecreatefromstring(base64_decode($B));
//if version string unavailable show letter A
else
    $image = imagecreatefromstring(base64_decode($A));


header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);

?>
[/image.php]

So yeah i made a small edit to demonstrate my point; you can test the code most it easily by signing up at https://litmus.com/coupon/twittertrial (this link allows you to get screenshots of your html emails in lots of different email clients; my link allows for a 7 day trial without any creditcard details requirements); and just uploading base.css & image.php to your website; double check all paths. You will see a significant amount of widely used platforms display B while also quite a lot displaying A.

You could make it so that you serve a transparant 1px png if the other image already loaded (to save on bandwith) . Also when the external css based cache busting doesn't function you basically just fallback to the unpredictable ETAG/EXPIRE based php cachebusting approach as described by alv-c.

Note; it seems like in the html/CSS imageA & imageB are basically the opposite of my naming scheme in the php file; haven't had time to clean things up.

I dont really understand what you are trying to prove. Email support for css and background images? Also, I don't understand how this is related to this bounty. It is related to the other..
georgefountain 11 days ago
Winning solution

Here is my solution

http://pastebin.com/ENez3MSf

The code is commented so it's preatty easy to understand what it does, and change behaviour of it.

Edit:

final version

Hi Alv! Thanks for the fast reply. Question does touch() modify the last access time, last modification time, or both? Thank you! Should I keep using touch or remove it? My question is because I also need to do client side caching and if it also modifies last modified time, it might break it.. Please see related bounty: https://bountify.co/php-setting-the-correct-cache-headers-client-side-caching
georgefountain 18 days ago
Touch changes both access time and last modification time. To only change access time using touch you should call touch like this touch($filePath, date('U', filemtime($filePath)), time()). touch function takes three parameters, first one is file path, second is modified time and third is access time. If third parameter is not passed then second parameter is used to change both modified and access time. But what we do here is set the file modification time to the one it already had (using filemtime($filePath))
alv-c 18 days ago
And I think that touch call also solves your other bounty
alv-c 18 days ago
Hi Alv. I want to award you the bounty but your code is not working as expected. Found /cache/5ed182e02f895a3e9317430efec006a7962bf35c-350x182-YNY-0.png 2017-01-12 20:53:12 ext:png ;diff:0 For example, in this case last modification date is "2017-01-12 20:53:12 " and it says difference to NOW is 0.
georgefountain 11 days ago
There is some kind of bug. See more results: Found /cache/5ed182e02f895a3e9317430efec006a7962bf35c-350x182-YNY-0.png 2017-01-12 20:53:12 ext:png ;diff:0 <-- Difference 0??!!! Found /cache/image12diff2a.png 2017-01-18 11:42:43 ext:png ;diff:26 <-- Difference 26 days is correct.
georgefountain 11 days ago
Updated solution. Now it works correctly. My bad, previous version used $diff->d to check for days difference. Previous version calculates difference in days but separates days from months and years. let's say an image was 1 month and 2 days old. Then $diff->d returns 2. Now with $diff->format("%a") it returns the correct difference in days. As I said, I updated the solution with working code
alv-c 11 days ago
%a or just a?
georgefountain 11 days ago
Use %a . Just a will literally print a
alv-c 11 days ago
Thank you!!!
georgefountain 11 days ago
You're welcome, george!
alv-c 11 days ago
View Timeline