Open Source Tutorials - Open Source Training
Open source training & tutorials from experienced, passionate people
chrome icon firefox icon ie icon opera icon safari icon Sings in these Browsers
A- A A+

By A Web Design

pdf icons text icons

Read And Write To A File Using PHP

Reading A File

Focus: To open a text file and read some of the file values into memory variables

Solution 1:

To open a file in PHP the built in method - fopen() can be used. fopen() takes four arguments, three required and one optional, they are:
The name of the file to be opened
The file access type i.e. Read or Write access,
The path to the file
And
Optionally - The context of the file handle

Syntax : fopen(filename, mode, include_path, context)

filename : Specifies the file or URL to open. This is required.

mode : Specifies the type of access you require to the file/stream. This is required.
             Possible values:

  • "r" (Read only. Starts at the beginning of the file)
  • "r+" (Read/Write. Starts at the beginning of the file)
  • "w" (Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist)
  • "w+" (Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist)
  • "a" (Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist)
  • "a+" (Read/Write. Preserves file content by writing to the end of the file)
  • "x" (Write only. Creates a new file. Returns FALSE and an error if file already exists)
  • "x+" (Read/Write. Creates a new file. Returns FALSE and an error if file already exists)

NOTE: You can use 'b' to force binary mode. To use these translation flags, specify either 'b' or 't' as the last character of the mode parameter.

fopen() requires a file handle, and an integer to tell the function how much data, in bytes, that must be read.

Once the file is open, fread() can be used to read content from within the file.

Syntax : fread(file, length)

file : Specifies the open file to read from. It is required.

length : Specifies the maximum number of bytes to read. It is required.

If you opened the file using fopen() then you have to close it using fclose(). The fclose () function takes one argument, the name of the file to close.

Syntax : fclose(file)

file : Specifies the name of the file to close. It is required.

For Example:

diagram1.png

Focus:  Placing lines of extracted text into an array.

In the technique below, explode( ) a built in PHP string function is used to create an array from each line of text contained within a text file.

diagram2.png

A Short Decomposition:

This is because each line in the example.txt file looks like this:
AAS = Alive and smiling

$parts = explode(‘=’, $line_of_text);

explode() splits a line of text, based on whatever has been provided as the separator.

In the codespec above, the equals sign ( = ) is used as the separator.

When explode() executes, the variable $parts will be an array.  The text file contains two values separate by the = sign.  Each will then become a position in the array.

Then both parts of the array are printed out:

print $parts[0] . $parts[1]. "<br />";

$parts[0] will hold the abbreviation (AAS) and $parts[1] will hold the sting Alive and smiling.

The next time round the while loop, the second line will be read from the text file.

Exactly the same thing happens. The line will be split again, and placed into the array.

This is a good technique to use, if each line must be split something different done with each part of the line.

Write Into A File

Focus: To open a text file and write text into the file

Solution 1:

The built in PHP method fopen() is used to open a text file.

We can easily write text into such a file using fwrite(). However, ensure that the file is opened in write mode before attempting to write to it.

The fwrite() function takes three arguments, they are:
The file handle
The string to be written
Optionally - The number of bytes to be written

Syntax: fwrite(file, string, length)

$handle – the file stream

$string – string to be written in file

$length – optional. Number of bytes to write in file.

For Example:

diagram3.png

Focus: To parse data in a file and overwrite a small part of text in a file with new text

Most often you will find yourself reading and writing to a file at the same time. The example below shows you how to parse data in a file i.e. read file line by line and overwrite a small part of text in a file with new text.

For our example below we will assume we have filename “studentinfo.txt” which contains the following information.

Student Name: Prerna
Student ID: BE12
Student GPA: 2.9

What we want to do is update the Student GPA from 2.9 to 3.9. Here is how we do it.

First open the file in both read and write mode using "r+".  Next, read the file line by line using fgets()until the Student GPA line is reached. Then use the string replace function to replace 2.9 with 3.9. Then write the new string back to the file.  Here is the code spec.

diagram4.png
diagram5.png

Output

Student Name: Prerna
Student ID: BE12
Student GPA: 3.9

Application Configuration

PHP applications come in many shapes and sizes. Some can be used locally from the command line, but more commonly, PHP codespec in used in web based applications.

More often than not, regardless of size or type, some form of configuration variables will be stored for global access. Usually these configuration options are held in one of these four types of containers.

  • ini file
  • XML file
  • PHP file
  • Contents of a database table

Each option has its pros and cons. For example, let’s consider .ini file.

The ini File

The ini(tialization) file has been around for many years and has come to be a pseudo standard among application developers for initializing data variables.

Even PHP uses the php.ini file to initialize many configuration options within PHP itself.  Its really a great advantage to have a single text file to edit, however, shell access is required to do so, or the file can be edited locally and then uploaded to the server. More advanced component libraries such as eZ Components have a built in ini file class to help read and write to .ini files.

Most applications that use an ini file for configuration use the PHP parse_ini_file() function to get values from the ini file. Many classes and abstractions have been written to provide an Object Oriented approach, but the core remains the single PHP function to gain access to the values within an ini file using PHP. The simple syntax of the ini file makes it - easy to read and simple to edit. The reason it has been around so long is due to this simplicity.

Here is an example of an ini file.
;
; This is a comment
;
[database]
db_username = username
db_password = password
db_host = localhost
db_port = 1234

[mail]
mail_username = username
mail_password = password
mail_host = mail.example.com

[blog]
blog_title = "My Blog"
blog_moderate = 1
blog_images = 1

To parse the example ini file, simply save it as config.ini and to parse it, as mentioned earlier, the PHP parse_ini_file() function is used.

diagram6.png

This simple script above reads the ini file into a multi-dimensional array for easy retrieval. The array looks like this

diagram7.png

Focus: Retrieving And Modifying Information within the Multidimensional Array

Most often you will find yourself reading and writing to a file at the same time. The example below shows you how to parse data in a file i.e. read file line by line and overwrite a small part of text in a file with new text.

For our example below we will assume we have filename config.ini which contains the following information.

[database]
db_username = username
db_password = password
db_host = localhost
db_port = 1234
..
..

What we want to do is update the db_password from password to newpasswd. Here is how we do it.

First open the file in both read and write mode using "r+".  Next, read the file line by line using fgets()until the db_password line is reached. Then use the string replace function to replace password with newpasswd. Then write the new string back to the file.  Here is the code spec.

diagram8.png
diagram9.png

Output:

[database]
db_username = username
db_host = localhost
db_port = 1234
..
..
db_password = newpasswd
OSV Newsletter


Receive HTML?

NOTE: To prevent subscription to the OSV newsletter, uncheck the checkbox above.
Guest Blog for OSV
Free Ebook Download
LinkShare_180x150
Artisteer - DNN Skin Generator
Tapestry Theme - A Tumblog-Style Theme for Wordpress