phpserveropcache

How do I keep the most recent OPcache folder only?


I'm new to using OPcache on php 8 and I have some questions. So my folder structure looks like this:

https://i.sstatic.net/vb93u.png

Within each folder is the exact same thing, it's the structure of my website.

  1. Why does OPcache generate multiple folders with the same content?
  2. What is the best way to keep only the most recent folder and delete the others? Is there a check that can be done every so often or a setting that overwrites older files with new ones?

I'm fast approaching the file limit with my hosting and need to clear up some space.

I've read the docs but I don't have a lot of knowledge working with servers so any help is greatly appreciated!

Oh and these are the settings in my php.ini:

zend_extension=opcache.so;
opcache.enable=1;
opcache.memory_consumption=32;
opcache.interned_strings_buffer=8;
opcache.max_accelerated_files=3000;
opcache.revalidate_freq=180;
opcache.fast_shutdown=0;
opcache.enable_cli=0;
opcache.revalidate_path=0;
opcache.validate_timestamps=1;
opcache.max_file_size=0;
opcache.file_cache=/mywebsitepath/.opcache;
opcache.file_cache_only=1;

Solution

  • Just in case anyone else has the same problem, this is what I ended up doing. First I tried to use the Wordpress cron manager but I was having issues getting a simple function to work. Instead, in my hosting you can create a cron job and link it to a php file, so I went that route instead. Here's the contents of the cron-jobs.php file which I put in my OPcache folder. Basically it sorts the folders by date modified then deletes the old ones while keeping the fresh one. If anyone has suggestions for improvements, be my guest!

    function opcache_clean($dir) {
        $folders = array();
    
        foreach (scandir($dir) as $file) {
            //we only want the folders, not files
            if ( strpos($file, '.') === false ) {
                $folders[$file] = filemtime($dir . '/' . $file);
            }
        }
        
        //only delete the old folders if there is more than one
        if (count($folders) > 1) {
            arsort($folders);
            $folders = array_keys($folders);
            //keep the first folder (most recent directory at index 0)
            $deletions = array_slice($folders, 1);
            
            foreach($deletions as $delete) {
                echo "deleting $delete <br>";
                system("rm -rf ".escapeshellarg($delete));
            }
        }
        else {
            echo "No folders to delete!";
        }
    }
    
    //clean the current directory
    opcache_clean ( dirname(__FILE__) );