Files in PHP
Files in PHP
Files in PHP
Append: 'a'
Open a file for write only. However, the data in the file is preserved and
you begin writing data at the end of the file.
The file pointer begins at the end of the file.
‘x’ - Write only. Creates a new file. Returns FALSE and an error if file
already exists
4 Department of Software Engineering 05/08/2024
Opening a File-Example
If the fopen() function is unable to open the specified file, it
returns 0 (false).
Example
The following example generates a message if the fopen()
function is unable to open the specified file:
<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
</body>
</html>
5 Department of Software Engineering 05/08/2024
Closing a File
The fclose() function is used to close an open file:
The function fclose requires the file handle that we want to close down.
After a file has been closed down with fclose it is impossible to read, write or
append to that file unless it is once more opened up with the fopen function.
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>
Check End-of-file
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
Note: You cannot read from files opened in w, a, and x mode!
if (feof($file)) echo "End of file";
6 Department of Software Engineering 05/08/2024
Reading a File
The fread function is used to get data out of a file.
The function requires a file handle, which we have, and an
integer to tell the function how much data, in bytes, it is
supposed to read.
One character is equal to one byte. If you wanted to read the
first five characters then you would use five as the integer.
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
echo $theData;
?>
! !!
OU
Y
N K
A
TH