File Handling in PHP
File Handling in PHP
Overview
File handling in PHP refers to the various functions and methods available in the language that
enable developers to read, write, manipulate, and manage files and directories on a server or
local machine. PHP provides several built-in functions like open (), fwrite(), fread(), fclose(), and
others to manipulate files in different modes like read, write, append, binary, etc. PHP also
provides functions to manage directories, such as opendir() to open a directory, readdir() to read
the contents of a directory and closedir() to close a directory. These functions enable developers
to create, move, rename, delete, and manage files and directories.
Introduction
File handling is a crucial aspect of programming that involves creating, reading, writing, and
deleting files. In PHP, file handling plays a vital role in web development, especially when
dealing with tasks such as data storage, retrieval, and manipulation. Understanding file handling
in PHP requires knowledge of the functions and techniques available to effectively perform these
tasks.
PHP provides a rich set of built-in functions for file handling, which can be used to perform a
variety of operations on files, including opening, reading, writing, and closing files. With a good
understanding of file handling in PHP, developers can create powerful web applications that can
handle various file-related tasks efficiently.
In this syntax:
$filename is the name of the file or URL to open
$mode is the mode in which to open the file. This can be one of the following:
'r': read only
'w': write only (truncates the file to zero length or creates a new file)
'a': append-only (opens the file for writing at the end of the file)
'x': exclusive write (creates a new file and opens it for writing only if it doesn't already
exist)
'b': binary mode (used in conjunction with the above modes to indicate that the file should
be opened in binary mode)
't': text mode (used in conjunction with the above modes to indicate that the file should be
opened in text mode)
$use_include_path is a boolean parameter that indicates whether to search for the file in
the include path (if set)
$context is an optional parameter that allows you to specify a context for the file stream
(e.g. HTTP headers, SSL settings, etc.)
Modes Description
Read-only. The file pointer starts at the beginning of the
r
file
Read/Write. The file pointer starts at the beginning of the
r+
file
Write only. It opens and clears the contents of the file; or
w
creates a new file if it doesn’t exist
Read/Write. It opens and clears the contents of the file;
w+
or creates a new file if it doesn’t exist
Append. It opens and writes to the end of the file or
a
creates a new file if it doesn’t exist
Read/Append. It preserves file content by writing to the
a+
end of the file
Write only. Creates a new file. Returns FALSE and an
x
error if file already exists
Read/Write. Creates a new file. Returns FALSE and an
x+
error if file already exist
Here's an example that demonstrates how to use fopen() to open a file in read-only mode, read its
contents line by line, and then close the file:
$file = fopen('example.txt', 'r');
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line;
}
fclose($file);
}
Explanation
In this example, the file example.txt is opened in read-only mode using fopen(). The while loop
reads the file line by line using the fgets() function, and the contents of each line are echoed to
the screen. Finally, the fclose() function is called to close the file.
Explore free courses by our top instructorsView All
TARUN LUTHRA
Java Course - Mastering the Fundamentals
84k+ enrolled
RAHUL JANGHU
Python Course for Beginners With Certification: Mastering the Essentials
75k+ enrolled
PRATEEK NARANG
C++ Course: Learn the Essentials
43k+ enrolled
35,262+ learners have attended these Courses.
PHP fclose() Function
The PHP fclose() function is used to close an open file pointer or handle in PHP. It is typically
used after a file has been opened using fopen() or a related function.
Here is the syntax for the fclose() function:
bool fclose ( resource $handle )
The function takes a single parameter, which is the file pointer or handles to be closed. The
function returns a boolean value indicating whether the file was successfully closed or not.
Here's an example that demonstrates how to use fclose() in PHP:
<?php
// Open a file for writing
$file = fopen("example.txt", "w");
Parameters:
$file_handle: Required. Specifies the file pointer or file handle to read from. $length: Required.
Specifies the number of bytes to read from the file.
Return Value:
Returns the read data as a string.
Example:
Suppose we have a file example.txt with the following content:
Hello, World! This is an example file.
And we want to read the first 10 bytes of this file using the fread() function. Here's how we can
do that:
<?php
$file_handle = fopen("example.txt", "r"); // opening the file in read mode
$length = 10; // specifying the number of bytes to read
$data = fread($file_handle, $length); // reading the first 10 bytes from the
file
fclose($file_handle); // closing the file
echo $data; // output: Hello, Wor
?>
resource $handle: A file pointer, which is a reference to the opened file. It can be
obtained using functions such as fopen(), fsockopen(), and tmpfile().
string $string: The string to be written to the file.
int $length: An optional parameter that specifies the maximum number of bytes to be
written. If this parameter is not specified, all the data in the string will be written to the
file.
The fwrite() function returns the number of bytes written to the file, or false on error.
Here's an example of how to use the fwrite() function to write data to a file:
$file = fopen("data.txt", "w");
if ($file) {
$data = "Hello, World!\n";
fwrite($file, $data);
fclose($file);
echo "Data written to the file.";
} else {
echo "Error opening file.";
}
Explanation
In this example, we first open a file named "data.txt" in write mode using the fopen() function.
We then check if the file was successfully opened, and if it was, we write the string "Hello,
World!\n" to the file using the fwrite() function.
PHP Delete File - unlink()
In PHP, the unlink() function is used to delete a file from the file system. It accepts a single
argument, which is the path to the file that needs to be deleted.
Here is the syntax of the unlink() function:
bool unlink ( string $filename [, resource $context ] )
if (file_exists($file_path)) {
if (unlink($file_path)) {
echo "File deleted successfully.";
} else {
echo "Unable to delete the file.";
}
} else {
echo "File does not exist.";
}
?>
Explanation
In this example, we first check if the file exists using the file_exists() function. If the file exists,
we attempt to delete it using the unlink() function. If the unlink() function returns true, we
display a success message. If it returns false, we display an error message.
It is important to note that the unlink() function permanently deletes the file, so be careful when
using it. Once a file is deleted using unlink(), it cannot be recovered.
Conclusion
File handling in PHP involves opening, reading, writing, and manipulating files stored on
a file system.
The fopen() function is used to open a file for reading, writing, or appending.
The fwrite() function is used to write to a file, while the fread() function is used to read
from a file.
The fgets() function can be used to read a single line from a file.
The fclose() function should be used to close a file after reading or writing to it.
HP Directory Functions
Function Description
Example
Change the current directory:
<?php
// Get current directory
echo getcwd() . "<br>";
// Change directory
chdir("images");
/home/php
/home/php/images
Example
Change the root directory:
<?php
// Change root directory
chroot("/path/to/chroot/");
Example
Open a directory, read its contents, then close:
<?php
$dir = "/images/";
filename: cat.gif
filename: dog.gif
filename: horse.gif