File Open & Close

File Open & Close


Posted in : PHP Posted on : January 4, 2011 at 6:45 PM Comments : [ 0 ]

This section contains detail about the File Open & Close in PHP.

File Open & Close

In PHP, fopen function is used to open the file. For opening file we need two parameters :

First : The name of the file which you want to open.

Second : The mode in which you want to open the file.

Example :

<?php
$MyFileName = 'C:\myfile.txt';
$MyFileHandle = fopen($MyFileName, 'r') or die("cant open file");
fclose($MyFileHandle);
?>

The above code will open the file in read mode.

The list of the modes in which file can be open is given below :

File Modes  Details 
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 Append. Opens and writes to the end of the 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
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

Closing File

In PHP, fclose() method is used to close an open file. Given below the example code

<?php
$MyFileName = 'C:\myfile.txt';
$MyFileHandle = fopen($MyFileName, 'r') or die("cant open file");
fclose($MyFileHandle);
?>

In fclose() method, we pass the variable which holds the 'file handle'.

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics