{"record":{"id":"c4109fac9db3b91d","repo":"vlucas/phpdotenv","slug":"conversion-from-encoding-s-failed","errorCode":null,"errorMessage":"Conversion from encoding [%s] failed.","messagePattern":"Conversion from encoding \\[(.+?)\\] failed\\.","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":"In Str::utf8() (src/Util/Str.php:49) mbstring's mb_convert_encoding() is run with error suppression; if it returns a non-string (false on failure), the Result becomes an error and Reader::readFromFile() throws Dotenv\\Exception\\InvalidEncodingException (src/Store/File/Reader.php:77). Unlike error [7] the encoding name was accepted — the conversion itself failed, meaning the file bytes could not be converted to UTF-8 under the declared (or auto-detected) encoding. The message prints 'NULL' when no encoding was given.","triggerScenarios":"Declaring fileEncoding='UTF-16' while the file is actually UTF-8/corrupt/truncated (bad BOM, odd byte length); leaving encoding null so mb_convert_encoding auto-detection guesses wrong on mixed or binary content; a .env containing binary garbage or a truncated multibyte sequence; file mutated by a tool that mangled bytes.","commonSituations":"Files written by Windows editors claiming UTF-16 but saved differently; CI checkouts applying encoding-filters or CRLF manglers; secrets pasted from a password manager inserting odd bytes; partial uploads of the env file.","solutions":["Open the file in an editor, re-save it as plain UTF-8, and drop the fileEncoding argument (null auto-detect then works).","If you keep a non-UTF-8 file, verify the declared encoding matches reality: mb_check_encoding(file_get_contents($path), $encoding).","Inspect the first bytes (BOM) and file size — truncated multibyte files convert fine only after repair.","Check for stray binary characters: bin2hex the region around any pasted secret."],"exampleFix":"// before\n$dotenv = Dotenv::createImmutable(__DIR__, null, true, 'UTF-16')->load();\n// file is actually UTF-8 -> InvalidEncodingException: Conversion from encoding [UTF-16] failed.\n\n// after (re-save .env as UTF-8, then)\n$dotenv = Dotenv::createImmutable(__DIR__)->load();","handlingStrategy":"validation","validationCode":"// Prove the file converts cleanly before bootstrapping Dotenv:\n$path = $dir . '/.env';\n$content = file_get_contents($path);\nif ($content !== false && $encoding !== null && !mb_check_encoding($content, $encoding)) {\n    throw new RuntimeException(\".env is not valid {$encoding}; re-save it as UTF-8\");\n}\n// For auto-detect (encoding === null), a round-trip sanity check:\nif ($content !== false && @mb_convert_encoding($content, 'UTF-8') === false) {\n    throw new RuntimeException('.env content could not be converted to UTF-8');\n}","typeGuard":null,"tryCatchPattern":"use Dotenv\\Exception\\InvalidEncodingException;\n\ntry {\n    Dotenv::createImmutable($dir, null, true, $encoding)->load();\n} catch (InvalidEncodingException $e) {\n    // 'Conversion from encoding [X] failed.' -> the bytes do not match the declared encoding\n    // re-save the file as UTF-8 and retry once with encoding omitted; then fail hard\n}","preventionTips":["Standardize all env files on UTF-8 and leave fileEncoding unset.","Add a pre-commit/CI check that each .env passes mb_check_encoding in its declared encoding.","Suspect truncated or binary-mangled content whenever a previously-working setup starts failing after tooling changes."],"tags":["dotenv","encoding","mbstring","env-file","php"],"backgroundTag":"character-encoding-conversion-failed","analyzedSha":"416df702837983f8d5ff48c9c3fee4f5f57b980b","analyzedAt":"2026-08-21T01:19:52.946Z","schemaVersion":2},"datasetVersion":"2026-08-21T03:17:12.404Z"}