PHP 8.3.4 Released!

file_get_contents

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

file_get_contentsLê todo o conteúdo de um arquivo para uma string

Descrição

file_get_contents(
    string $filename,
    bool $use_include_path = false,
    ?resource $context = null,
    int $offset = 0,
    ?int $length = null
): string|false

Esta função é semelhante à file(), exceto que file_get_contents() retorna o arquivo em uma string, começando a partir de offset até length bytes. Em caso de falha, file_get_contents() retornará false.

file_get_contents() é o método preferível para ler o conteúdo de um arquivo em uma string. Ela usa técnicas de mapeamento de memória suportadas pelo sistema operacional para melhorar o desempenho.

Nota:

Se for aberta uma URI com caracteres especiais, como espaços, é necessário codificar a URI com urlencode().

Parâmetros

filename

Nome do arquivo para ler.

use_include_path

Nota:

A constante FILE_USE_INCLUDE_PATH pode ser usada para acionar a busca no include path. Isto não é possível se a tipagem estrita estiver habilitada, já que FILE_USE_INCLUDE_PATH é um int. Em vez disso, use true.

context

Um recurso de contexto válido, criado com stream_context_create(). Se você não precisa usar um contexto personalizado, você pode ignorar este parâmetro passando null.

offset

O ponto onde a leitura deve começar no fluxo original. Offsets negativos contam a partir do final do fluxo.

offset não é suportado em arquivos remotos. Tentar fazer busca em arquivos não locais pode funcionar com offsets pequenos, mas isso é imprevisível pois só funciona no fluxo com buffer.

length

Comprimento máximo dos dados lidos. O padrão é ler até que o fim do arquivo seja alcançado. Note que este parâmetro é aplicado para o fluxo processado pelos filtros.

Valor Retornado

A função retorna os dados lidos ou false em caso de falha.

Aviso

Esta função pode retornar o valor booleano false, mas também pode retornar um valor não booleano que pode ser avaliado como false. Leia a seção sobre Booleanos para mais informações. Use o operador === para testar o valor retornado por esta função.

Erros/Exceções

Um erro de nível E_WARNING é gerado se filename não puder ser encontrado, length é menor que zero, ou se a busca no fluxo pelo offset especificado falhar.

Quando file_get_contents() é chamada em um diretório, um erro nível E_WARNING é gerado no Windows, e a partir do PHP 7.4 em outros sistemas operacionais também.

Registro de Alterações

Versão Descrição
8.0.0 length agora é anulável.
7.1.0 Suporte para offsets negativos foi adicionado.

Exemplos

Exemplo #1 Obtém e exibe o código-fonte da página inicial de um website

<?php
$homepage
= file_get_contents('http://www.example.com/');
echo
$homepage;
?>

Exemplo #2 Buscando no include_path

<?php
// Se strict types estiver ativado com declare(strict_types=1);
$file = file_get_contents('./people.txt', true);
// Se não
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>

Exemplo #3 Lendo uma sessão de um arquivo

<?php
// Le 14 letras começando da letra 21
$section = file_get_contents('./people.txt', FALSE, NULL, 20, 14);
var_dump($section);
?>

O exemplo acima produzirá algo semelhante a:

string(14) "lle Bjori Ro"

Exemplo #4 Usando contextos de fluxo

<?php
// Criam um fluxo
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);

$context = stream_context_create($opts);

// Abre o arquivo utilizando os headers HTTP craidos acima
$file = file_get_contents('http://www.example.com/', false, $context);
?>

Notas

Nota: Esta função é compatível com dados binários.

Dica

Uma URL pode ser usada como um nome de arquivo com esta função se os wrappers fopen estiverem habilitados. Consulte a função fopen() para mais detalhes sobre como especificar o nome do arquivo. Consulte os Protocolos e Wrappers suportados para obter links para informações sobre as capacidades de cada wrapper, notas de uso e informações sobre quaisquer variáveis predefinidas que eles possam fornecer.

Aviso

Ao usar SSL, o Microsoft IIS violará o protocolo fechando a conexão sem enviar uma notificação close_notify. O PHP reportará isso como "SSL: Fatal Protocol Error" quando chegar ao final dos dados. Para contornar isso, o valor de error_reporting deve ser reduzido a um nível que não inclua avisos. O PHP pode detectar servidores IIS defeituosos quando o stream é aberto usando o wrapper https:// e suprimirá o aviso. Ao usar fsockopen() para criar um soquete ssl://, o desenvolvedor é responsável por detectar e suprimir este aviso.

Veja Também

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