{"record":{"id":"8ba0d9046a74a0a2","repo":"vlucas/phpdotenv","slug":"failed-to-parse-dotenv-file-s","errorCode":null,"errorMessage":"Failed to parse dotenv file. %s","messagePattern":"Failed to parse dotenv file\\. (.+?)","errorType":"exception","errorClass":"InvalidFileException","httpStatus":null,"severity":"error","filePath":"src/Parser/Parser.php","lineNumber":30,"sourceCode":"final class Parser implements ParserInterface\n{\n    /**\n     * Parse content into an entry array.\n     *\n     * @param string $content\n     *\n     * @throws \\Dotenv\\Exception\\InvalidFileException\n     *\n     * @return \\Dotenv\\Parser\\Entry[]\n     */\n    public function parse(string $content)\n    {\n        return Regex::split(\"/(\\r\\n|\\n|\\r)/\", $content)->mapError(static function () {\n            return 'Could not split into separate lines.';\n        })->flatMap(static function (array $lines) {\n            return self::process(Lines::process($lines));\n        })->mapError(static function (string $error) {\n            throw new InvalidFileException(\\sprintf('Failed to parse dotenv file. %s', $error));\n        })->success()->get();\n    }\n\n    /**\n     * Convert the raw entries into proper entries.\n     *\n     * @param string[] $entries\n     *\n     * @return \\GrahamCampbell\\ResultType\\Result<\\Dotenv\\Parser\\Entry[], string>\n     */\n    private static function process(array $entries)\n    {\n        /** @var \\GrahamCampbell\\ResultType\\Result<\\Dotenv\\Parser\\Entry[], string> */\n        return \\array_reduce($entries, static function (Result $result, string $raw) {\n            return $result->flatMap(static function (array $entries) use ($raw) {\n                return EntryParser::parse($raw)->map(static function (Entry $entry) use ($entries) {\n                    /** @var \\Dotenv\\Parser\\Entry[] */\n                    return \\array_merge($entries, [$entry]);","sourceCodeStart":12,"sourceCodeEnd":48,"githubUrl":"https://github.com/vlucas/phpdotenv/blob/416df702837983f8d5ff48c9c3fee4f5f57b980b/src/Parser/Parser.php#L12-L48","documentation":"Thrown as Dotenv\\Exception\\InvalidFileException by Parser::parse() (src/Parser/Parser.php:30) when the file content is not valid dotenv syntax. The parser splits content into lines (Lines::process drops comments/blank lines and stitches multiline quoted values), then runs each remaining entry through EntryParser inside a Result chain; the first Result error is rethrown with its concrete reason appended, e.g. 'Failed to parse dotenv file. Encountered an invalid name at [FOO BAR=1].'. This is the library's only syntax-error signal for ->load(), ->safeLoad() and Dotenv::parse().","triggerScenarios":"Calling Dotenv::createImmutable($dir)->load() or Dotenv::parse($content) with an entry that EntryParser rejects: a line starting with '=' ('=VALUE' -> 'an unexpected equals'); a name with characters outside [letters digits _ .] after export/quote stripping ('FOO BAR=1', 'FOO-BAR=1' -> 'an invalid name'); an unterminated quoted value ('FOO=\"bar' or \"FOO='bar\" -> 'a missing closing quote'); a double-quoted escape outside \\\\ \\\" \\$ \\f \\n \\r \\t \\v ('FOO=\"bar\\q\"' -> 'an unexpected escape sequence'); unquoted value with embedded whitespace followed by more text ('FOO=bar baz' -> 'unexpected whitespace'); or, rarely, a PCRE failure in the line split ('Could not split into separate lines.').","commonSituations":"Unquoted values containing spaces or inline '#' comments; secrets with quotes, backslashes or '$'; multiline blocks whose closing quote was deleted; keys with hyphens/spaces copied from docker-compose or shell scripts; hand-edited files pasted from chat/docs that mangled quotes; very large .env files hitting PCRE limits.","solutions":["Read the text after 'Failed to parse dotenv file.' — it names the exact cause and the offending line (e.g. 'Encountered unexpected whitespace at [FOO=bar baz].').","Double-quote values containing spaces, '#', '$' or quotes: FOO=\"bar baz\".","Fix or delete the named line; for multiline values make sure the opening \" has a matching closing \".","Inside double quotes only use escapes \\n \\r \\t \\v \\f \\\" \\\\ \\$; for literal text use single quotes (no escapes processed).","Add a lint step to CI (e.g. dotenv-linter) and validate deployment artifacts with Dotenv::parse() before release."],"exampleFix":"// before (.env)\nAPP_NAME=My App # comment\nMAIL_DSN=\"smtp://user\\q:pass@host\"\n\n// after (.env)\nAPP_NAME=\"My App\" # comment\nMAIL_DSN='smtp://user\\q:pass@host'","handlingStrategy":"try-catch","validationCode":"// Pre-flight a .env before wiring it into bootstrap (throws the same InvalidFileException on bad syntax):\nuse Dotenv\\Dotenv;\nuse Dotenv\\Exception\\InvalidFileException;\n\ntry {\n    Dotenv::parse((string) file_get_contents($dir . '/.env'));\n} catch (InvalidFileException $e) {\n    fwrite(STDERR, $e->getMessage() . \\PHP_EOL); // names cause + offending line\n    exit(1);\n}","typeGuard":null,"tryCatchPattern":"use Dotenv\\Exception\\InvalidFileException;\nuse Dotenv\\Exception\\InvalidPathException;\nuse Dotenv\\Exception\\InvalidEncodingException;\n\ntry {\n    Dotenv::createImmutable($dir)->load();\n} catch (InvalidFileException $e) {\n    // syntax error: message contains the exact cause; fail the boot loudly\n    throw new RuntimeException('Invalid .env syntax: ' . $e->getMessage(), 0, $e);\n} catch (InvalidPathException | InvalidEncodingException $e) {\n    // separate handling for path/encoding problems, see errors 7-10\n}","preventionTips":["Always double-quote values that contain spaces, '#', '$' or quotes.","Keep a linted .env.example and run a dotenv linter in CI.","Never hand-edit production .env files from word processors or chat windows.","Run Dotenv::parse() over the file in a deploy pre-check so bad syntax blocks the release, not the runtime."],"tags":["dotenv","env-file","parsing","syntax","php"],"backgroundTag":"dotenv-syntax-error","analyzedSha":"416df702837983f8d5ff48c9c3fee4f5f57b980b","analyzedAt":"2026-08-21T01:19:52.946Z","schemaVersion":2},"datasetVersion":"2026-08-21T03:17:12.404Z"}