PHP 8.3.4 Released!

file_get_contents

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

file_get_contentsTransmite un fichero completo a una cadena

Descripción

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

Esta función es similar a file(), excepto que file_get_contents() devuelve el fichero a un string, comenzando por el offset especificado hasta maxlen bytes. Si falla, file_get_contents() devolverá false.

file_get_contents() es la manera preferida de transmitir el contenido de un fichero a una cadena. Para mejorar el rendimiento, utiliza técnicas de mapeado de memoria si sistema operativo lo admite..

Nota:

Si se está abriendo un URI con caracteres especiales, tales como espacios, se necesita codificar el URI con urlencode().

Parámetros

filename

Nombre del fichero a leer.

use_include_path

Nota:

A partir de PHP 5, se puede usar la constante FILE_USE_INCLUDE_PATH para lanzar la búsqueda en include_path. Esto no es posible si está habilitada la tipificación esctricta, ya que FILE_USE_INCLUDE_PATH es de tipo int. Utilice true en su lugar.

context

Un recurso de contexto válido creado con stream_context_create(). Si no se necesita usar un contexto a medida, se puede saltar este parámetro usando null.

offset

El índice donde comienza la lectura en el flujo original. Los índices negativos inician la cuenta desde el final del flujo.

La búsqueda de (offset) no está soportada con ficheros remotos. Intentar buscar un fichero no local puede funcionar con índices pequeños, pero es impredecible debido a que trabaja sobre el flujo almacenado en buffer.

maxlen

La longitud máxima de los datos leídos. De manera predeterminada se lee hasta que se alcance el final del fichero. Observe que este parámetro se aplica al flujo procesado por los filtros.

Valores devueltos

Esta función devuelve los datos leídos o false en caso de error.

Advertencia

Esta función puede devolver el valor booleano false, pero también puede devolver un valor no booleano que se evalúa como false. Por favor lea la sección sobre Booleanos para más información. Use el operador === para comprobar el valor devuelto por esta función.

Errores/Excepciones

Se genera un error de nivel E_WARNING si filename no se pudo encontrar, maxlength es menor de cero, o si falla la búsqueda del offset especificado en el flujo.

Ejemplos

Ejemplo #1 Obtiene y muestra el código fuente de la página de inicio de un sitio web

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

Ejemplo #2 Buscar dentro de include_path

<?php
// <= PHP 5
$fichero = file_get_contents('./gente.txt', true);
// > PHP 5
$fichero = file_get_contents('./gente.txt', FILE_USE_INCLUDE_PATH);
?>

Ejemplo #3 Leer una sección de un fichero

<?php
// Leer 14 caracteres comenzando desde el carácter número 21
$sección = file_get_contents('./people.txt', FALSE, NULL, 20, 14);
var_dump($sección);
?>

El resultado del ejemplo sería algo similar a:

string(14) "lle Bjori Ro"

Ejemplo #4 Usar contextos de flujo

<?php
// Crear un flujo
$opciones = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);

$contexto = stream_context_create($opciones);

// Abre el fichero usando las cabeceras HTTP establecidas arriba
$fichero = file_get_contents('http://www.example.com/', false, $contexto);
?>

Historial de cambios

Versión Descripción
7.1.0 Se añadió soporte para valores negativos de offset.
5.1.0 Se añadieron los parámetros offset y maxlen.

Notas

Nota: Esta función es segura binariamente.

Sugerencia

Se puede emplear un URL como nombre de fichero con esta función si las envolturas de fopen han sido activadas. Véase fopen() para más información de cómo especificar el nombre de fichero. Véanse las Protocolos y Envolturas soportados; continen enlaces con información sobre las diferentes capacidades que tienen las envolturas, notas sobre su empleo, e información de cualquier variable predefinida que podría proporcionarse.

Advertencia

Cuando se usa SSL, Microsoft IIS violará el protocolo, cerrando la conexión sin mandar un indicador close_notify. PHP avisará de esto con este mensaje "SSL: Fatal Protocol Error", cuando llegue al final de los datos. Una solución a este problema es bajar el nivel de aviso de errores del sistema para que no incluya advertencias. PHP pueden detectar servidores IIS con este problema cuando se abre un flujo usando https:// y suprime la advertencia. Si usáis la función fsockopen() para crear un socket ssl://, tendréis que suprimir la advertencia explicitamente.

Ver también

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