Search code examples
phpcodeignitererror-handlingcodeigniter-4

Getting error "CodeIgniter\Cache\Exceptions\CacheException Cache unable to write to ... " for a new Codeigniter 4 project


Almost always, when I am starting a Codeigniter 4 project, I am getting the following error:

"CodeIgniter\Cache\Exceptions\CacheException Cache unable to write to "/path/to/codeigniter-project/writable/cache/."

SYSTEMPATH/Cache/Handlers/FileHandler.php at line 61

which points at the below line:

throw CacheException::forUnableToWrite($this->path);

Cache Exception

What is the best way to solve this?


Solution

  • After doing a research, I've concluded into two options

    Option 1: The very quick way to just solve the above issue is to go to the command tool (e.g. terminal) and change the permissions of the folder to be writable and also to change the owner of the folder to be the one that is used from your server application. For example, I am using Apache and the user for apache is www-data:

    chmod -R 755 writable/ 
    chown -R www-data:www-data writable/
    

    or for macOS:

    chmod -R 755 writable/ 
    chown -R _www:_www writable/
    

    Pros:

    • A quick copy-paste solution
    • Those commands - most of the times - works out of the box
    • Even if you don't have access to command tool, you can change the permissions and ownership of the folder through FTP (e.g. through FileZilla UI interface)

    Cons:

    • You always need to add those commands into a new project
    • You may experience issues on development when you are trying to access the folder with your username

    Option 2 (suggested for local development): Add the www-data or _www (for macOS) to be at the same group role as your user.

    for Linux and Apache:

    sudo usermod -aG www-data your_username
    

    or for macOS and Apache:

    sudo dseditgroup -o edit -a your_username -t user _www
    

    If you are still getting the error also make sure that you have the folder as writable with the following command:

    chmod -R 755 writable/ 
    

    I don't know why but it may also need to do a restart of the Apache.

    Pros:

    • It works for new projects with no extra effort
    • You don't need to change the owner of the folder so you can have access to the folder for development
    • Once this change is available to the server or locally, you don't need to use sudo anymore if the chmod command is required

    Cons:

    • Not that safe for production environments (especially if you don't know what you are doing) since you would prefer to have specific users with specific roles rather than have users to have access everywhere
    • It requires more effort and it is not that straight forward for beginners
    • It needs more permissions to the server (e.g. sudo access)