PHP script to delete old files from CDN

At present our APIs do not support a query based on the date of creation. To delete the old files it is necessary to request the list using the “ls” command and then compare the creation date with the current date.

header("Content-Type: text/plain"); 


// First i get the files from the CDN 
// to create a for loop and check the save dates. 

$data = array("apikey" => $APIKEY, 
              "cmd" => "ls",
              "beauty" => "true");

$curl = curl_init("");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 

$output = curl_exec($curl);  


echo $output;

$files = json_decode($output, true);

$now = new DateTime('now');

// I want to delete only files older than 60 days.
$older_than = 60;

foreach ($files['resources'] as $resource) {
    $d        = explode("T", $resource["creationDate"]);
    $datetime = DateTime::createFromFormat('Y-m-d', $d[0]);        
    $interval = $datetime->diff($now);
    if ($interval->format('%R%a') > $older_than) {
        echo $resource["UID"];
        echo "\n";
        echo file_get_contents("" . $resource["UID"] . "/?apikey=" . $APIKEY . "&cmd=del"  );
        echo "\n";
        echo "\n";    

Leave a Comment

Your email address will not be published. Required fields are marked *