You are on page 1of 10

Course Handout Student Notebook

Contents
Unit 5: P HP File Handling 2
Learning Objectives 2
Introduction 3
File Open 3
File Creation 3
Writing to files 4
Reading from Files 5
Closing a File 6
Using PHP with HTML Forms 7
Summary 9
Problems to Solve 10

Copyright IBM Corp. 2011 Course Contents 1


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
PHP Core Student Notebook

Unit 5: PHP File Handling


Learning Objectives

At the end of this unit, you will be able to

Understand the types of file manipulation in PHP.


List and make use of various functions that help to create, read and write disk files.
Know how to access information from the HTML page.

Copyright IBM Corp. 2011 Unit 5 PHP Basics 2


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

Introduction
Some applications require data to be available for several executions of the program, for example, data on
employees required by payroll applications. Data used in the programs have a lifetime only till the duration of the
program. They are stored in the RAM, and lose their value once the program terminates. Unless explicitly placed
in secondary storage devices, the data kept in variables is lost once the program is terminated.
PHP offers a large set of functions for storing the data permanently into files, and to perform manipulation like
appending the data into a file, to delete the contents present in the file etc.

File Open
Before performing any manipulation in the file, you should open it. Files are opened in PHP using the fopen
function. The function takes two parameters, the first is the name of the file and the second is the mode in which
it should be opened. The function returns a file pointer if successful, otherwise zero.
Example:
$fp=fopen(Employeedetails.txt, r);
Employeedetails.txt is the file which you are going to open and r denotes that the file has been opened in read
mode. If the file exits the function will return a file pointer else it will return 0.
The following table shows the different modes the file can be opened in.

Modes Description
r opens the file in read-only mode
w Write only. Opens and clears the contents of file; or
creates a new file if it doesn't exist
a Append. Opens and writes to the end of the file or
creates a new file if it doesn't exist
r+ Read and write if the file exists already , will write to
the beginning of the file
w+ Read/Write. Opens and clears the contents of file; or
creates a new file if it doesn't exist
a+ Read/Append. Preserves file content by writing to the
end of the file or creates a new file if it doesn't exist

File Creation
Before you can do anything with a file it has to exist. In PHP the fopen function is used to open files. However, it can
also create a file if it does not find the file specified in the function call. So if you use fopen on a file that does not
exist, it will create it, given that you open the file for writing or appending. For example:
$fp=fopen(Employeedetails.txt, w);
In the above code you have opened the file in the write mode, so if Employeedetails.txt file does not exist, it will
create a file.
Note: The fopen function is used for opening and creating a file.

3 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

Writing to files
Now that you know how to open a file, lets get on to the most useful part of file manipulation, writing. The fwrite
function is used to write a string, or part of a string to a file. The function takes three parameters, the file handle,
the string to write, and the number of bytes to write. If the number of bytes is omitted, the whole string is written
to the file. For example:
$fp=fopen("employeedetails.txt","w");
$name="john";
$id=123;
$address="Bangalore";
$salary=30000.56;
fwrite($fp,$name);
fwrite($fp,$id);
fwrite($fp,$address);
fwrite($fp,$salary);
The $fp variable contains the file handle for employeedetails.txt. The file handle knows the current file pointer, which
for writing, starts out at the beginning of the file.
What happens when you open an existing file for writing? For example, if you want to store another employees details
in the same file it can be written as:
$fp=fopen("employeedetails.txt","w");
$name="amit";
$id=124;
$address="Chennai";
$salary=30000.56;
fwrite($fp,$name);
fwrite($fp,$id);
fwrite($fp,$address);
fwrite($fp,$salary);
But here it will overwrite the previous contents, because you have opened the file in the write mode. As
mentioned earlier, in the write mode it opens and moves the file pointer to the starting position, so the new
content will overwrite the old one. If you read the contents from the employeedetails.txt file only amits
information will be available and John's information will be lost. In this case you can open the file in the append
mode, where it will open the file and moves the file pointer to the end of file. You can modify the above code as:
$fp=fopen("employeedetails.txt","a");
$name="amit";
$id=124;
$address="Chennai";
$salary=30000.56;

Copyright IBM Corp. 2011 Unit 5 PHP Basics 4


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

fwrite($fp,\r\n);
fwrite($fp,$name);
fwrite($fp,$id);
fwrite($fp,$address);
fwrite($fp,$salary);

Note: Windows requires a carriage return character as well as a new line character, so if you're using Windows,
terminate the string with \r\n.
If you want the lines to appear on separate lines in the file, use \n character. In the above example to
differentiate from one employee record with another one we have used \n. The contents inside the
employeedetails.txt will be
john123Bangalore30000.56
amit124Chennai35000

Reading from Files


Before we can read information from a file we have to use the function fopen to open the file for reading. You
can read from files opened in r, r+, w+, and a+ mode. The fread function is used for getting data out of a file. The
function requires a file pointer, which we have, and an integer to tell the function how much data, in bytes, it is
supposed to read. Let us see an example to read the contents from the employeedetails.txt file.

$fp=fopen("employeedetails.txt","r");

$content=fread($fp,7);

echo $content;

The output of the above code will be john123, since we have given the number of characters as 7. If you want to
read all the data from the file, then you need to get the size of the file. The filesize function is used to find the
length of a file, in bytes; you need to pass the filename as an argument to this function.

$fp=fopen("employeedetails.txt","r");

$content=fread($fp,filesize("employeedetails.txt"));

echo $content;
PHP also lets you read a line of data at a time from a file with the gets function. If you had separated your data with
new lines then you could read one segment of data at a time with the gets function.
$fp=fopen("employeedetails.txt","r");
$content=fgets($fp);
echo $content;
For the above code you will get the output;
john123Bangalore30000.56

5 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

If you want to read all the lines from the employeedetails.txt file using fgets:
while(!(feof($fp)))
{
$content=fgets($fp);
echo $content;
}
In the above code we have used the feof function in a while loop, to read from the file until the end of file is
encountered. The feof function is used to determine if the end of file is true.
You can read a single character at a time from a file using the fgetc function:
while(!(feof($fp)))
{
$ch=fgetc($fp);
echo $ch;
}
Searching a record from a file
The Preg_Match PHP function is used to search a string, and return 1 or 0. If the search was successful 1 will be
returned, and if it was not found 0 will be returned. The syntax:
preg_match(search_pattern, your_string)
The search_pattern needs to be a regular expression.
If you want to search only amits information from the employeedetails.txt file the following code can be used.
$fp=fopen("employeedetails.txt","r");
while(!(feof($fp)))
{
$content=fgets($fp);
if (preg_match('/amit/',$content))
echo $content."<br>";
}

Closing a File
Once you have opened a file and finished your business with it is necessary to close that file down. You don't
want an open file running around on your server taking up resources and causing mischief! The fclose() function
is used to close an open file.

$fp=fopen("employeedetails.txt","r");

$content=fread($fp,filesize("employeedetails.txt"));

echo $content;

Copyright IBM Corp. 2011 Unit 5 PHP Basics 6


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

fclose($fp);

Some of the file manipulation functions in PHP:

rewind()
The rewind function is used to move the file pointer to the beginning of the file.
fputs()
The fputs() function is an alias of the fwrite() function.
fprintf()
The fprintf() function writes a formatted string to a file.
fscanf()
The fscanf() function parses the input from an open file according to the specified format

Using PHP with HTML Forms


A very common application of PHP is to have an HTML form gather informat ion from a website's visitor and then
use PHP to process that information.
When a form is submitted to a PHP script, the information from that form is automatically made available to the
PHP script. Lets see an example of how to access information in the PHP page Customer.html

<html>
<body>
<form action="customer.php">
Name<input type="text" name="name"/><br />
Age<input type="text" name="age"/><br />
Gender:<input type="radio" name="gender" value="male"/> male
<input type="radio" name="gender" value="female"/> female <br />
Address <input type="text" name="address"/><br />
<input type="submit" value="save"/>
</form>
</body>
</html>

When you submit this form it will move on to the customer.php page. In this page we need to access the
information gathered in the customer.html file. Using $_GET and $_POST variables you can access the
information. Let us create the "customer.php" file which will process the HTML form information.
Customer.php
<?php
$name=$_GET["name"];
$age=$_GET["age"];
$gender=$_GET["gender"];
$address=$_GET["address"];

7 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

echo "Name:".$name."<br>";
echo "Age:".$age."<br>";
echo "Gender:".$gender."<br>";
echo "Address:".$address;
?>
We have used the $_GET variable to collect form data & the names of the form fields would automatically be the
keys in the $_GET array.
The predefined $_GET and _$POST variables are used to collect values in a form with method="get" and
method=post. Since we have not specified any method name, by default it would be GET.

Copyright IBM Corp. 2011 Unit 5 PHP Basics 8


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

Summary

Now that you have completed this unit, you should be able to:

Understand the types of file manipulation in PHP.

List and make use of various functions that help to create, read and write disk files.

Know how to access information from the HTML page.

9 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

Problems to Solve
1. Write a program to store the roll no, name, age, address, phone no of students into the file called
studentdetails.txt and the records should be stored in the format given below
101:priya:19:bangalore
102:prem:20:chennai
103:anu:18:chennai
104:john:21:bangalore
105:amit:20:mumbai
2. Write a function to retrieve the student information from the studentdetails.txt file.
3. Write a program to display all the students who belong to the city bangalore from the studentdetails.txt
file.
4. Write a program to copy the contents of studentdetails.txt to studentdetailsbackup.txt file.
5. Design a HTML page for getting the employee information such as name, age, gender, qualification.
Write a PHP script to access the employee information from the HTML page and store it in a file
employeeinfo.txt.

Copyright IBM Corp. 2011 Unit 5 PHP Basics 10


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.

You might also like