File Handling
File Handling
• File attributes are the properties of a file, for example its size, the last
time it was accessed, its owner, etc.
filesize()
• If the file doesn’t exist, the filesize() function will return false and emit
an E_WARNING.
file_exists()
• This functions is used to check first whether the file exists or not.
• It comes in handy when we want to know if a file exists or not before
• processing it.
• You can also use this function when creating a new file and you want
to
• ensure that the file does not already exist on the server
FILE HISTORY
• To make absolutely sure that you’re dealing with a file you can use the
is_file()
• function. is_dir() is the counterpart to check if it is a directory.
OPENING AND CLOSING FILES
A better method to open files is with the fopen() function. This function
gives you more options than the readfile() function.
open(): The PHP fopen() function is used to open a file. It requires two
arguments stating first the file name and then mode in which to operate.
• Syntax: fopen($file_name,$mode);
Here,
• “fopen” is the PHP open file function
• “$file_name” is the name of the file to be opened
• “$mode” is the mode in which the file should be opened Places the file pointer
at the end of the file. If files does not exist then it attempts to create a file
Files modes can be specified as one
of the six options in this table.
r
• Opens the file for reading only.
• Places the file pointer at the beginning of the file.
r+
• Opens the file for reading and writing.
• Places the file pointer at the beginning of the file
w
• Opens the file for writing only.
• Places the file pointer at the beginning of the file and truncates the file to
zero length. If files does not exist then it attempts to create a file
Files modes can be specified as one
of the six options in this table
w+
• Opens the file for reading and writing only.
• Places the file pointer at the beginning of the file and truncates the file to
zero length. If files does not exist then it attempts to create a file.
a
• Opens the file for writing only.
• Places the file pointer at the end of the file. If files does not exist then it
attempts to create a file.
a+
• Opens the file for reading and writing only.
READING A FILE
fread():
• Once a file is opened using fopen() function it can be read with a function
called fread().
• This function requires two arguments. These must be the file pointer and
the length of the file expressed in bytes.
• The files length can be found using the filesize() function which takes the
filename as its argument and returns the size of the file expressed in bytes.
• The steps required to read a file with PHP.
The fclose() function is used to close an open file.