PHP 8.3.4 Released!

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 8 notes

up
5
KC
3 months 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 4KB

if ( 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
33
Bart Friederichs
11 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
0
daniel at dangarbri dot tech
1 year ago
Note that if an HTTP request fails but still has a response body, the result is still false, Not the response body which may have more details on why the request failed.
up
-2
soger
1 year 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
}
up
-1
brentcontact at daha dot us
7 months 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
-22
Anonymous
2 years ago
if the connection is
content-encoding: gzip
and you need to manually ungzip it, this is apparently the key
$c=gzinflate( substr($c,10,-8) );
(stolen from the net)
up
-24
453034559 at qq dot com
2 years ago
//从指定位置获取指定长度的文件内容
function file_start_length($path,$start=0,$length=null){
if(!file_exists($path)) return false;
$size=filesize($path);
if($start<0) $start+=$size;
if($length===null) $length=$size-$start;
return file_get_contents($path, false, null, $start, $length );
}
up
-29
allenmccabe at gmail dot com
2 years ago
I'm not sure why @jlh was downvoted, but I verified what he reported.

>>> file_get_contents($path false, null, 5, null)
=> ""
>>> file_get_contents($path, false, null, 5, 5)
=> "r/bin"
To Top