PHP File Handling (original) (raw)

Last Updated : 04 Apr, 2025

File handling allows the developers to interact with the server’s file system, which is essential for tasks like saving data, processing user-uploaded files, and generating dynamic content. PHP File Handling enables developers to read from and write to files, making it a core feature for web applications. Without file handling, managing files such as images, documents, and text would be difficult.

In this article, we’ll discuss file handling in PHP, its types, and its functionality.

What is File Handling in PHP?

In PHP, File handling is the process of interacting with files on the server, such as reading files, writing to a file, creating new files, or deleting existing ones. File handling is essential for applications that require the storage and retrieval of data, such as logging systems, user-generated content, or file uploads.

Types of File Operations in PHP

Several types of file operations can be performed in PHP:

Common File Handling Functions in PHP

Opening and Closing Files

Before you can read or write to a file, you need to open it using the fopen() function, which returns a file pointer resource. Once you’re done working with the file, you should close it using fclose() to free up resources.

PHP `

`

File Modes in PHP

Files can be opened in any of the following modes:

Reading from Files

There are two ways to read the contents of a file in PHP. These are –

1. Reading the Entire File

You can read the entire content of a file using the fread() function or the file_get_contents() function.

PHP `

content=fread(content = fread(content=fread(file, filesize("gfg.txt")); echo $content; fclose($file); ?>

`

2. Reading a File Line by Line

You can use the fgets() function to read a file line by line.

PHP `

"; } fclose($file); } ?>

`

Writing to Files

You can write to files using the fwrite() function. It writes data to an open file in the specified mode.

PHP `

`

Deleting Files

Use the unlink() function to delete the file in PHP.

PHP `

`