How do I access and modify information in a file using PHP?

PHP also allows you full ability to read and write to files in your account. Files are opened via the fopen command, which is given in the form:

$FILE = fopen("filename","mode");

where $FILE is the variable you’ll use to refer to the open file, filename is the name of the file to be opened, and, mode determines level of access to the file using one of the following values:

  • r (read only)
  • r+ (read and write)
  • w (write only)
  • w+ (read and write, truncate file to 0 bytes)
  • a (write only, start at end of file – append)
  • a+ (read and write, starting at file end)

Once the file is opened, there are two commands to read in data. fgetc retrieves a single character, while fgets retrieves a number of bytes you specify. They are used in the following manner:

$ONECHAR = fgetc($FILE);
$TENBYTES = fgets($FILE,10);

If you need to write to the file, the function used is fputs:

fputs($FILE,"This text is written to the file");

After you are done interfacing with the file, you must close your file descriptor with the fclose command:

Fclose ($FILE);

The sample code below uses the file functions and a while loop to copy the contents of data.txt to newdata.txt (not particularly useful in “real life”, but good for demonstrative purposes).

/ open data.txt for reading
= fopen("/usr/home/username/data.txt","r");

// open newdata.txt for writing
$NEWFILE = fopen("/usr/home/username/newdata.txt","w");

// continously read in from data.txt
while ($BUFFER = fgets($FILE,4096)) {
// write line to newdata.txt

// close data.txt

// close newdata.txt

Please note that fopen is restricted to local files only.