Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index

PHP Script Tips - Reading and Writing Files

By: FYICenter.com

Part:   1  2   3  4 

(Continued from previous part...)

How To Append New Data to the End of a File?

If you have an existing file, and want to write more data to the end of the file, you can use the fopen($fileName, "a") function. It opens the specified file, moves the file pointer to the end of the file, and returns a file handle. The second argument "a" tells PHP to open the file for appending. Once the file is open, you can use other functions to write data to the file through this file handle. Here is a PHP script example on how to use fopen() for appending:

<?php 
$file = fopen("/temp/cgi.log", "a");
fwrite($file,"Remote host: 64.233.179.104.\r\n");
fclose($file); 
$file = fopen("/temp/cgi.log", "a");
fwrite($file,"Query string: cate=102&order=down&lang=en.\r\n");
fclose($file); 
?>

This script will write the following to the file:

Remote host: 64.233.179.104.
Query string: cate=102&order=down&lang=en.

As you can see, file cgi.log opened twice by the script. The first call of fopen() actually created the file. The second call of fopen() opened the file to allow new data to append to the end of the file.

How To Read One Line of Text from a File?

If you have a text file with multiple lines, and you want to read those lines one line at a time, you can use the fgets() function. It reads the current line up to the "\n" character, moves the file pointer to the next line, and returns the text line as a string. The returning string includes the "\n" at the end. Here is a PHP script example on how to use fgets():

<?php 
$file = fopen("/windows/system32/drivers/etc/services", "r");
while ( ($line=fgets($file)) !== false ) {
  $line = rtrim($line);
  print("$line\n");
  # more statements...
}
fclose($file); 
?>

This script will print:

# This file contains port numbers for well-known services

echo                7/tcp
ftp                21/tcp
telnet             23/tcp
smtp               25/tcp
...

Note that rtrim() is used to remove "\n" from the returning string of fgets().

How To Read One Character from a File?

If you have a text file, and you want to read the file one character at a time, you can use the fgetc() function. It reads the current character, moves the file pointer to the next character, and returns the character as a string. If end of the file is reached, fgetc() returns Boolean false. Here is a PHP script example on how to use fgetc():

<?php 
$file = fopen("/windows/system32/drivers/etc/services", "r");
$count = 0;
while ( ($char=fgetc($file)) !== false ) {
  if ($char=="/") $count++;
}
fclose($file); 
print("Number of /: $count\n");
?>

This script will print:

Number of /: 113

Note that rtrim() is used to remove "\n" from the returning string of fgets().

(Continued on next part...)

Part:   1  2   3  4 


Selected Developer Jobs:

More...