The main group of files handling functions is that one that includes opening, reading, and writing to files.
The files handling funcitons are listed below:
- fopen() - It is used to open a file.
- fread() - It is used to read a file.
- fwrite() - This is used to write in a file.
- fclose() - Closes a file.
- fgets() - A line can be read by using this function.
- feof() - It checks if the end of file has reached.
- fgetc() - It is used to read a single character from a file.
The fopen() function
Local or remote files can be accessed by using accessed fopen() function. This function allows using different modes of operation, depending on what we want to achieve.
Syntax for fopen() funciton
fopen ("filename", "method");
Where modes are:
Modes |
Description |
---|---|
r |
Open a file for read only |
w |
Open a file for write only |
a |
Open a file for write only |
x |
Creates a new file for write only |
r+ |
Open a file for read/write |
w+ |
Open a file for read/write |
a+ |
Open a file for read/write |
x+ |
Creates a new file for read/write |
Basic example with fopen(), fread() and fclose() functions
<?php
$file = fopen ("example_file.txt", "r") or die(); // open file or 'kill' script
echo fread ($file, filesize("example_file.txt")); // reads file size
fclose ($file); // close file
?>
Explanation of the example above: The fopen() function reads the file only (hence the extension “r”). Instead of “r” any of the other modes can be used, mentioned in the previous section. The rest of the functions read (fread()) the file's size (filesize()), and close the file (fclose()). Note that the die() function will stop the script if the file does not exist.
Comments
No comments have been made yet.
Please login to leave a comment. Login now