<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/include/shared-manual.inc';
$TOC = array();
$TOC_DEPRECATED = array();
$PARENTS = array();
include_once dirname(__FILE__) ."/toc/ref.filesystem.inc";
$setup = array (
  'home' => 
  array (
    0 => 'index.php',
    1 => 'PHP Manual',
  ),
  'head' => 
  array (
    0 => 'UTF-8',
    1 => 'es',
  ),
  'this' => 
  array (
    0 => 'function.file-get-contents.php',
    1 => 'file_get_contents',
    2 => 'Lee todo un fichero en una cadena',
  ),
  'up' => 
  array (
    0 => 'ref.filesystem.php',
    1 => 'Funciones del Sistema de Archivos',
  ),
  'prev' => 
  array (
    0 => 'function.file-exists.php',
    1 => 'file_exists',
  ),
  'next' => 
  array (
    0 => 'function.file-put-contents.php',
    1 => 'file_put_contents',
  ),
  'alternatives' => 
  array (
  ),
  'source' => 
  array (
    'lang' => 'es',
    'path' => 'reference/filesystem/functions/file-get-contents.xml',
  ),
  'history' => 
  array (
  ),
);
$setup["toc"] = $TOC;
$setup["toc_deprecated"] = $TOC_DEPRECATED;
$setup["parents"] = $PARENTS;
manual_setup($setup);

contributors($setup);

?>
<div id="function.file-get-contents" class="refentry">
 <div class="refnamediv">
  <h1 class="refname">file_get_contents</h1>
  <p class="verinfo">(PHP 4 &gt;= 4.3.0, PHP 5, PHP 7, PHP 8)</p><p class="refpurpose"><span class="refname">file_get_contents</span> &mdash; <span class="dc-title">Lee todo un fichero en una cadena</span></p>

 </div>

 <div class="refsect1 description" id="refsect1-function.file-get-contents-description">
  <h3 class="title">Descripción</h3>
  <div class="methodsynopsis dc-description">
   <span class="methodname"><strong>file_get_contents</strong></span>(<br>&nbsp;&nbsp;&nbsp;&nbsp;<span class="methodparam"><span class="type"><a href="language.types.string.php" class="type string">string</a></span> <code class="parameter">$filename</code></span>,<br>&nbsp;&nbsp;&nbsp;&nbsp;<span class="methodparam"><span class="type"><a href="language.types.boolean.php" class="type bool">bool</a></span> <code class="parameter">$use_include_path</code><span class="initializer"> = <strong><code><a href="reserved.constants.php#constant.false">false</a></code></strong></span></span>,<br>&nbsp;&nbsp;&nbsp;&nbsp;<span class="methodparam"><span class="type"><span class="type"><a href="language.types.null.php" class="type null">?</a></span><span class="type"><a href="language.types.resource.php" class="type resource">resource</a></span></span> <code class="parameter">$context</code><span class="initializer"> = <strong><code><a href="reserved.constants.php#constant.null">null</a></code></strong></span></span>,<br>&nbsp;&nbsp;&nbsp;&nbsp;<span class="methodparam"><span class="type"><a href="language.types.integer.php" class="type int">int</a></span> <code class="parameter">$offset</code><span class="initializer"> = 0</span></span>,<br>&nbsp;&nbsp;&nbsp;&nbsp;<span class="methodparam"><span class="type"><span class="type"><a href="language.types.null.php" class="type null">?</a></span><span class="type"><a href="language.types.integer.php" class="type int">int</a></span></span> <code class="parameter">$length</code><span class="initializer"> = <strong><code><a href="reserved.constants.php#constant.null">null</a></code></strong></span></span><br>): <span class="type"><span class="type"><a href="language.types.string.php" class="type string">string</a></span>|<span class="type"><a href="language.types.singleton.php" class="type false">false</a></span></span></div>

  <p class="para rdfs-comment">
   Similar a la función <span class="function"><a href="function.file.php" class="function">file()</a></span>, excepto que
   <span class="function"><strong>file_get_contents()</strong></span> devuelve el fichero
   <code class="parameter">filename</code> en una cadena, comenzando
   desde la posición <code class="parameter">offset</code> y hasta
   <code class="parameter">length</code> bytes.
   En caso de error, <span class="function"><strong>file_get_contents()</strong></span> devuelve
   <strong><code><a href="reserved.constants.php#constant.false">false</a></code></strong>.
  </p>
  <p class="para">
   <span class="function"><strong>file_get_contents()</strong></span> es el método recomendado para leer
   el contenido de un fichero en una <span class="type"><a href="language.types.string.php" class="type string">string</a></span>. Utilizará un buffer en
   memoria si este mecanismo es soportado por el sistema, con el fin de mejorar
   el rendimiento.
  </p>
  <blockquote class="note"><p><strong class="note">Nota</strong>: 
   <p class="para">
    Si se abre una URI con caracteres especiales, como espacios, es necesario
    codificar esta URI con la función <span class="function"><a href="function.urlencode.php" class="function">urlencode()</a></span>.
   </p>
  </p></blockquote>
 </div>


 <div class="refsect1 parameters" id="refsect1-function.file-get-contents-parameters">
  <h3 class="title">Parámetros</h3>
  <p class="para">
   <dl>
    
     <dt><code class="parameter">filename</code></dt>
     <dd>
      <p class="para">
       Nombre del fichero a leer.
      </p>
     </dd>
    
    
     <dt><code class="parameter">use_include_path</code></dt>
     <dd>
      <blockquote class="note"><p><strong class="note">Nota</strong>: 
       <p class="para">
        La constante <strong><code><a href="filesystem.constants.php#constant.file-use-include-path">FILE_USE_INCLUDE_PATH</a></code></strong>
        puede ser utilizada para activar la búsqueda en el
        <a href="ini.core.php#ini.include-path" class="link">ruta de inclusión</a>.
        Esto no es posible si <a href="language.types.declarations.php#language.types.declarations.strict" class="link">strict typing</a>
        está activado, ya que <strong><code><a href="filesystem.constants.php#constant.file-use-include-path">FILE_USE_INCLUDE_PATH</a></code></strong> es un
        <span class="type"><a href="language.types.integer.php" class="type int">int</a></span>. Utilice <strong><code><a href="reserved.constants.php#constant.true">true</a></code></strong> en su lugar.
       </p>
      </p></blockquote>
     </dd>
    
    
     <dt><code class="parameter">context</code></dt>
     <dd>
      <p class="para">
       Un recurso de contexto válido, creado con la función
       <span class="function"><a href="function.stream-context-create.php" class="function">stream_context_create()</a></span>. Si no es necesario
       utilizar un contexto específico, este parámetro puede ser omitido
       asignándole el valor <strong><code><a href="reserved.constants.php#constant.null">null</a></code></strong>.
      </p>
     </dd>
    
    
     <dt><code class="parameter">offset</code></dt>
     <dd>
      <p class="para">
       La posición desde la cual se comienza a leer en el flujo original.
       Una posición negativa cuenta desde el final del flujo.
      </p>
      <p class="para">
       El desplazamiento en el fichero (<code class="parameter">offset</code>) no es
       soportado en ficheros remotos. Si se intenta desplazarse en un fichero
       que no es local puede funcionar en pequeños desplazamientos, pero el
       comportamiento puede no ser el esperado ya que el proceso utiliza el
       flujo del buffer.
      </p>
     </dd>
    
    
     <dt><code class="parameter">length</code></dt>
     <dd>
      <p class="para">
       El tamaño máximo de datos a leer. El comportamiento por defecto es leer
       hasta el final del fichero. Este parámetro se aplica al flujo procesado
       por los filtros.
      </p>
     </dd>
    
   </dl>
  </p>
 </div>


 <div class="refsect1 returnvalues" id="refsect1-function.file-get-contents-returnvalues">
  <h3 class="title">Valores devueltos</h3>
  <p class="para">
   Devuelve los datos leídos  o <strong><code><a href="reserved.constants.php#constant.false">false</a></code></strong> si ocurre un error.
  </p>
  <div class="warning"><strong class="warning">Advertencia</strong><p class="simpara">
 Esta función puede retornar <strong><code><a href="reserved.constants.php#constant.false">false</a></code></strong>, pero también puede retornar un valor equivalente a <strong><code><a href="reserved.constants.php#constant.false">false</a></code></strong>.
 Por favor, lea la sección sobre los <a href="language.types.boolean.php" class="link">booleanos</a> para más información.
 Utilice el <a href="language.operators.comparison.php" class="link">operador ===</a>
 para probar el valor de retorno exacto de esta función.
</p></div>
 </div>


 <div class="refsect1 errors" id="refsect1-function.file-get-contents-errors">
  <h3 class="title">Errores/Excepciones</h3>
  <p class="para">
   Genera una advertencia de tipo <strong><code><a href="errorfunc.constants.php#constant.e-warning">E_WARNING</a></code></strong> si,
   <code class="parameter">filename</code> no puede ser encontrado, si el
   parámetro <code class="parameter">length</code> es menor que cero,
   o si el desplazamiento a la posición <code class="parameter">offset</code>
   especificado en el flujo falla.
  </p>
  <p class="para">
   Cuando <span class="function"><strong>file_get_contents()</strong></span> es llamado sobre un directorio,
   se genera un error de nivel <strong><code><a href="errorfunc.constants.php#constant.e-warning">E_WARNING</a></code></strong> en Windows,
   y a partir de PHP 7.4 en otros sistemas operativos también.
  </p>
 </div>


 <div class="refsect1 changelog" id="refsect1-function.file-get-contents-changelog">
  <h3 class="title">Historial de cambios</h3>
  <p class="para">
   <table class="doctable informaltable">
    
     <thead>
      <tr>
       <th>Versión</th>
       <th>Descripción</th>
      </tr>

     </thead>

     <tbody class="tbody">
      <tr>
       <td>8.0.0</td>
       <td>
        <code class="parameter">length</code> ahora es nullable.
       </td>
      </tr>

      <tr>
       <td>7.1.0</td>
       <td>
        Se añade soporte para posiciones <code class="parameter">offset</code> negativas.
       </td>
      </tr>

     </tbody>
    
   </table>

  </p>
 </div>


 <div class="refsect1 examples" id="refsect1-function.file-get-contents-examples">
  <h3 class="title">Ejemplos</h3>
  <p class="para">
   <div class="example" id="example-1">
    <p><strong>Ejemplo #1 Lee y muestra el código HTML de un sitio web</strong></p>
    <div class="example-contents">
<div class="phpcode"><code><span style="color: #000000"><span style="color: #0000BB">&lt;?php<br />$homepage </span><span style="color: #007700">= </span><span style="color: #0000BB">file_get_contents</span><span style="color: #007700">(</span><span style="color: #DD0000">'http://www.example.com/'</span><span style="color: #007700">);<br />echo </span><span style="color: #0000BB">$homepage</span><span style="color: #007700">;<br /></span><span style="color: #0000BB">?&gt;</span></span></code></div>
    </div>

   </div>
   <div class="example" id="example-2">
    <p><strong>Ejemplo #2 Busca un fichero en el include_path</strong></p>
    <div class="example-contents">
<div class="phpcode"><code><span style="color: #000000"><span style="color: #0000BB">&lt;?php<br /></span><span style="color: #FF8000">// Si el tipado estricto está activado c.à.d. declare(strict_types=1);<br /></span><span style="color: #0000BB">$file </span><span style="color: #007700">= </span><span style="color: #0000BB">file_get_contents</span><span style="color: #007700">(</span><span style="color: #DD0000">'./people.txt'</span><span style="color: #007700">, </span><span style="color: #0000BB">true</span><span style="color: #007700">);<br /></span><span style="color: #FF8000">// De lo contrario<br /></span><span style="color: #0000BB">$file </span><span style="color: #007700">= </span><span style="color: #0000BB">file_get_contents</span><span style="color: #007700">(</span><span style="color: #DD0000">'./people.txt'</span><span style="color: #007700">, </span><span style="color: #0000BB">FILE_USE_INCLUDE_PATH</span><span style="color: #007700">);<br /></span><span style="color: #0000BB">?&gt;</span></span></code></div>
    </div>

   </div>
   <div class="example" id="example-3">
    <p><strong>Ejemplo #3 Lee una sección de un fichero</strong></p>
    <div class="example-contents">
<div class="phpcode"><code><span style="color: #000000"><span style="color: #0000BB">&lt;?php<br /></span><span style="color: #FF8000">// Lee 14 caracteres a partir del 21º carácter<br /></span><span style="color: #0000BB">$section </span><span style="color: #007700">= </span><span style="color: #0000BB">file_get_contents</span><span style="color: #007700">(</span><span style="color: #DD0000">'./people.txt'</span><span style="color: #007700">, </span><span style="color: #0000BB">FALSE</span><span style="color: #007700">, </span><span style="color: #0000BB">NULL</span><span style="color: #007700">, </span><span style="color: #0000BB">20</span><span style="color: #007700">, </span><span style="color: #0000BB">14</span><span style="color: #007700">);<br /></span><span style="color: #0000BB">var_dump</span><span style="color: #007700">(</span><span style="color: #0000BB">$section</span><span style="color: #007700">);<br /></span><span style="color: #0000BB">?&gt;</span></span></code></div>
    </div>

    <div class="example-contents"><p>Resultado del ejemplo anterior es similar a:</p></div>
    <div class="example-contents screen">
<div class="examplescode"><pre class="examplescode">string(14) &quot;lle Bjori Ro&quot;</pre>
</div>
    </div>
   </div>
   <div class="example" id="example-4">
    <p><strong>Ejemplo #4 Uso de contextos de flujo</strong></p>
    <div class="example-contents">
<div class="phpcode"><code><span style="color: #000000"><span style="color: #0000BB">&lt;?php<br /></span><span style="color: #FF8000">// Creación de un flujo<br /></span><span style="color: #0000BB">$opts </span><span style="color: #007700">= [<br />  </span><span style="color: #DD0000">'http'</span><span style="color: #007700">=&gt; [<br />    </span><span style="color: #DD0000">'method'</span><span style="color: #007700">=&gt;</span><span style="color: #DD0000">"GET"</span><span style="color: #007700">,<br />    </span><span style="color: #DD0000">'header'</span><span style="color: #007700">=&gt;</span><span style="color: #DD0000">"Accept-language: en\r\n" </span><span style="color: #007700">.<br />              </span><span style="color: #DD0000">"Cookie: foo=bar\r\n"</span><span style="color: #007700">,<br />  ]<br />];<br /><br /></span><span style="color: #0000BB">$context </span><span style="color: #007700">= </span><span style="color: #0000BB">stream_context_create</span><span style="color: #007700">(</span><span style="color: #0000BB">$opts</span><span style="color: #007700">);<br /><br /></span><span style="color: #FF8000">// Acceso a un fichero HTTP con los encabezados HTTP indicados arriba<br /></span><span style="color: #0000BB">$file </span><span style="color: #007700">= </span><span style="color: #0000BB">file_get_contents</span><span style="color: #007700">(</span><span style="color: #DD0000">'http://www.example.com/'</span><span style="color: #007700">, </span><span style="color: #0000BB">false</span><span style="color: #007700">, </span><span style="color: #0000BB">$context</span><span style="color: #007700">);<br /></span><span style="color: #0000BB">?&gt;</span></span></code></div>
    </div>

   </div>
  </p>
 </div>


 <div class="refsect1 notes" id="refsect1-function.file-get-contents-notes">
  <h3 class="title">Notas</h3>
  <blockquote class="note"><p><strong class="note">Nota</strong>: <span class="simpara">Esta función es
segura para sistemas binarios.</span></p></blockquote>
  <div class="tip"><strong class="tip">Sugerencia</strong><p class="simpara">
 Puede utilizar una URL como nombre de archivo con esta función, si el
 <a href="filesystem.configuration.php#ini.allow-url-fopen" class="link">gestor fopen</a> ha sido activado. Véase <span class="function"><a href="function.fopen.php" class="function">fopen()</a></span>
 para más detalles sobre cómo especificar el nombre del archivo. Consulte
 <a href="wrappers.php" class="xref">Protocolos y Envolturas soportados</a> para más información sobre las capacidades de los diferentes gestores,
 las notas sobre su uso, así como la información sobre las variables predefinidas que proporcionan.
</p></div>
  <div class="warning"><strong class="warning">Advertencia</strong><p class="para">
 Cuando SSL es utilizado, el servidor IIS de Microsoft violará el protocolo al cerrar la conexión sin
 enviar un indicador <code class="literal">close_notify</code>. PHP lo reportará como &quot;SSL: Fatal Protocol Error&quot;
 cuando se llegue al final de los datos. Para evitar esto, el nivel de la directiva
 <a href="errorfunc.configuration.php#ini.error-reporting" class="link">error_reporting</a> debe ser bajado para no incluir los avisos.
 PHP puede detectar automáticamente los servidores IIS defectuosos al abrir
 el flujo utilizando <code class="literal">https://</code> y suprimirá el aviso.
 Al utilizar <span class="function"><a href="function.fsockopen.php" class="function">fsockopen()</a></span> para crear un socket <code class="literal">ssl://</code>,
 es responsabilidad del desarrollador detectar y suprimir el aviso.
</p></div>
 </div>


 <div class="refsect1 seealso" id="refsect1-function.file-get-contents-seealso">
  <h3 class="title">Ver también</h3>
  <p class="para">
   <ul class="simplelist">
    <li><span class="function"><a href="function.file.php" class="function" rel="rdfs-seeAlso">file()</a> - Lee el fichero y devuelve el resultado en un array</span></li>
    <li><span class="function"><a href="function.fgets.php" class="function" rel="rdfs-seeAlso">fgets()</a> - Recupera la l&iacute;nea actual a partir de la posici&oacute;n del puntero de archivo</span></li>
    <li><span class="function"><a href="function.fread.php" class="function" rel="rdfs-seeAlso">fread()</a> - Lectura del archivo en modo binario</span></li>
    <li><span class="function"><a href="function.readfile.php" class="function" rel="rdfs-seeAlso">readfile()</a> - Muestra un fichero</span></li>
    <li><span class="function"><a href="function.file-put-contents.php" class="function" rel="rdfs-seeAlso">file_put_contents()</a> - Escribe datos en un fichero</span></li>
    <li><span class="function"><a href="function.stream-get-contents.php" class="function" rel="rdfs-seeAlso">stream_get_contents()</a> - Lee todo un flujo en un string</span></li>
    <li><span class="function"><a href="function.stream-context-create.php" class="function" rel="rdfs-seeAlso">stream_context_create()</a> - Crea un contexto de flujo</span></li>
    <li><a href="reserved.variables.httpresponseheader.php" class="link">$http_response_header</a></li>
   </ul>
  </p>
 </div>


</div><?php manual_footer($setup); ?>