PHP File Handling
File handling is an important piece of any web application. For certain tasks to be done, a file needs to be processed. PHP file handling functions allow us to store, access and manipulate the file.
These are the basic operations performed on a file.
- Creating a file
- Opening a file
- Reading a file
- Writing to a file
- Closing the file
1. Creating a file -
PHP predefined function touch() is used to create a file.
Syntax -touch('filename');
Example -
<?php
touch('text.txt'); // create a text file.
?>
2. Opening a file -
PHP predefined function fopen() is used to open a file from a local machine or a server or from a url.
Syntax -fopen('filename', 'mode')
Example -
<?php
$file = fopen('text.txt', r);
?>
The above statement opens a file for reading purpose. The first parameter is a file name and the second parameter is an accessed modifier which tells the purpose of opening a file, like read, write etc.
Six access modifiers of file -
r -> open the file for reading.
r+ -> open the file for reading and writing.
w -> open the file for writing, if no file exists with that name, then it will create the file and place the file
pointer at the begging.
w+ -> open the file for reading and writing.
a -> open the file for writing and place the file pointer at the end of the file contents.
3. Reading a file -
The PHP fread() function is used to read a file. Before reading a file, we need to open it. So first, open a file using fopen() function, then read the file using fread() function.
Syntax -fread('filename', 'filesize')
The filesize() function is used to get the filesize.
Example -
<?php
$file_name = 'text.txt';
$file = fopen($file_name, 'r');
$file_size = filesize($file_name);
$file_content = fread($file, $file_size);
echo $file_size;
echo $file_content;
?>
4. Writing a file -
The PHP fwrite() function is used to write in an open file.
Syntax -
fwrite('filename', 'content to write');
Example -
<?php
$file_name = 'text.txt';
$file = fopen($file_name, 'r');
$content = 'welcome to etutorialspoint';
$file_write = fwrite($file, $content);
if($file_write) {
echo 'content written to a file';
}
else{
echo 'Failed content written';
}
?>
5. Closing a file -
The PHP fclose() function is used to close an open file pointer. This function is called at the end of a file operation.
Syntax - fclose ( resource $handle )
Example -
<?php
$file_name = 'text.txt';
$file = fopen($file_name, 'r');
$content = 'welcome to etutorialspoint';
$file_write = fwrite($file, $content);
if($file_write) {
echo 'content written to a file';
}
else{
echo 'Failed content written';
}
fclose();
?>
Including File
PHP provides function to call external file within a file. There are four include functions in PHP -
- include('/filepath/filename');
- require('/filepath/filename');
- include_once('/filepath/filename');
- require_once('/filepath/filename');