Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Working with file handling in PHP

This article will discuss about file handling (opening, reading, writing, closing) in php.

Today, we are going to learn about file handling (opening, reading, writing, closing) in php

Introduction

File handling is a very important part of any web application. Many times you need to open a file and process the file according to the specific requirement. Php provide you function to do these functions on file simply. You may open file in mode which is most applicable.

First we need to know about the available file format so that we are comfortable while coding

  1. r -> Open the file in read only mode. With this mode you are only allowed to read and no editing is allowed
  2. w -> Open the file in write mode. You are allowed to write in the file
  3. r+ - > It will open file in read/write mode. The pointer is placed at file beginning and data is not truncatedw+ - > It will open file in read/write mode. The file content is truncated to length 0 and pointer is placed to beginning of file. It will create a new file if one does not exist.
  4. a -> It appends data to end of file contents.If file does not exist then one is created.
  5. a+ -> It open the file in read/append mode. It also write data at end of file contents
  6. x -> Creates a new file in write mode. Throws error if file already exist.
  7. x+ -> Open file Read/Write mode. It also create file and throw error in case file already exist

Now we will discuss about operation on the files:

First we make a temporary file on which we are going to perform several file operations

Listing 1: myfile.txt

File handling is easy to do

Opening a file

Listing 2: Opening file(myfile.txt)

<html>
<head>
	<title>MrBool Development Tutorial</title>
</head>
<body>
	<?php
	if(!file_exists("myfile.txt")) {
    		die("File was not found");
		}else{
    		$file=fopen("myfile.txt","r");
	}
?> 
</body>
</html>

The above code will display nothing(in case file is found) and will open the file in read only mode. Firstly we check if the file “myfile.txt exists or not. If it does not exist then we use the die function to show the error and stop the script from further execution, otherwise we open the file.

We used the fopen function to open the file. The two argument passed are the name of file and the mode in which you want to open this file. In this case we opened the file in Read only mode.

Closing a file

We should always close all the active connections when there requirement is over. We show this in below example :

Listing 3: Closing file(myfile.txt)

<html>
<head>
	<title>MrBool Development Tutorial</title>
</head>
<body>
<?php
	if(!file_exists("myfile.txt")) {
    	die("File was not found");
	}else{
    	$f=fopen("myfile.txt","r");
    	//File operations codes
    	//Closing file connection
    	fclose($f);
	}
?> 
</body>
</html>

We followed the earlier example. We just closed the file connection making use of fclose function. We passed the object f(containing reference for the file we opened) to the fclose function.

Reading a file

We will discuss a simple example which will read the lines in our file and display that on screen

Listing 4: Reading file(myfile.txt)

<html>
<head>
	<title>MrBool Development Tutorial</title>
</head>
<body>
<?php
	if(!file_exists("myfile.txt")) {
	    die("File was not found");
	}else{
	    $f = fopen("myfile.txt", "r");
	    while(!feof($f)) {
	        echo fgets($f). "<br />";
	    }
	    fclose($f);
} 
</body>
</html>
?>

First we check if file exist or not. If not we show the error and stop the script, if file is there then we open the file in read only mode and save the reference in an object called $f.

We use the feof method to determine the end of file and pass the variable $f containing reference to our file. This is placed inside a while loop, so that the while loop executes until the end of file “myfile.txt” is reached.

Inside while loop we use the gets method to obtain the single line and then we show that on screen using the echo method after this we simply close the file.

In above example we read the file line by line. We can also read the file character by character. Suppose in same file we want to show the file content such that every letter “I” is removed.

Listing 5: Reading file(myfile.txt)(character by character)

<?php
if(!file_exists("myfile.txt")) {
    die("File was not found");
}
else {
    $f = fopen("myfile.txt", "r");
    while(!feof($f)) {
        $read=fgetc($f);
        if($read!='i')
            echo $read;
    }
    fclose($f);
}
?>
  1. We checked if file exist or not. Show error message in case it don’t exist
  2. If the file exist we read the file in read only mode and store the reference in the variable named $f.
  3. We start reading the file until end of file is reached.
  4. We use the fgetc method to read a character.
  5. We read the character and store that in a variable named $read
  6. Now we check whether the letter we read is ‘I’ or not. If it is not ‘I’ then we display that on the screen otherwise move to next character.
  7. At last we close the connection.
Writing to the file

Listing 6: Writing to file(myfile.txt)

<?php
if(!file_exists("myfile.txt")) {
    die("File was not found");
}
else {
    $f = fopen("myfile.txt", "w");
    fwrite($f,"It is easy to write in a file");
    fclose($f);
}
?>
  1. Like earlier we check if file exist or not. If not, show the error.
  2. If file exist, we open the file in write mode. The reference is stored in a variable named $f.
  3. We use the fwrite method to write to the file. It accepts two argument here.
  4. The first argument will take the name of object containing reference of file.
  5. The second variable will contain the data to be written in file
  6. In this case since we opened the file in write mode so the previous data is truncated and the new data is written
  7. After this we will close the file

This is all for this article. Hope you liked it. See you next time.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login