PHP109

From mi-linux
Jump to navigationJump to search

Main Page >> Web Application Development >> Workbook >> File Handling

Text Files

A simple text file may be considered to be a database. It will be simple (flat), sequential, not secure and contain just plain ASCII text. However, as we can read and write to it on the server we can treat it as a database. We will look at storing simple information such as peoples names, email addresses etc, and in this sense use our text file as our database

Some of these are from Internet & World Wide Web - How to Program, Deitel, Deitel & Nieto (2002)

Opening Files - fopen

fopen stands for "file open", and is used to create a pointer to the file which we want to open for read/write access. It accepts 2 required and 2 optional parameters. Its syntax is shown below:

int fopen ( string filename, string mode [, int use_include_path [, resource zcontext]])

For example, let's say that we wanted to open a file called test.txt. We would use fopen like this:

<?php 
   $fp = fopen("test.txt", "r"); 
?>

IF YOU ATTEMPT THIS, you will likely get one of two errors

  • Error 1: the file does not exist - the example above is a read of an existing file, thus if the file does not exist, you'll get an error, so the obvious thing to do is create the file with some dummy content and run the script again, when you'll likely get...
  • Error 2: file permissions - see Troubleshooting PHP for information on file permission errors and how to solve them.

The $fp variable would now contain a pointer (or reference) to the test.txt file. The second parameter, "r", tells PHP that we want to open the file in read mode only -- we don't actually want to write to the file.

Open Modes

One-way file operations are quicker than 2 way operations (such as read+write access) because the location of the file pointer is uni-directional, i.e. it only has to travel down the file, and not jump from position to position.

There are 6 different file modes that we can use when working with files in PHP. They are shown below (courtesy of php.net):

  • 'r' - Open for reading only; place the file pointer at the beginning of the file.
  • 'r+' - Open for reading and writing; place the file pointer at the beginning of the file.
  • 'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
  • 'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
  • 'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
  • 'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

As you can see, PHP is very flexible when it comes to files. We can read a file, read and write to a file, append to the end of a file, move the file pointer to the bottom of the file automatically and more!

End of File - feof

Is the the function that we can use in PHP to determine whether or not we have reached the end of a file when we're reading it in. All file functions are prefixed with the character "f" in PHP, and EOF is an acronym for End-Of-File.

Feof is a simple function, and accepts just 1 parameter, as shown below:

int feof ( int fp) 

The parameter, fp, is a reference to a file pointer that contains the details of the file we're working with. Feof returns true if we're at the end of a file, and false if we're not.

Before we can see the feof function in action, we need to learn a bit about the fread function, which we will look at next.

Read from File - fgets & fread

In PHP there are 2 different functions that you can use to read in a file:

  • fgets
  • fread

The following two examples demonstrate the use of the fgets and the fread commands.

The fundamental difference between these two approaches is fgets grabs a line from the file, whereas fread grabs a certain amount of characters from the file.

BEFORE you attempt the next couple of exercises, create a file called "test.txt" in the same directory as the exercises, change the permissions to make it world-readable (see Troubleshooting PHP for information on how to do this) and put some content in the file - doesn't matter what.

  • fgets
<?php 
   $fp = fopen("test.txt", "r"); 
   $data = ""; 
   while(!feof($fp)) { 
     $data .= fgets($fp, 4096); 
   } 
   echo $data; 
?> 
  • fread
<?php
   $filename = "test.txt";
   $fp = fopen($filename, "r");
   $data = fread($fp, filesize($filename));
   echo $data;
?>

EXERCISE

OK, so now you know about the 4 functions that we need to open and then read-in the contents of a file:

  • fopen(),
  • foef(),
  • fread() and
  • filesize().


Create a text file called person.data and add the following lines to it:

Joe 
Bloggs 
22
M 

Create a file called getperson.php and add the following code to it (make sure you save it in the same directory as person.data):

<?php
   $filename = "person.data";
   $fp = @fopen($filename, "rb") or die("Couldn't open file"); 
   $data = fread($fp, filesize($filename)); 
   while(!feof($fp)) { 
     $data .= fgets($fp, 1024); 
   } 
   fclose($fp); 

   $values = explode("\n", $data); 
   // NOTE: if you create your data file on Windows you need to replace the line above with the one below
   // $values = explode("\r\n", $data); 

   echo "Name: " . $values[0] . " " . $values[1] . "<br>"; 
   echo "Age: " . $values[2] . "<br>"; 
   echo "Sex: " . $values[3]; 
?>

Writing to Files

By simply specifying "w" as the file mode, PHP will move the file pointer to the beginning of the file and truncate (cut-down) the file to zero length if that file already exists. If it doesn't exist, here's the good part - PHP will automatically create it for us!

So, how would we create a blank file using just the fopen command? Simple. Take a look:

<?php 
   $fp = fopen("newfile.file", "w") or die("Couldn't create file"); 
?>

That's really all there is to it. To actually output a value to the file, we need to use the fwrite function.

fwrite

fwrite simply writes the contents of a string to a file. The signature for the fwrite function looks like this:

int fwrite ( int fp, string string [, int length])

fwrite returns the number of bytes written on success, or false if an error occurs. The first parameter is the file pointer ($fp in all of our previous examples). The second parameter is the string that you want to write to the file, and the third optional parameter is the length of the string that will be output to the file.

If we wanted to output a simple sentence to a file, then we could do it like this:

<?php 
   $fp = fopen("newfile.file", "w") or die("Couldn't create file"); 
   $numBytes = fwrite($fp, "Hello, this is some text!"); 
   fclose($fp); 

   echo "Wrote $numBytes bytes to newfile.file!"; 
?>

If you get "Couldn't create file" errors, make sure the folder the PHP file is in has world-writable permissions - if the webserver cannot write to the folder, you cannot create the file.

Writing Options

  • 'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
  • 'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

Because we are only performing write operations on the file, we will use "a" (remember that it's quicker to use a unidirectional access method instead of a bi-directional one, such as read/write).

So, to append a sentence to the bottom of newfile.file, we could use this code:

<?php 
   $fp = fopen("newfile.file", "a") or die("Couldn't create new file"); 
   $numBytes = fwrite($fp, "\r\nLook, it's a brand new line!"); 
   fclose($fp); 

   echo "Wrote $numBytes bytes to the end of newfile.file!"; 
?>

The output from our PHP script shows how many bytes were written to newfile.file

Ready to move on?

Let's tackle this week's mini-task!