{"record":{"id":"a4198521257e1716","repo":"vlucas/phpdotenv","slug":"illegal-character-encoding-s-specified","errorCode":null,"errorMessage":"Illegal character encoding [%s] specified.","messagePattern":"Illegal character encoding \\[(.+?)\\] specified\\.","errorType":"exception","errorClass":"InvalidEncodingException","httpStatus":null,"severity":"error","filePath":"src/Store/File/Reader.php","lineNumber":77,"sourceCode":"\n    /**\n     * Read the given file.\n     *\n     * @param string      $path\n     * @param string|null $encoding\n     *\n     * @throws \\Dotenv\\Exception\\InvalidEncodingException\n     *\n     * @return \\PhpOption\\Option<string>\n     */\n    private static function readFromFile(string $path, ?string $encoding = null)\n    {\n        /** @var Option<string> */\n        $content = Option::fromValue(@\\file_get_contents($path), false);\n\n        return $content->flatMap(static function (string $content) use ($encoding) {\n            return Str::utf8($content, $encoding)->mapError(static function (string $error) {\n                throw new InvalidEncodingException($error);\n            })->success();\n        });\n    }\n}\n","sourceCodeStart":59,"sourceCodeEnd":82,"githubUrl":"https://github.com/vlucas/phpdotenv/blob/416df702837983f8d5ff48c9c3fee4f5f57b980b/src/Store/File/Reader.php#L59-L82","documentation":"Str::utf8() (src/Util/Str.php:38) validates the requested file encoding with a strict in_array($encoding, mb_list_encodings(), true) before converting file content to UTF-8; on mismatch Reader::readFromFile() rethrows the Result error as Dotenv\\Exception\\InvalidEncodingException (src/Store/File/Reader.php:77). Because the comparison is strict, the encoding string must match an mbstring name exactly (case and hyphens included). The check only runs when at least one env file was actually read — an unread file fails differently (InvalidPathException).","triggerScenarios":"Passing a fifth argument / fileEncoding that is not an exact mbstring encoding name to Dotenv::create(), createMutable(), createImmutable(), createUnsafeMutable(), createUnsafeImmutable() or createArrayBacked(): 'utf8' or 'UTF8' (mbstring wants 'UTF-8'), lowercase 'utf-8' vs 'UTF-8' (strict compare is case-sensitive), 'latin1' (wants 'ISO-8859-1'), 'ANSI', or a value with trailing whitespace like 'UTF-16 '.","commonSituations":"Loading UTF-16 .env files exported from Windows tooling; encoding names taken from user config or an HTTP-accepted value; copy-pasting an encoding from a Java/Python project ('utf8'); case differences introduced by mb_strtolower'd config normalization.","solutions":["Use the exact name from mb_list_encodings(): 'UTF-8', 'UTF-16', 'UTF-16BE', 'ISO-8859-1', etc.","Or omit the encoding (pass null) to let mbstring auto-detect — most UTF-8 files need no argument.","Validate configurable encodings before use: in_array($encoding, mb_list_encodings(), true).","Confirm the mbstring extension is installed and current — the valid list comes from it."],"exampleFix":"// before\n$dotenv = Dotenv::createImmutable(__DIR__, null, true, 'utf8'); // throws InvalidEncodingException\n\n// after\n$dotenv = Dotenv::createImmutable(__DIR__, null, true, 'UTF-8'); // exact mbstring name; or omit for auto-detect","handlingStrategy":"validation","validationCode":"// Validate a configurable encoding before handing it to Dotenv::create*():\n$encoding = $config['env_encoding'] ?? null; // e.g. 'utf8' from user config\nif ($encoding !== null && !in_array($encoding, mb_list_encodings(), true)) {\n    throw new InvalidArgumentException(sprintf(\n        'env_encoding [%s] is not a valid mbstring encoding; valid examples: %s',\n        $encoding,\n        implode(', ', array_slice(mb_list_encodings(), 0, 5))\n    ));\n}","typeGuard":"function isValidMbEncoding(?string $encoding): bool\n{\n    return $encoding === null || in_array($encoding, mb_list_encodings(), true); // strict: case-sensitive\n}","tryCatchPattern":"use Dotenv\\Exception\\InvalidEncodingException;\n\ntry {\n    Dotenv::createImmutable($dir, null, true, $encoding)->load();\n} catch (InvalidEncodingException $e) {\n    // message: 'Illegal character encoding [X] specified.' -> fix the encoding name, do not retry\n    log_and_abort($e->getMessage());\n}","preventionTips":["Prefer omitting fileEncoding (null) — mbstring auto-detects plain UTF-8 files.","Treat encoding names as an enum from mb_list_encodings(), never free-form config.","Remember the check is case-sensitive: 'UTF-8' passes, 'utf-8' does not."],"tags":["dotenv","encoding","mbstring","env-file","php"],"backgroundTag":"invalid-character-encoding","analyzedSha":"416df702837983f8d5ff48c9c3fee4f5f57b980b","analyzedAt":"2026-08-21T01:19:52.946Z","schemaVersion":2},"datasetVersion":"2026-08-21T03:17:12.404Z"}