Week 03 Lec 02 File Handling
Week 03 Lec 02 File Handling
02
SADAM HUSSAIN
File Handling
Manipulating Files
readfile() Function
The readfile() function reads a file and writes it to the output
If we have a text file called “abc.txt", saved on the server:
File Handling
Manipulating Files
PHP code to read the file and write it to the output buffer
is as follows (the readfile() function returns the number of
bytes read on success
<?php
echo readfile(“abc.txt");
?>
File Open/Read/Close
PHP Open File - fopen()
This function gives you more options than the readfile() function
<?php
$myfile = fopen(“abc.txt", "r") or die(“Can not open file");
echo fread($myfile,filesize("abc.txt"));
fclose($myfile);
?> // or use fopen("c:\\folder\\abc.txt", "r");
The first parameter of fopen() contains the name of the file to
be opened and the second parameter specifies in which mode
the file should be opened.
The following example also generates a message if the fopen()
function is unable to open the specified file
File Open/Read/Close
PHP Open File - fopen()
The file may be opened in one of the following modes
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts
at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a
new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts
at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a
new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
File Open/Read/Close
Read Single Line - fgets()
The fgets() function is used to read a single line from a file
$txt = “Welcome\n";
fwrite($myfile, $txt);
fclose($myfile);
File Create/Write
Append Text : using the "a" mode.
The "a" mode appends text to the end of the file, while the
The "w" mode overrides (and erases) the old content of the file
fclose($myfile);