{"record":{"id":"8c6cbb387b222e93","repo":"Intervention/image","slug":"failed-to-build-stream-from-string","errorCode":null,"errorMessage":"Failed to build stream from string","messagePattern":"Failed to build stream from string","errorType":"exception","errorClass":"Intervention\\Image\\Exceptions\\StreamException","httpStatus":null,"severity":"error","filePath":"src/Traits/CanBuildStream.php","lineNumber":29,"sourceCode":"{\n    /**\n     * Transform the provided data into a stream resource with the data as its content.\n     *\n     * @param resource|string|null $data\n     * @throws InvalidArgumentException\n     * @throws StreamException\n     * @return resource\n     */\n    public static function buildStreamOrFail(mixed $data = null)\n    {\n        $buildStrategy = match (true) {\n            is_null($data) => fn(mixed $data) => fopen('php://temp', 'r+'),\n            is_resource($data) && get_resource_type($data) === 'stream' => fn(mixed $data) => $data,\n            is_string($data) => function (mixed $data) {\n                $stream = fopen('php://temp', 'r+');\n\n                if ($stream === false) {\n                    throw new StreamException('Failed to build stream from string');\n                }\n\n                fwrite($stream, $data);\n                return $stream;\n            },\n            default => throw new InvalidArgumentException(\n                'Unable to create stream from ' . gettype($data) . '. Use only null, string or resource.',\n            ),\n        };\n\n        $stream = $buildStrategy($data);\n\n        if ($stream === false) {\n            throw new StreamException('Failed to build stream');\n        }\n\n        $rewind = rewind($stream);\n","sourceCodeStart":11,"sourceCodeEnd":47,"githubUrl":"https://github.com/Intervention/image/blob/5598b9e39751c34afc5cdee84abef77f92c26f68/src/Traits/CanBuildStream.php#L11-L47","documentation":"buildStreamOrFail() (src/Traits/CanBuildStream.php) turns string input into a PHP stream by copying it into a php://temp handle. This StreamException means fopen('php://temp', 'r+') itself returned false, so the stream could not even be created before any data was written. It is essentially an environment-level failure (memory/temp capacity or a broken PHP runtime), not an input-format problem.","triggerScenarios":"Calling a stream-backed API with a large string where the PHP process cannot allocate the php://temp handle: e.g. $image->toJpeg() / toStream()-style encode paths (AbstractEncoder uses this trait) or ImageManager::read($binaryString) on a big buffer while memory_limit is nearly exhausted. Also possible when the system temp directory is full, since php://temp spills to disk after the memory threshold.","commonSituations":"Shared hosting with a tight memory_limit (e.g. 64M/128M) while processing multi-megapixel photos; batch jobs that keep many image strings in memory; containers with a full /tmp volume (php://temp spills there); rare misconfigured PHP builds.","solutions":["Raise PHP's memory_limit (ini_set('memory_limit', '512M'); or php.ini/FPM pool config) and retry with the same input.","Free memory before the call: unset() large buffers, avoid holding all images of a batch in memory, process one at a time.","Check disk space on the temp filesystem (df -h /tmp) since php://temp falls back to a temp file; clear space or point sys_temp_dir elsewhere.","Catch Intervention\\Image\\Exceptions\\StreamException around the operation and report the environment problem instead of letting it fatal."],"exampleFix":"// before\nini_set('memory_limit', '128M');\n$stream = $manager->read($hugeBinaryString)->toGif(); // StreamException on tight limits\n\n// after\nini_set('memory_limit', '512M');\n$stream = $manager->read($hugeBinaryString)->toGif();","handlingStrategy":"try-catch","validationCode":"if (strlen($binary) > ini_get('memory_limit') === false) { /* size sanity check */ }\n// pragmatic pre-check:\n$limit = ini_parse_quantity(ini_get('memory_limit')) ?: 128 * 1024 * 1024;\nif (strlen($binary) > $limit / 4) {\n    ini_set('memory_limit', (string) (strlen($binary) * 8));\n}","typeGuard":null,"tryCatchPattern":"try {\n    $result = $image->toJpeg(); // or any stream-building encode\n} catch (\\Intervention\\Image\\Exceptions\\StreamException $e) {\n    // environment failure (memory/temp) - raise limits, free memory, then retry once\n    ini_set('memory_limit', '512M');\n    $result = $image->toJpeg();\n}","preventionTips":["Keep memory_limit comfortably above your largest expected image buffer (rule of thumb: 5-10x the decompressed pixel size for GD).","Process images one at a time; unset() intermediate buffers in batch loops.","Monitor free space on the temp filesystem where php://temp spills."],"tags":["php","intervention-image","stream","memory-limit","tmp"],"backgroundTag":"stream-open-failed","analyzedSha":"5598b9e39751c34afc5cdee84abef77f92c26f68","analyzedAt":"2026-08-23T02:17:31.068Z","schemaVersion":2},"datasetVersion":"2026-08-23T08:06:27.607Z"}