File Handling in PHP - Codingque

File Handling in PHP

Learn how to handle files in PHP, including reading from, writing to, and managing files. This guide covers various file operations and their applications.

File Handling in PHP

File handling is an essential part of PHP, allowing you to create, read, write, and delete files. PHP provides various functions to work with files.

1. Creating and Opening a File

The fopen() function is used to open files. It takes two arguments: the name of the file and the mode in which to open the file.

<?php
$file = fopen("example.txt", "w"); // Open or create a file for writing
if ($file) {
    echo "File opened successfully.";
} else {
    echo "Unable to open the file.";
}
?>

Modes:

2. Writing to a File

You can write to a file using the fwrite() function.

<?php
$file = fopen("example.txt", "w");
if ($file) {
    $content = "Hello, World!";
    fwrite($file, $content);
    echo "Content written to the file.";
    fclose($file);
} else {
    echo "Unable to open the file.";
}
?>

Explanation: The above code opens example.txt for writing, writes "Hello, World!" to the file, and then closes the file.

3. Reading from a File

The fread() function is used to read from a file.

<?php
$file = fopen("example.txt", "r");
if ($file) {
    $content = fread($file, filesize("example.txt"));
    echo "File Content: " . $content;
    fclose($file);
} else {
    echo "Unable to open the file.";
}
?>

Explanation: This code reads the content of example.txt and prints it.

4. Appending to a File

To append data to an existing file, use the 'a' mode with fopen().

<?php
$file = fopen("example.txt", "a");
if ($file) {
    $additionalContent = "\nThis is additional content.";
    fwrite($file, $additionalContent);
    echo "Content appended to the file.";
    fclose($file);
} else {
    echo "Unable to open the file.";
}
?>

Explanation: This code appends new content to the end of example.txt.

5. Deleting a File

You can delete a file using the unlink() function.

<?php
$file = "example.txt";
if (unlink($file)) {
    echo "File deleted successfully.";
} else {
    echo "Unable to delete the file.";
}
?>

Explanation: The unlink() function deletes the specified file.

Previous Next
Modern Footer