PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

file_put_contents> <file_exists
Last updated: Fri, 20 Jun 2008

view this page in

file_get_contents

(PHP 4 >= 4.3.0, PHP 5)

file_get_contents — Lit tout un fichier dans une chaîne

Description

string file_get_contents ( string $filename [, int $flags [, resource $context [, int $offset [, int $maxlen ]]]] )

Identique à la fonction readfile(), hormis le fait que file_get_contents() retourne le fichier filename dans une chaîne, à partir de la position offset , et jusqu'à maxlen octets. En cas d'erreur, file_get_contents() retourne FALSE.

file_get_contents() est la façon préférée pour lire le contenu d'un fichier dans un fichier. Elle utilisera un mappage de mémoire si ce mécanisme est supporté par votre système, afin d'améliorer les performances.

Note: Si vous ouvrez une URI avec des caractères spéciaux, comme des espaces, vous devez encoder cette URI avec la fonction urlencode().

Liste de paramètres

filename

Nom du fichier à lire.

flags
Avertissement

Pour toutes les versions antérieures à PHP 6, ce paramètre est appelé use_include_path et est du type bool. Le paramètre flags n'est disponible que depuis PHP 6. Si vous utilisez une ancienne version et que vous voulez rechercher le fichier filename dans le chemin d'inclusion, ce paramètre doit être défini à TRUE. Depuis PHP 6, vous devez utiliser le drapeau FILE_USE_INCLUDE_PATH à la place.

La valeur de flags peut être n'importe quelle combinaison des drapeaux suivants (avec quelques restrictions), joints avec l'opérateur binaire OU (|).

Drapeaux disponibles
Drapeau Description
FILE_USE_INCLUDE_PATH Recherche le fichier filename dans le dossier d'inclusion. Voir include_path pour plus d'informations.
FILE_TEXT Si la sémantique unicode est activée, l'encodage par défaut pour la lecture des données sera UTF-8. Vous pouvez spécifier un encodage différent en créant un contexte personnalisé ou en modifiant celui par défaut en utilisant la fonction stream_default_encoding(). Ce drapeau ne peut être utilisé avec FILE_BINARY.
FILE_BINARY Avec ce drapeau, le fichier est lu en mode binaire. C'est la configuration par défaut et ne peut être utilisé avec FILE_TEXT.

context

Une ressource de contexte valide, créée avec la fonction stream_context_create(). Si vous n'avez pas besoin d'utiliser un contexte particulier, vous pouvez ignorer ce paramètre en affectant la valeur NULL.

offset

La position à partir de laquelle on commence à lire.

maxlen

La taille maximal de données à lire.

Valeurs de retour

Retourne les données lues, ou FALSE si une erreur survient.

Historique

Version Description
5.0.0 Ajout du support du contexte.
5.1.0 Ajout des paramètres offset et maxlen .
6.0.0 Le paramètre use_include_path a été remplacé par le paramètre flags .

Notes

Note: Cette fonction gère les chaînes binaires.

Astuce

Vous pouvez utiliser une URL comme nom de fichier avec cette fonction, si le gestionnaire fopen a été activée. Voyez fopen() pour plus de détails sur la façon de spécifier le nom du fichier et Liste des protocoles supportés pour une liste des protocoles URL supportés.

Avertissement

Lorsque vous utilisez SSL, le serveur IIS de Microsoft violera le protocole en fermant la connexion sans envoyer l'indicateur close_notify. PHP le reportera en tant que "SSL: Fatal Protocol Error" quand vous arrivez à la fin des données. L'astuce est de baisser le niveau de la directive error_reporting pour ne pas inclure les warnings. À partir de PHP 4.3.7, le bogue est détecté automatiquement lors de l'ouverture du flux en utilisant https:// et supprimera cet avertissement pour vous. Si vous utilisez fsockopen() pour créer une socket ssl://, vous devez vous occuper vous-même de supprimer l'erreur.



file_put_contents> <file_exists
Last updated: Fri, 20 Jun 2008
 
add a note add a note User Contributed Notes
file_get_contents
joachimb at gmail dot com
15-Apr-2008 11:38
Setting the timeout properly without messing with ini values:

<?php
$ctx
= stream_context_create(array(
   
'http' => array(
       
'timeout' => 1
       
)
    )
);
file_get_contents("http://example.com/", 0, $ctx);
?>
3n1gm4 [at] gmail [dot] com
02-Apr-2008 11:12
This is a nice and simple substitute to get_file_contents() using curl, it returns FALSE if $contents is empty.

<?php
function curl_get_file_contents($URL)
    {
       
$c = curl_init();
       
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
       
curl_setopt($c, CURLOPT_URL, $URL);
       
$contents = curl_exec($c);
       
curl_close($c);

        if (
$contents) return $contents;
            else return
FALSE;
    }
?>

Hope this help, if there is something wrong or something you don't understand let me know :)
jose dot nobile at gmail dot com
29-Jan-2008 08:29
<?PHP
//PHP 4.2.x Compatibility function
if (!function_exists('file_get_contents')) {
      function
file_get_contents($filename, $incpath = false, $resource_context = null)
      {
          if (
false === $fh = fopen($filename, 'rb', $incpath)) {
             
trigger_error('file_get_contents() failed to open stream: No such file or directory', E_USER_WARNING);
              return
false;
          }
 
         
clearstatcache();
          if (
$fsize = @filesize($filename)) {
             
$data = fread($fh, $fsize);
          } else {
             
$data = '';
              while (!
feof($fh)) {
                 
$data .= fread($fh, 8192);
              }
          }
 
         
fclose($fh);
          return
$data;
      }
  }
?>
php [spat] hm2k.org
16-Jan-2008 12:58
I decided to make a similar function to this, called file_post_contents, it uses POST instead of GET to call, kinda handy...

<?php
function file_post_contents($url,$headers=false) {
   
$url = parse_url($url);

    if (!isset(
$url['port'])) {
      if (
$url['scheme'] == 'http') { $url['port']=80; }
      elseif (
$url['scheme'] == 'https') { $url['port']=443; }
    }
   
$url['query']=isset($url['query'])?$url['query']:'';

   
$url['protocol']=$url['scheme'].'://';
   
$eol="\r\n";

   
$headers "POST ".$url['protocol'].$url['host'].$url['path']." HTTP/1.0".$eol.
               
"Host: ".$url['host'].$eol.
               
"Referer: ".$url['protocol'].$url['host'].$url['path'].$eol.
               
"Content-Type: application/x-www-form-urlencoded".$eol.
               
"Content-Length: ".strlen($url['query']).$eol.
               
$eol.$url['query'];
   
$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
    if(
$fp) {
     
fputs($fp, $headers);
     
$result = '';
      while(!
feof($fp)) { $result .= fgets($fp, 128); }
     
fclose($fp);
      if (!
$headers) {
       
//removes headers
       
$pattern="/^.*\r\n\r\n/s";
       
$result=preg_replace($pattern,'',$result);
      }
      return
$result;
    }
}
?>
francois hill
03-Dec-2007 05:56
Seems file looks for the file inside the current working (executing) directory before looking in the include path, even with the FILE_USE_INCLUDE_PATH flag specified.

Same behavior as include actually.

By the way I feel the doc is not entirely clear on the exact order of inclusion (see include). It seems to say the include_path is the first location to be searched, but I have come across at least one case where the directory containing the file including was actually the first to be searched.

Drat.
bearachute at gmail dot com
11-Jul-2007 11:38
If you're having problems with binary and hex data:

I had a problem when trying to read information from a ttf, which is primarily hex data. A binary-safe file read automatically replaces byte values with their corresponding ASCII characters, so I thought that I could use the binary string when I needed readable ASCII strings, and bin2hex() when I needed hex strings.

However, this became a problem when I tried to pass those ASCII strings into other functions (namely gd functions). var_dump showed that a 5-character string contained 10 characters, but they weren't visible. A binary-to-"normal" string conversion function didn't seem to exist and I didn't want to have to convert every single character in hex using chr().

I used unpack with "c*" as the format flag to see what was going on, and found that every other character was null data (ordinal 0). To solve it, I just did

str_replace(chr(0), "", $string);

which did the trick.

This took forever to figure out so I hope this helps people reading from hex data!
tobsn at php dot net
02-May-2007 06:26
you'll find the http response headers in: $http_response_header

;o)
Greg Ambrose (greg at catalina-it dot com dot au)
17-Apr-2007 06:37
[Editors note: As of PHP 5.2.1 you can specify `timeout` context option and pass the context to file_get_contents()]

The only way I could get get_file_contents() to wait for a very slow http request was to set the socket timeout as follows.

 ini_set('default_socket_timeout',    120);   
$a = file_get_contents("http://abcxyz.com");

Other times like execution time and input time had no effect.
siegfri3d at gmail dot com
05-Dec-2006 09:52
Use the previous example if you want to request the server for a special part of the content, IF and only if the server accepts the method.
If you want a simple example to ask the server for all the content, but only save a portion of it, do it this way:
<?
$content
=file_get_contents("http://www.google.com",FALSE,NULL,0,20);
echo
$content;
?>

This will echo the 20 first bytes of the google.com source code.
fcicqbbs at gmail dot com
04-Aug-2006 10:55
the bug #36857 was fixed.
http://bugs.php.net/36857

Now you may use this code,to fetch the partial content like this:
<?php
$context
=array('http' => array ('header'=> 'Range: bytes=1024-', ),);
$xcontext = stream_context_create($context);
$str=file_get_contents("http://www.fcicq.net/wp/",FALSE,$xcontext);
?>
that's all.
richard dot quadling at bandvulc dot co dot uk
15-Nov-2005 11:47
If, like me, you are on a Microsoft network with ISA server and require NTLM authentication, certain applications will not get out of the network. SETI@Home Classic and PHP are just 2 of them.

The workaround is fairly simple.

First you need to use an NTLM Authentication Proxy Server. There is one written in Python and is available from http://apserver.sourceforge.net/. You will need Python from http://www.python.org/.

Both sites include excellent documentation.

Python works a bit like PHP. Human readable code is handled without having to produce a compiled version. You DO have the opportunity of compiling the code (from a .py file to a .pyc file).

Once compiled, I installed this as a service (instsrv and srvany - parts of the Windows Resource Kit), so when the server is turned on (not logged in), the Python based NTLM Authentication Proxy Server is running.

Then, and here is the bit I'm really interested in, you need to tell PHP you intend to route http/ftp requests through the NTLM APS.

To do this, you use contexts.

Here is an example.

<?php

// Define a context for HTTP.
$aContext = array(
   
'http' => array(
       
'proxy' => 'tcp://127.0.0.1:8080', // This needs to be the server and the port of the NTLM Authentication Proxy Server.
       
'request_fulluri' => True,
        ),
    );
$cxContext = stream_context_create($aContext);

// Now all file stream functions can use this context.

$sFile = file_get_contents("http://www.php.net", False, $cxContext);

echo
$sFile;
?>

Hopefully this helps SOMEONE!!!
aidan at php dot net
31-Jan-2005 08:23
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat

file_put_contents> <file_exists
Last updated: Fri, 20 Jun 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites