File Handling

Last updated on

File Handling in PHP is an important tool especially when you need to manage files such as reading, writing, or handling uploads.

In this article, you will learn everything you need to know about file handling in PHP. Let's get started.

File handling means working with files on your server. PHP provides several built-in functions to open, read, write, and delete files. These functions let you handle files efficiently while keeping things easy to manage.

Here are some of the built-in functions for file handling in PHP:

You need to specify a mode when opening a file. These modes tell PHP how you intend to work with the file. Here are some modes:

  • 'r': Read-only. The file must exist.\n
  • 'w': Write-only. Creates a new file or overwrites an existing file.
  • 'a': Append. Adds data to the end of the file without overwriting.
  • 'x': Exclusive create. Fails if the file already exists.
  • 'r+': Read and write.

Each mode serves a specific purpose, so pick one based on what you need to do.

In the following section, you will learn how to read files in PHP.

Reading Files in PHP

PHP provides multiple ways to read files. We just need to use each method to read the flatcoding.txt file. Look at the following image that shows the structure within this script.

Read Files in PHP

Here is how you can do it:

Read Files with fread()

Here is an example:

// flatcoding.txt  => contains this text (Hello, this is the content of flatcoding.txt)
$file = fopen("flatcoding.txt", "r");
if ($file) {
    $content = fread($file, filesize("flatcoding.txt"));
    fclose($file);
    echo $content;
} else {
    echo "Failed to open the file.";
}

The output of this example would be like below:

Hello, this is the content of flatcoding.txt

This reads the contents of a file named flatcoding.txt and prints it to the screen. It first tries to open the file in "read" mode using fopen. If the file is successfully opened, it reads the entire content using fread, closes the file with fclose, and displays the content using echo. If something goes wrong (like the file does not exist or there is a permissions issue), It handles the error by printing "Failed to open the file.".

There is another way to read files, which is the built-in function in PHP, file_get_contents. Let's move on to the following section to see how it works.

Read File with file_get_contents()

Here is an example:

$content = file_get_contents("example.txt");
if ($content !== false) {
    echo $content;
} else {
    echo "Failed to read the file.";
}

We used the file_get_contents to read the file "flatcoding.txt". If the operation is successful, it stores the file's content in the $content variable and prints it using echo. On the other hand, if something goes wrong (like the file does not exist or there is an issue reading it), the if statement detects this and outputs "Failed to read the file.".

So, how do you write to the file you already opened in the previous PHP example? Let's move into that in the following section.

Writing Files in PHP

There are two ways to do this task. Let's take a look at each one with an example.

Write Fiels with fwrite() Function

Here is an example:

$file = fopen("example.txt", "w");
if ($file) {
    fwrite($file, "This is a new line of text.");
    fclose($file);
    echo "File written successfully.";
} else {
    echo "Failed to write to the file.";
}

The fwrite function writes the text "This is a new line of text." into the file. After writing, the file is closed with fclose to ensure changes are saved properly. It prints "File written successfully." If there is an issue opening the file (like permission problems), it will instead print "Failed to write to the file.".

Let's do the same task with file_put_contents().

Writing Files by file_put_contents()

Here is an example:

$result = file_put_contents("example.txt", "Overwritten content.");
if ($result !== false) {
    echo "File written successfully.";
} else {
    echo "Failed to write to the file.";
}

Here, I used the file_put_contents function to write the string "Overwritten content." to the file example.txt. It will create a new one If the file does not exist

In the following section, you will learn how to append data into files in PHP.

Append Data to Existing Data

To add data to a file without overwriting the existing content, you can open the file in "append" mode using the "a" flag. This ensures that new content is added to the end of the file. Here is an example:

$file = fopen("example.txt", "a");
if ($file) {
    fwrite($file, "This is an appended line of text.\n");
    fclose($file);
    echo "Data appended successfully.";
} else {
    echo "Failed to append to the file.";
}

The "a" flag opens the file in append mode. If the file does not exist, it creates a new one. fwrite adds the specified text to the end of the file, without removing the existing content. \n adds a new line after the appended text, ensuring the next addition starts on a new line. It prints "Failed to append to the file." If the file cannot be opened.

You can do the same job with file_put_contents(). Here is an example:

$result = file_put_contents("example.txt", "\nAnother line.", FILE_APPEND);
if ($result !== false) {
    echo "Data appended successfully.";
} else {
    echo "Failed to append to the file.";
}

Both will append text to the end of the file. Below is an image that shows what happens:

Append Data to File in PHP with a Flag

In the following section, you will learn how to check if the current file already exists on the drive in PHP.

Checking If a File Exists

It is always good to check if the file exists before performing file operations. Here is an example:

if (file_exists("example.txt")) {
    echo "The file exists.";
} else {
    echo "The file does not exist.";
}

This will check if the file exists in the directory. If it does, it will print "The file exists." Otherwise, it will print "The file does not exist.".

Let's move on to the following section to learn how to delete a file in a specific path using PHP.

Deleting Files

You can use the unlink() function to delete a file in a specific directory. Here is an example:

if (file_exists("example.txt")) {
    if (unlink("example.txt")) {
        echo "File deleted successfully.";
    } else {
        echo "Failed to delete the file.";
    }
} else {
    echo "File does not exist.";
}

The file_exists function helps us detect the existence of a file. If it already exists, it will delete the file from the directory.

Let's summarize.

Wrapping Up

File handling in PHP helps you to read, write, append data, or deleting files. Here are a quick recap:

  • File operations with fopen(), fclose(), fread(), and fwrite() for basic file handling tasks.
  • Checking files using file_exists() function ensures the file's existence before performing operations.
  • Appending data by using the "a" mode or FILE_APPEND with file_put_contents() to add content without overwriting.
  • Deleting files with unlink() function to  remove files.
  • Reading by using file_get_contents() for file reading.

Thank you for read this overview of file handling in PHP! If you found this helpful, do not miss out on our complete PHP tutorial. Happy coding!

Frequently Asked Questions (FAQs)

  • What is file handling in PHP?

    File handling in PHP refers to working with server-side files for tasks like reading, writing, appending, and deleting data using built-in PHP functions.
  • What are the main PHP functions used for file handling?

    fopen()
  • How do you check if a file exists in PHP?

    Use the file_exists() function:
     if (file_exists("example.txt")) {  
        echo "The file exists.";  
    } else {  
        echo "The file does not exist.";  
    }  
    
  • How can you write to a file in PHP?

    fwrite()
  • What is the difference between "w" and "a" modes in `fopen()`?

    • "w": Opens a file for writing, creating it if it does not exist or overwriting it if it does.
    • "a": Opens a file for appending, creating it if it does not exist and adding content to the end without overwriting.
Share on: