HOME
PHP
Introduction Php Installation
PHP Basic Scripts
PHP variables
PHP operators
PHP Conditional statement
PHP functions
PHP Arrays
PHP Objects & classes
PHP with Forms
PHP Files
PHP With Database
PHP session
PHP cookies
PHP Regular Expressions
PHP Server Environment
PHP Graphics
PHP Advance
|
PHP File handling
Before yu can work with afile,you must first open it for reading,writing,or both.PHP provides the fopen()
function for this.fopen() require a string containing the file path,followed by a string containing the mode in which the file is to
be opened.The most common mode are read('r') and write('w') and append('a').
To open the file for reading you should use the following:
$fp=fopen("test.txt".'r');
To open the file for writing you should use the following:
$fp=fopen("test.txt".'w');
To open the file for appending you should use the following:
$fp=fopen("test.txt".'a');
Here is the simple example
Example
The following example generates a message if the fopen() function is unable to open the specified file:
Closing a File
The fclose() function is used to close an open file:
<?php
$file = fopen("test.txt","r");
?>
Reading a File Character by Character
The fgetc() function is used to read a single character from a file.
Note: After a call to this function the file pointer moves to the next character.
The example below reads a file character by character, until the end of file is reached:
| The file may be opened in one of the following modes:
| Modes |
Description |
| 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 |
|
|
|
|