search for in the  
<file_put_contentsfileatime>
Last updated: Thu, 19 May 2005

file

(PHP 3, PHP 4, PHP 5)

file -- Reads entire file into an array

Description

array file ( string filename [, int use_include_path [, resource context]] )

Identical to readfile(), except that file() returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.

You can use the optional use_include_path parameter and set it to "1", if you want to search for the file in the include_path, too.

<?php
// Get a file into an array.  In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');

// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
   echo
"Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

// Another example, let's get a web page into a string.  See also file_get_contents().
$html = implode('', file('http://www.example.com/'));
?>

Tip: You can use a URL as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename and Appendix L for a list of supported URL protocols.

Note: Each line in the resulting array will include the line ending, so you still need to use rtrim() if you do not want the line ending present.

Note: If you are having problems with PHP not recognizing the line endings when reading files either on or created by a Macintosh computer, you might want to enable the auto_detect_line_endings run-time configuration option.

Note: As of PHP 4.3.0 you can use file_get_contents() to return the contents of a file as a string.

In PHP 4.3.0 file() became binary safe.

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CXXII, Stream Functions.

Warning

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To workaround this, you should lower your error_reporting level not to include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning for you. If you are using fsockopen() to create an ssl:// socket, you are responsible for detecting and suppressing the warning yourself.

See also readfile(), fopen(), fsockopen(), popen(), file_get_contents(), and include().



User Contributed Notes
file
camilokawerin(at)ciudad(dot)com(dot)ar
20-Mar-2005 06:46
This function allows to read configuration files like this:

[level_0]
     total=>8
     [level_1]
         1=3
     [/level_1]
     [level_1]
         [level_2]
             1=something
         [/level_2]
     [/level_1]
[/level_0]

where 'level_n' may be replaced by any label to create a tree structure. This is usefull to fill an array with all the values you need in one script.

$archivo="configuration.txt";
$resultado=file($archivo);
reset($resultado);
$n=0;
foreach ($resultado as $linea) {
if (ereg("^\[\/.*\]$", rtrim($linea))) {  //close labels
$n=$n-1; 
}
elseif (ereg("^\[.*\]$", trim($linea), $nombre)) {  //open labels
$n+=1;
$nivel[$n]=ereg_replace("(\[|\])", "", $nombre[0]);
}
elseif (($linea!="") and ($linea!="\n") and !ereg("(\/\*|\*\/)", $linea)) { //ignore empty lines and comments in '/* */' format
$pares=explode("=", trim($linea));  //separate key and value
for($i=$n; $i>0; $i--) { //fill the array
if ($i==$n) {${$nivel[$i]}[$pares[0]]=$pares[1]; }
else {${$nivel[$i]}[$nivel[$i+1]]=${$nivel[$i+1]}; }
}
$propiedades[$nivel[1]]=${$nivel[1]};
}
}
redzia
08-Feb-2005 09:55
Example usage of file to remove line containing a key string
<?

$key
= "w3ty8l";

//load file into $fc array

$fc=file("some.txt");

//open same file and use "w" to clear file

$f=fopen("some.txt","w");

//loop through array using foreach

foreach($fc as $line)
{
     if (!
strstr($line,$key)) //look for $key in each line
          
fputs($f,$line); //place $line back in file
}
fclose($f);

?>
Jason dot haymer at Haymer dot co dot uk
13-Jan-2005 10:58
Beware of using file() to call a URL from a remote server on a live Web site, as there is no way to set a maximum connection time.

To exemplify this I cite the circumstance of a Web site which receives content from a remote server in the form of an XML feed. If the remote server does not respond, the Web page will hang and if this is a regular occurance, the parts of the Web site which use the feed may often prove inaccessible to search engine robots, possibly resulting in their removal from the search engine indices.

Here is an alternative function which like file() can be used to retrieve a remote feed, but which imposes a maximum connection time, after which the page will be displayed without the feed.

<?

function fetchUrlWithoutHanging($url)
   {
  
// Set maximum number of seconds (can have floating-point) to wait for feed before displaying page without feed
  
$numberOfSeconds=4;   

  
// Suppress error reporting so Web site visitors are unaware if the feed fails
  
error_reporting(0);

  
// Extract resource path and domain from URL ready for fsockopen

  
$url = str_replace("http://","",$url);
  
$urlComponents = explode("/",$url);
  
$domain = $urlComponents[0];
  
$resourcePath = str_replace($domain,"",$url);

  
// Establish a connection
  
$socketConnection = fsockopen($domain, 80, $errno, $errstr, $numberOfSeconds);

   if (!
$socketConnection)
       {
      
// You may wish to remove the following debugging line on a live Web site
      
print("<!-- Network error: $errstr ($errno) -->");
       }   
// end if
  
else    {
      
$xml = '';
      
fputs($socketConnection, "GET /$resourcePath HTTP/1.0\r\nHost: $domain\r\n\r\n");
  
      
// Loop until end of file
      
while (!feof($socketConnection))
           {
          
$xml .= fgets($socketConnection, 128);
           }   
// end while

      
fclose ($socketConnection);

       }   
// end else

  
return($xml);

   }   
// end function

?>
rpanning at hotmail dot com
10-Jan-2005 02:50
A quick way to trim the array:
<?php
function file_trim(&$value, $key)
{
$value = trim($value); }

$file = file('name.txt');
@
array_walk($file, 'file_trim');
?>
corychristison[-At]lavacube(dot.)com
04-Jan-2005 08:56
Just realized that the function I posted above should have one small modification:

The line:
<?php
          
// add line to array, do an rtrim()
          
$open_data[$line] = rtrim(fgets($open, $buffer_size));
?>

Should probably be:
<?php
          
// add line to array, do an rtrim()
          
$open_data[$line] = rtrim(fgets($open, $buffer_size), "\n");
?>
corychristison[-At]lavacube(dot.)com
22-Dec-2004 07:52
The file function will load the entire file before you can do anything to it [remove lines, explode() each line, and so on...]

I wrote a function [ file_v2() ] to help eliminate the restrictions of file(). Below are a few features/abilites file_v2() has over file().

file_v2() features:
 - uses an editable buffer size, for performance tweaking.
 - ability set maximum lines returned[from beginning]
 - optional automatically rtrim the line
 - optional ability to provide a callback function for each array element

Here is the code:

<?php

function file_v2 ( $filename, $return_max_lines=0, $callback_func=null, $do_rtrim=true, $buffer_size=1024 )
{

  
// open file pointer
  
$open = fopen( $filename, 'rb' );

  
// start an array [good coding practice]
  
$open_data = array();

  
// start an internal line counter [good coding practice]
  
$line=0;

  
// begin the loop
  
while( !feof($open) )
   {
       if(
$do_rtrim )
       {
          
// add line to array, do an rtrim()
          
$open_data[$line] = rtrim(fgets($open, $buffer_size));
       }
       else
       {
          
// add line to array
          
$open_data[$line] = fgets($open, $buffer_size);
       }

       if(
$callback_func != null && function_exists( $callback_func ) )
       {
           eval(
$callback_func . '($open_data[$line]);');
       }

      
// +1 to the internal line counter
      
$line++;
      
       if(
$return_max_lines > 0 )
       {
           if(
$line >= $return_max_lines )
           {
               break;
           }
       }
   }

  
// close the file pointer
  
fclose($open);

  
// return the data
  
return $open_data;
}

?>

Example usage:

=========
file_test.txt
=========
01    firstname_1    lastname_1    fake_email@fake_addr1.fk
02    firstname_2    lastname_2    fake_email@fake_addr2.fk
03    firstname_3    lastname_3    fake_email@fake_addr3.fk
04    firstname_4    lastname_4    fake_email@fake_addr4.fk
05    firstname_5    lastname_5    fake_email@fake_addr5.fk
06    firstname_6    lastname_6    fake_email@fake_addr6.fk
07    firstname_7    lastname_7    fake_email@fake_addr7.fk
08    firstname_8    lastname_8    fake_email@fake_addr8.fk
09    firstname_9    lastname_9    fake_email@fake_addr9.fk
10    firstname_10    lastname_10    fake_email@fake_addr10.fk
11    firstname_11    lastname_11    fake_email@fake_addr11.fk
12    firstname_12    lastname_12    fake_email@fake_addr12.fk

=========
test.php
=========
<?php

// we will assume the function is in here somewhere

// create a callback function
function mk_callback( &$input )
{
  
$input = explode("\t", $input);
}

$open = file_v2('file_test.txt', 3, 'mk_callback');

// output array using print_r()
print_r($open);

?>

Example will output:
Array
(
   [0] => Array
       (
           [0] => 01
           [1] => firstname_1
           [2] => lastname_1
           [3] => fake_email@fake_addr1.fk
       )

   [1] => Array
       (
           [0] => 02
           [1] => firstname_2
           [2] => lastname_2
           [3] => fake_email@fake_addr2.fk
       )

   [2] => Array
       (
           [0] => 03
           [1] => firstname_3
           [2] => lastname_3
           [3] => fake_email@fake_addr3.fk
       )

)

This is one of my few contributions to this fine world.
Happy coding everybody!

   - Cory Christison
thecelestialcelebi^hotmail$com
03-Oct-2004 02:33
<?php
$textfile
= "Includes/Quotes.txt";      //quotes file
if ($quotes = @file("$textfile")) {    //don't display errors on file open
  
$quote = rand(0, sizeof($quotes)-1);
   echo
$quotes[$quote];                //echo a random quote
}else{
   echo (
"default quote");          //if quotes file wasn't found, echo out a default quote
}
?>

Why all those variables? :x

<?php
$sTextfile
= "Includes/Quotes.txt";      //quotes file
if ($aQuotes = @file($sTextfile)) { // NO VARIABLES INSIDE QUOTES  //don't display errors on file open
  
echo $aQuotes[array_rand($aQuotes)];                //echo a random quote
}
else
{
   echo
'blaat';
}
?>
andyg at stingrayboats dot com
21-Jul-2004 03:27
i tried for quite sometime to get my pdf to attach right some of you may want to try reading it as binary first then base 64 it.

//this did not work for me with a pdf file it came in garbled
$data = chunk_split(base64_encode(implode("", file($filelocation))));
//but tis seemed to make it work correctly
$data = fread($file,filesize($filelocation));
   fclose($file);
   $data = chunk_split(base64_encode($data));
kangaroo232002 at yahoo dot co dot uk
18-Jun-2004 07:03
Instead of using file() for parsing ini / conf files, as shown in mvanbeek at supporting-role dot co dot uk's example below (above?), a great function that puts all your conf info into an associative array is parse_ini_file($filename); very useful !

ian.
J at TIPPELL dot com
12-Jun-2004 09:18
heres a little script to return a random quote from a quotes file.

<?php
$textfile
= "Includes/Quotes.txt";      //quotes file
if ($quotes = @file("$textfile")) {    //don't display errors on file open
  
$quote = rand(0, sizeof($quotes)-1);
   echo
$quotes[$quote];                //echo a random quote
}else{
   echo (
"default quote");          //if quotes file wasn't found, echo out a default quote
}
?>
lance at lancemiller dot org
14-Apr-2004 12:55
This is just a presentation idea extending the php example.
Anchor links as line numbers and the document in a table data
field of it's own so it can be easily copy/pasted.
<?php
$lines
=file("http://www.example.com");
echo
"<table border=1><tr><td>\n";
foreach (
$lines as $line_num => $line) {
echo
"<a name=".$line_num."><a href=\"#".$line_num."\">".$line_num."</a><br>\n";
}
echo
"</td><td>\n";
foreach (
$lines as $line_num => $line) {
echo
htmlspecialchars($line)."<br />\n";
}
echo
"</td></tr></table>\n";
?>
http://iubito.free.fr
29-Feb-2004 02:09
Another way to do mvanbeek at supporting-role dot co dot uk (31 december) config reader.

I've an array $config
<?php
   $array_tmp
= file('configfile.txt');
   foreach(
$array_tmp as $v)
   {
       if ((
substr(trim($v),0,1)!=';') && (substr_count($v,'=')>=1))
       {
//Line mustn't start with a ';' and must contain at least one '=' symbol.
          
$pos = strpos($v, '=');
          
$config[trim(substr($v,0,$pos))] = trim(substr($v, $pos+1));
       }
   }
   unset(
$array_tmp);
?>

The configfile :
   variable  =    value
will be loaded into $config['variable'] = 'value';
it trims spaces near the '=', don't read lines starting with a ';' (it can have spaces and tabs before the ';' ).

Have a nice day :)
skipjack at skipjack dot info
12-Feb-2004 04:45
this a little function I wrote that checks if two ascii files are the same.
it opens the file then removes the spaces then coverts the crc32 to base 10 and compares the results.
function fcheck($tool)
{    if(fopen("file.01", "r") != FALSE){
   $fp1 = 'file.02';
   $fp = 'semcond.01';

   $data = implode(" ", file($fp));
   $data1 = implode(" ", file($fp1));
   $test1 = (dechex(crc32($data)));
   $test2 = (dechex(crc32($data1)));
     if($test1 == $test2)
         $sfv_checksum = 'TRUE';
           else
             $sfv_checksum = 'FALSE';
         return $sfv_checksum;
   }

}
mvanbeek at supporting-role dot co dot uk
31-Dec-2003 11:39
I needed a cross platform config file for a project using both perl and php, so I used the perl script in the Perl Cookbook, and wrote the following PHP script. This going in an include file that all the PHP files reference, so the only thing that needs to be do for set up, is to set the location of the config file.

$filename = "/opt/ssis/includes/ssis-config";
$config = file($filename);
reset ($config);
foreach ($config as $line)
     {
     if ( $line == "" ) next($config);          # Ignore blankline
     elseif ( $line == "\n" ) next($config);      # Ignore newline
     elseif ( strstr($line,"#")) next($config); # Ignore comments
     else
         {
         $line = rtrim($line);  # Get rid of newline characters
         $line = ltrim($line);  # Get rid of any leading spaces
         $value = preg_split("/\s*=\s*/", $line, 2); # split by "=" and removing blank space either side of it.
         ${Settings}["$value[0]"] = $value[1]; # Create a new array with all the values.
         }
     }

I am sure there is a neater way of doing it, but all the Config libaries floating arround seemed very complicated. All the config file needs is a series of lines ( key = value ) in plain text.
global-thenumberafterzero at nospam dot web dot de
30-Oct-2003 09:21
If you want a more powerful tool to open files you may want to use the curllib functions. If curllib is installed on your Server it is probably the best (but not fastest) tool for opening files. More information you can find here:

http://curl.haxx.se
or on php.net:
http://de.php.net/manual/de/ref.curl.php
dir @ badblue com
12-Sep-2003 04:48
Jeff's array2file function is a good start; here are a couple of improvements (no possibility of handle leak when fwrite fails, additional capability of both string2file and array2file; presumably faster performance through use of implode).

function String2File($sIn, $sFileOut) {
  $rc = false;
  do {
   if (!($f = fopen($sFileOut, "wa+"))) {
     $rc = 1; break;
   }
   if (!fwrite($f, $sIn)) {
     $rc = 2; break;
   }
   $rc = true;
  } while (0);
  if ($f) {
   fclose($f);
  }
  return ($rc);
}

function Array2File($aIn, $sFileOut) {
  return (String2File(implode("\n", $aIn), $sFileOut));
}

If you're generating your string text using a GET or POST from a TEXTAREA (e.g., a mini-web-text-editor), remember that strip_slashes and str_replace of "/r/n" to "/n" may be necessary as well using these functions.

HTH --dir @ badblue com
hhw
23-Aug-2003 10:43
The following function can handle text files whose line endings are whatever <LF> (*nix), <CR><LF> (M$) or <CR> (Mac)

function file2($filename) {
       $fp = fopen($filename, "rb");
       $buffer = fread($fp, filesize($filename));
       fclose($fp);
       $lines = preg_split("/\r?\n|\r/", $buffer);
       return $lines;
}
John
20-Jul-2003 06:32
after many months of confusion and frustration, i have finally figured out something that i should have noticed the first time around.

you can't file("test.txt") when that same file has been flocked. i guess i didn't have a full understanding of what i was doing when i used flock(). all i had to do was move the flock() around, and all was well.
webmaster AT the-afterburner DOT de
25-Mar-2003 06:35
If you want to send a URL via GET to a script and want to open this URL via file() there are problems if there is a & sign in the URL, all after die & sign is cut.

TO fix this an get it working with the & sign in the URL

@$myopenedcontent= implode("", file ("$url"));
$myopenedcontent=eregi_replace('&','{KU}',$myopenedcontent);

so all & signs are replaced by {KU}

before use the file() function you have to rereplace it, the whole code:

$url=eregi_replace('{KU}','&,$url);
@$myopenedcontent= implode("", file ("$url"));
$myopenedcontent=eregi_replace('&','{KU}',$myopenedcontent);
echo "$myopenedcontent";

hope it is helpful ;)

Bye
Afterburner
justin at visunet dot ie
20-Mar-2003 11:36
Note: Now that file() is binary safe it is 'much' slower than it used to be. If you are planning to read large files it may be worth your while using fgets() instead of file() For example:

$fd = fopen ("log_file.txt", "r");
while (!feof ($fd))
{
   $buffer = fgets($fd, 4096);
   $lines[] = $buffer;
}
fclose ($fd);

The resulting array is $lines.

I did a test on a 200,000 line file. It took seconds with fgets()  compared to minutes with file().
gaurav_saparia at yahoo dot com
17-Mar-2003 04:47
<?
$headers
= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: $sendername <$senderemail>\r\n";

$contents = implode("",file("newsletter.htm") );
echo(
$contents);

$a_list = array() ;
 
$a_list = file("mail_list.txt") ;
echo(
"<h6>Total ".count($a_list)." email addresses found in the list </h6><br>") ;
$cnt = 0 ;
for(
$i=0 ;$i<count($a_list) ; $i++)
{
  
$cnt ++ ;
           echo(
$cnt . "....sending mail to ".$a_list[$i] ."....") ;
          
mail($a_list[$i],$sub,"$contents","$headers");
       echo(
"Done .....<br>");
}
?>
03-Mar-2003 04:16
You can use file with https if you go to:

http://ftp.proventum.net/pub/php/win32/misc/openssl/.

This is instead of using the php_openssl.dll, so be sure to comment this extension in your php.ini.
akaylaa at yahoo dot com
06-Dec-2002 01:01
a quick way to count the number of lines in a file is

 $lines = file ('filename');
 $num_lines = count ($lines);

echo ("Total lines in file: " . $num_lines);
e dot maccarthy at csuohio dot edu
02-Jun-2002 05:04
[[Editors note: using fopen/fgets instead of file() would be more efficient for this task as there is no need to load the entire file into memory]]

Here is a quick snippet that will read in N number of lines of a file, then print them.

$n=10
$fp = file('/path/to/your/file');
$i=0
while($i < $n){
           echo "$fp[$i]";
           $i++;
}

I am using this right now to display the current progress of the seti@home client working on my server, instead of displaying the whole thing, which isn't web page friendly.
Because sometimes short really is sweet...
andrea at brancatelli dot it
16-Mar-2002 01:16
file() has a strange behaviour when reading file with both \n and \r as line delimitator (DOS files), since it will return an array with every single line but with just a \n in the end. It seems like \r just disappears.

This is happening with PHP 4.0.4 for OS/2. Don't know about the Windows version.
php@don't_spam_me
09-Feb-2002 02:56
It appears that the file() function causes file access problems for perl cgi scripts accessing the same files.  I am using Perl v5.6.0 in linux with PHP/4.0.4pl1.  After running a php app using the file() function, any perl cgi trying to access the same file randomly dies returning an internal server error: premature end of script headers.

The simple fix is to use fopen(), fgets() and fclose() instead of file().

<file_put_contentsfileatime>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT