Page 1 of 1

Working with Files Rate Topic: -----

#1 PPDP  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 3
  • View blog
  • Posts: 38
  • Joined: 14-April 09

Posted 09 October 2010 - 04:33 AM

Working with Files
Flat files are simple to use, simpler than databases. You don't need any other software, such as database software. You just use PHP statements to read from or write to the file.

Using Flat Files require 3 steps:

1. Open the file
2. Write data into the file or retrieve data from the file.
3. Close the file.

Accessing Files
The first step, before you can write information or read information from a file, is to open the file. The following is the general format for the statement that opens a file:
$fh = fopen("filename","mode")


The variable, $fh, referred to as a file handle, is used in the statements that write data to or read data from the open file so that PHP knows which file to write into or read from. $fh contains the info that identifies the location of the open file.

You use a mode when you open the file to let PHP know what you intend to do with the file.

I will show you the different modes below:
  • r - Read Only - If the file does not exist, a warning message is displayed
  • r+ - Reading and writing - If the file does not exist, a warning message is displayed.
  • w - Write only - If the file does not exist, PHP attempts to create it. If the file exists, PHP overwrites it.
  • w+ - Reading and writing - If the file does not exist, PHP attempts to create it. If the file exists, PHP overwrites it.
  • a - Append data at the end of the file - If the file does not exist, PHP attempts to create it
  • a+ - Reading and appending - If the file does not exist, PHP attempts to create it


The filename can be a simple filename (filename.txt), a path to the file (c:/data/filename.txt), or a URL (http://yoursite.com/filename.txt)

Opening files in read mode


You can open the file file1.txt to read the info in the file with the following statement:
$fh = fopen("file1.txt","r");


Based on this statement, PHP looks for file1.txt in the current directory, which is the directory where your PHP script is located. If the file can't be found, a warning message, similar to the following, may or may not be displayed, depending on the error level.
Warning: fopen(file1.txt): failed to open stream: No such file or directory in c:\test1.php on line 15


Remember, a warning condition does not stop the script. The script continues to run, but the file does not open, so any later statements that read or write to the file aren't executed.

You probably want the script to stop if the file can't be opened. You need to do this yourself with a die statement, as follows:
$fh = fopen("file1.txt","r")
      or die(" Can't open file");

The die statement stops the script and the displays the specified message.

Opening files in write mode
You can open a file in a specified directory to store info by using the following type of statement:
$fh = fopen("c:/testdir/file1.txt","w");


If the file does not exist, it is created in the indicated directory. However, if the directory doesn't exist, the directory is not created, and a warning is displayed. (You must create the directory first, before you try to write a file into the directory.)

You can check whether a directory exists before you try to write a file into it by using the following statements:
If(is_dir("c/tester"))
{
      $fh = fopen("c:/tester/file1.txt","w");
}


With these statements, the fopen statement is executed only if the directory exists and is a directory.

Opening files on another Web site


ED NOTE: Requires allow_url_fopen to be "On" in the php.ini file.

You can also open a file on another Web site by using a statement such as the following:
$fh = fopen("http://example.com/index.html","r");

You can use a URL only with a read mode, not a write mode.

Closing a file
To close a file after you have finished reading or writing it, use the following statement:
fclose($fh);

In this statement, $fh is the file handle variable you created when you opened the file.

Writing to a file
After you open the file, you can write into it using the fwrite statement, which has the following general format:
fwrite($fh,datatosave);

In this statement, $fh is the file handle that you created when you opened the file, containing the pointer to open the file, and datatosave is the info to be stored in the file. The info can be a string or a variable. For example, you can use the following statements:
$today = date("Y-m-d");
$fh = fopen("file2.txt","a");
fwrite($fh,$today);
fclose($fh);


These statements store the current date in a file called file2.txt. Notice that the file is opened in append mode.If the file doesn't exist, it is created, and the date is written as the first line. If the file exists, the data is added to the end of the file. In this way, you create a log file, which stores a list of the dates on which you the script is run. The fwrite statement stores exactly what you send, so the second time these statements are run, file2.txt contains the following:
2010-10-092010-10-09

You probably want the two dates to be store on separate lines. To do so, use the following fwrite statement rather than the previous one:
fwrite($fh,$today . "\n");

With the new line character added, file2.txt contains the following:
2010-10-09
2010-10-09

Be sure to open the file with the a mode if you want to add info to a file. If you use a write mode, the file is overwritten each time it is opened.

Reading from a file

You can read from a file by using the fgets statement, which has the following general format:
$line = fgets($fh)

In this statement, $fh holds the the pointer to open the file. This statement reads the a string until it encounters the end of the line or the end of the file, whichever comes first, and stores the string in $line. To read an entire file, you keep reading lines until you get to the end of the of the file. PHP recognizes the end of the file, and provides a function feof to tell you when you reach the end of the file. The following statements read and display all the lines in the file:
while(!feof($fh))
{
  $line - fgets($fh);
  echo "$line;
}


In the first line , feof($fh) returns TRUE when the end of the file is reached. The exclamation point negates the condition being tested, so that the while statement continues to run as long as the end of the files is not reached. When the end of the file is reached, while stops.

If you use these statements to read the log file created you get the following output:
2010-10-09
2010-10-09



As you can see, the new line character is included when the line is read. In some cases, you don't want the end of the line included. If so, you need to remove it by using the following statements:
while(!feof($fh))
{
  $line = rtrim(fgets(fh));
  echo "$line;
}



The rtrim function removes any trailing blank spaces and the new line character. The output from these statements is as follows:
2010-10-092010-10-09



Reading files piece by piece
Sometimes you want to read strings of a certain size from a file. You ccan tell fgets to read a certain number of characters by using the following format:
$line = fgets($fh,n)


This statement tells PHP to read a string that is n-1 characters long until it reaches the end of the line or the end of the file.
For example, you can use the following statements:
while(!feof($fh))
{
   $char4 = fgets($fh,5);
   echo "$char4\n";
}


These statements read each four-character string until the end of the file. The output is as follows:
2010
-10-
09 

2010
-10-
09 


Notice that there is a new line at the end of each line of the file.

Reading a file into a array
It's often handy to have the entire file in an array. You can do that with the following statements:
$fh = fopen("file2.txt","r");
while(!feof($fh))
{
   $content[] = fgets($fh);
}
fclose($fh);


The result is the array $content with each line of the file as an element of the array. The array keys are numbers

PHP provides a shortcut function for opening a file and reading the entire contents into an array, one line in each element of the array. The following statement produces the same results as the preceding 5 lines:
$content = file("file2.txt")



The statement opens file2.txt, puts each line into an element of the array $content, and then closes the file.

The file function can slow down your script if the file you're opening is very large. How large depends on the amount of available computer memory. If your script seems slow, try reading the file with fgets rather than file and see if that speed up the script.

You can direct the file function to automatically open files in your include directory by using the following statement:
$content = file("file2.txt",1);



The 1 tell PHP to look for file2.txt in the directory rather than in the current directory.

Reading a file into a string
Sometimes it's useful to put the entire contents of a file into one long string. For example, you may want to send the file contents in an e-mail. PHP provides a function for reading a file into a string, as follows:
$content = file_get_contents("file2.txt",1);


The file_get_contents function works the same as the file function, except that it puts the entire contents of the file into a string rather than an array. After this statement, you can echo $content as follows:
echo $content;


The output is the following:
2010-10-09
2010-10-09


The output appears on separate lines because the end of line characters are read and stored as part of the string. Thus, when you echo the string, you also echo the end of line characters, which start a new line.

The file_get_contents function was introduced in version 4.3.0. It is not available in older versions of PHP.

Wrap up

So what did you learn in this tutorial:
How to open a file
Write data
Read data
Close the file
Different modes for reading and writing
Opening files from another Web site
Reading files piece by piece
Reading a file into an array

Hope you enjoyed ^^
PPDP's tutorial

This post has been edited by PPDP: 09 October 2010 - 10:26 PM


Is This A Good Question/Topic? 3
  • +

Replies To: Working with Files

#2 PPDP  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 3
  • View blog
  • Posts: 38
  • Joined: 14-April 09

Posted 09 October 2010 - 11:59 AM

Thanks JackOfAllTrades for adding that. I appreciate it. :D
Was This Post Helpful? 0
  • +
  • -

#3 grimpirate  Icon User is offline

  • Pirate King
  • member icon

Reputation: 149
  • View blog
  • Posts: 714
  • Joined: 03-August 06

Posted 09 October 2010 - 04:19 PM

My only critique is that the title is misleading. I would suggest something more along the lines of "Working with Files". A flat file typically denotes some sort of structured file that is used to hold particular data in a particular way as opposed to just a file that data is written to. Otherwise, nice work.
Was This Post Helpful? 1
  • +
  • -

#4 PPDP  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 3
  • View blog
  • Posts: 38
  • Joined: 14-April 09

Posted 09 October 2010 - 10:26 PM

View Postgrimpirate, on 09 October 2010 - 03:19 PM, said:

My only critique is that the title is misleading. I would suggest something more along the lines of "Working with Files". A flat file typically denotes some sort of structured file that is used to hold particular data in a particular way as opposed to just a file that data is written to. Otherwise, nice work.

Thanks GrimPirate Changed it, I appreciate it. :^:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1