file_get_contents

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

file_get_contentsLegge un file all'interno di una stringa

Description

file_get_contents(
    string $filename,
    bool $use_include_path = ?,
    resource $context = ?,
    int $offset = ?
): string

Simile alla funzione file(), tranne che file_get_contents() restituisce il file in una stringa, iniziando allo specificato offset. Se si verifica un errore file_get_contents() restituirà false

Nota: Il parametrooffset è stato aggiunto nel PHP 5.1.0.

Nota:

Se si sta aprendo un URI con caratteri speciali, spazi ad esempio, si ha bisogno di decodificare l' URI con urlencode().

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Suggerimento

È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Vedere fopen() per maggiori informazioni su come specificare i nomi di file. Vedere Supported Protocols and Wrappers per i link verso le informazioni sulle capacità dei vari wrapper, note sul loro uso, informazioni sulle variabili predefinite che forniscono.

Nota: Il supporto per il contesto è stato aggiunto in PHP 5.0.0. Per la descrizione del contesto, fare riferimento a Stream Funzioni.

Avviso

Quando si usa SSL, Microsoft IIS viola il protocollo chiudendo la connessione senza inviare un'indicazione close_notify. PHP indicherà questo con un "SSL: Fatal Protocol Error" al raggiungimento della fine dei dati. Per aggirare questo problema, occorre abbassare il livello error_reporting per non includere questi avvisi. PHP 4.3.7 e successivi sono in grado di identificare gli IIS bacati quando si apre lo stream utilizzando il wrapper https:// e disabilitano automaticamente l'avviso. Se si usa fsockopen() per creare un socket ssl://, occorre identificare e sopprimere l'avviso manualmente.

Vedere anche fgets(), file(), fread(), include, readfile() e file_put_contents().

add a note

User Contributed Notes 5 notes

up
40
Bart Friederichs
13 years ago
file_get_contents can do a POST, create a context for that first:

<?php

$opts = array('http' =>
  array(
    'method'  => 'POST',
    'header'  => "Content-Type: text/xml\r\n".
      "Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n",
    'content' => $body,
    'timeout' => 60
  )
);
                        
$context  = stream_context_create($opts);
$url = 'https://'.$https_server;
$result = file_get_contents($url, false, $context, -1, 40000);

?>
up
1
julien at pixeye dot net
5 months ago
See also: http_get_last_response_headers() function to get last HTTP response headers including the HTTP response status code (200, 404, ...)
up
5
brentcontact at daha dot us
2 years ago
To prevent mixed content most browsers/functions will use the protocol already used if you specify only // instead of http:// or https://. This is not the case with file_get_contents. You must specify the protocol. This does not work:<?php$jsonData = file_get_contents('//example.com/file.json');print $jsonData;?>Specifying only 'example.com/file.json' without the double slash does not work either.When running on Apache 2.4 , using $_SERVER['REQUEST_SCHEME'] is a better way to be protocol agnostic.<?php$jsonData = file_get_contents($_SERVER['REQUEST_SCHEME'].'://example.com/file.json');print $jsonData;?>If using another web server, you may have to get the protocol another way or hard code it.
up
4
KC
1 year ago
If doing a negative offset to grab the end of a file and the file is shorter than the offset, then file_get_contents( ) will return false.If you want it to just return what is available when the file is shorter than the negative offset, you could try again.For example...$contents = file_get_contents( $log_file, false, null, -4096 ); // Get last 4KBif ( false === $contents ) {    // Maybe error, or maybe file less than 4KB in size.    $contents = file_get_contents( $log_file, false, null );    if ( false === $contents ) {        // Handle real error.    }}
up
-4
soger
2 years ago
There's barely a mention on this page but the $http_response_header will be populated with the HTTP headers if your file was a link. For example if you're expecting an image you can do this:<?php$data = file_get_contents('https://example.net/some-link');$mimetype = null;foreach ($http_response_header as $v) {    if (preg_match('/^content\-type:\s*(image\/[^;\s\n\r]+)/i', $v, $m)) {        $mimetype = $m[1];    }}if (!$mimetype) {    // not an image}
To Top