Simple PHP File Handling Script
Question: Write a PHP-script to open, close, read and write into a file.
PHP provides a good number of file handling in-built functions. A few are:
file_exists( ): The function checks if file exists then it returns TRUE else FALSE boolean value is returned.
fopen( ): The api is used to open files for reading or writing or both. It accepts two arguments i.e. first is the filename (along with optional path) and second argument is mode to open file. It returns a file handle.
$filehandle = fopen('myfile.text', 'w');
The various mode values are:
r : Opens a file for reading only. It places the file pointer at the beginning of the file.
r+ : Opens a file for reading and writing, and places the file pointer at the start of the file.
w : Opens a file for writing only, and places the file pointer at the start of the file.
w+ : Opens a file for writing and reading, and places the file pointer at the start of the file.
a : Opens the file for writing (append) only, and places the file pointer at the end of the file.
a+ : Opens the file for reading and writing, and places the file pointer at the end of the file.
b : To open binary files, generally used alongwith other mode values e.g. wb+
fread( ): to read the contents (in bytes) of a file. If you’re trying to read a file over a network link
fgets() function is a better option.
filesize( ): returns the size of the file.
fwrite( ): to write the number of bytes to a file.
fclose( ): closes the opened file.
Here is a PHP script which opens a file, reads its content, displays it, writes a line and closes the file.