Signatur
Beschreibung
file_get_contents() ist der einfachste Weg, Datei-Inhalt in PHP zu laden. Die Funktion liest sowohl lokale Pfade als auch, wenn allow_url_fopen aktiviert ist, HTTP(S)-URLs.
Achtung Memory: Die komplette Datei wird in einen String geladen. Für Dateien größer als ein paar MB besser fopen() + fgets() in einer Schleife nutzen.
Für produktive HTTP-Requests ist file_get_contents() nicht die richtige Wahl — nutze cURL oder Guzzle: keine Retries, keine Timeouts, keine Header-Kontrolle out-of-the-box.
Parameter
| Name | Typ | Default | Beschreibung |
|---|---|---|---|
| $filename Pflicht | string | — | Pfad zur Datei oder URL. |
| $use_include_path | bool | false | Ob der PHP-include_path durchsucht werden soll. |
| $context | resource|null | null | Stream-Context, z. B. für HTTP-Header oder SSL-Optionen. |
| $offset | int | 0 | Byte-Position, ab der gelesen wird. |
| $length | ?int | null | Maximale Byte-Länge. null = bis Dateiende. |
Rückgabewert
false bei Fehler.Beispiele
Lokale Datei lesen
<?php
$content = file_get_contents(__DIR__ . '/config.json');
if ($content === false) {
throw new RuntimeException('Konfig konnte nicht gelesen werden');
}
$config = json_decode($content, associative: true, flags: JSON_THROW_ON_ERROR);
HTTP-Request mit Timeout
<?php
$ctx = stream_context_create([
'http' => [
'timeout' => 5,
'header' => "User-Agent: programmierung.net\r\n",
],
]);
$json = file_get_contents('https://api.github.com/repos/laravel/laravel', context: $ctx);