{"record":{"id":"e35e0a39dc94519b","repo":"twigphp/Twig","slug":"unable-to-create-the-cache-directory-s","errorCode":null,"errorMessage":"Unable to create the cache directory (%s).","messagePattern":"Unable to create the cache directory \\((.+?)\\)\\.","errorType":"exception","errorClass":"RuntimeException","httpStatus":null,"severity":"error","filePath":"src/Cache/FilesystemCache.php","lineNumber":53,"sourceCode":"\n        return $this->directory.$hash[0].$hash[1].'/'.$hash.'.php';\n    }\n\n    public function load(string $key): void\n    {\n        if (is_file($key)) {\n            @include_once $key;\n        }\n    }\n\n    public function write(string $key, string $content): void\n    {\n        $dir = \\dirname($key);\n        if (!is_dir($dir)) {\n            if (false === @mkdir($dir, 0777, true)) {\n                clearstatcache(true, $dir);\n                if (!is_dir($dir)) {\n                    throw new \\RuntimeException(\\sprintf('Unable to create the cache directory (%s).', $dir));\n                }\n            }\n        } elseif (!is_writable($dir)) {\n            throw new \\RuntimeException(\\sprintf('Unable to write in the cache directory (%s).', $dir));\n        }\n\n        $tmpFile = tempnam($dir, basename($key));\n        if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $key)) {\n            @chmod($key, 0666 & ~umask());\n\n            if (self::FORCE_BYTECODE_INVALIDATION == ($this->options & self::FORCE_BYTECODE_INVALIDATION)) {\n                // Compile cached file into bytecode cache\n                if (\\function_exists('opcache_invalidate') && filter_var(\\ini_get('opcache.enable'), \\FILTER_VALIDATE_BOOLEAN)) {\n                    @opcache_invalidate($key, true);\n                } elseif (\\function_exists('apc_compile_file')) {\n                    apc_compile_file($key);\n                }\n            }","sourceCodeStart":35,"sourceCodeEnd":71,"githubUrl":"https://github.com/twigphp/Twig/blob/a414c3a491defb5a60f2fc88ef79ff37c90010cd/src/Cache/FilesystemCache.php#L35-L71","documentation":"FilesystemCache::write() creates the cache directory with @mkdir if it is missing. If mkdir fails (and the directory still doesn't exist afterward), it means filesystem-level permission or path problems, so Twig throws this RuntimeException because compiled templates cannot be stored.","triggerScenarios":"Calling $env->setCache('/path') (FilesystemCache) and then rendering; the dirname of the cache key path cannot be created because a parent directory is missing/unwritable, the filesystem is read-only, or a non-directory file exists at that path. Also triggered when mkdir races and fails and the dir truly is absent.","commonSituations":"Deployed containers running the PHP process as a non-root user without write access to the cache path; read-only filesystems (Docker images, serverless /var restrictions); typoed cache path like /var/cache/twig where /var/cache/twig is actually a file; disk full.","solutions":["Create the cache directory manually and give the PHP user write access: mkdir -p <dir> && chown www-data:www-data <dir>.","Verify the cache path in setCache() points to a writable location and is not occupied by a regular file.","Check for read-only mounts or restricted sandbox filesystems and point the cache at a writable path (e.g. sys_get_temp_dir()).","If the cache is not needed, disable it (don't set a filesystem cache) in dev.","Check disk space with df -h."],"exampleFix":"// before\n$twig->setCache('/var/cache/twig'); // www-data cannot create /var/cache/twig\n\n// after\n$cacheDir = '/var/cache/twig';\nif (!is_dir($cacheDir)) { @mkdir($cacheDir, 0775, true); }\nif (!is_dir($cacheDir) || !is_writable($cacheDir)) {\n    $cacheDir = sys_get_temp_dir().'/twig';\n}\n$twig->setCache($cacheDir);","handlingStrategy":"try-catch","validationCode":"function ensureCacheDirWritable(string $cacheDir): void {\n    if (!is_dir($cacheDir)) { @mkdir($cacheDir, 0775, true); }\n    if (!is_dir($cacheDir) || !is_writable($cacheDir)) {\n        throw new \\RuntimeException(\"Cache dir not writable: $cacheDir\");\n    }\n}","typeGuard":null,"tryCatchPattern":"try { $twig->render($name, $vars); } catch (\\RuntimeException $e) {\n    if (str_starts_with($e->getMessage(), 'Unable to create the cache directory')) {\n        $twig->setCache(sys_get_temp_dir().'/twig'); // fallback cache\n    } else { throw $e; }\n}","preventionTips":["Provision and chown the cache directory during deployment, not at first render.","Run PHP under a user with write access to the configured cache path.","Never point setCache() at read-only mounts or paths occupied by files.","Monitor disk space and filesystem writability in health checks."],"tags":["twig","cache","filesystem","permissions","mkdir"],"backgroundTag":"mkdir-permission-denied","analyzedSha":"a414c3a491defb5a60f2fc88ef79ff37c90010cd","analyzedAt":"2026-09-13T15:10:46.849Z","contentChangedAt":"2026-09-13T15:10:46.849Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}