Search code examples
phpfunctionvariablesreturnunlink

Pass variable from within PHP function


I'd like to report how many files get deleted from a function that I'm running within php via a cron task.

Current codes is as follows:-

<?php

function deleteAll($dir) {
    $counter = 0;
    foreach(glob($dir . '/*') as $file) {
        if(is_dir($file)) {
            deleteAll($file); }
        else {
            if(is_file($file)){
// check if file older than 14 days
                if((time() - filemtime($file)) > (60 * 60 * 24 * 14)) {
                    $counter = $counter + 1;
                    unlink($file);
                } 
            }
        }
    }
}   

deleteAll("directory_name");

// Write to log file to confirm completed
$fp = fopen("logthis.txt", "a");
fwrite($fp, $counter." files deleted."."\n");
fclose($fp);

?>

That makes sense to me with a VBA background, but the counter returns null I think when written to my custom log file at the end. I presume there is some restriction on a shared hosting site of being able to declare the variable globally or similar?

Appreciate any help! It's not the end of world if I can't count the deleted files, but it would be nice to log the output in the format I've chosen.


Solution

  • This doesnt work due to scopes. In your example $counter only exists inside your function.

    function deleteAll($dir):int {
        $counter = 0; // start with zero
        /* Some code here */
        if(is_dir($file)) {
            $counter += deleteAll($file); // also increase with the recursive amount
        }
        /* Some more code here */
        return $counter; // return the counter (at the end of the function
    }
    
    $filesRemoved = deleteAll("directory_name");
    

    Alternatively, if you want to send back more info, eg 'totalCheck' etc, you can send back an array of info:

    function deleteAll($dir):array {
        // All code here
        return [
            'counter' => $counter,
            'totalFiles' => $allFilesCount
        ];
    }
    $removalStats = deleteAll("directory_name");
    echo $removalStats['counter'].'files removed, total: '.$removalStats['totalFiles'];
    

    There are other solutions like 'pass-by-reference', but you dont want those.