PHP File Handling

Working with files in PHP

📁 What is PHP File Handling?

PHP file handling allows you to create, read, write, and delete files on the server. It's essential for storing data, managing uploads, and working with text or configuration files efficiently.


<?php
// Simple file handling example
$file = fopen("welcome.txt", "r");
echo fread($file, filesize("welcome.txt"));
fclose($file);
?>
                                    

File Handling Operations

📖

Reading Files

Open and read content from existing files using functions like fopen(), fread(), and file_get_contents() to access stored data.

<?php
$content = file_get_contents("data.txt");
echo $content;
?>
✍️

Writing Files

Create new files or modify existing ones using fwrite() or file_put_contents() to save data permanently on the server.

<?php
file_put_contents("log.txt", "New entry");
?>
🗑️

Deleting Files

Remove unwanted files from the server using the unlink() function to clean up storage and manage file systems.

<?php
unlink("oldfile.txt");
echo "File deleted";
?>

Checking Files

Verify if files exist, check permissions, and get file information using file_exists(), is_readable(), and is_writable() functions.

<?php
if(file_exists("test.txt")) {
    echo "File exists!";
}
?>

🔹 Opening Files with fopen()

The fopen() function opens a file with different modes:

<?php
// Open file for reading
$file = fopen("example.txt", "r");

// Open file for writing (creates if not exists)
$file = fopen("newfile.txt", "w");

// Open file for appending
$file = fopen("log.txt", "a");

// Always close the file when done
fclose($file);
?>

File Modes:

  • r - Read only (file must exist)
  • w - Write only (creates new or overwrites)
  • a - Append (adds to end of file)
  • r+ - Read and write
  • w+ - Read and write (overwrites)

🔹 Reading File Content

Multiple ways to read files in PHP:

🔸 Using file_get_contents()

<?php
// Read entire file into a string
$content = file_get_contents("message.txt");
echo $content;
?>

🔸 Using fread()

<?php
$file = fopen("data.txt", "r");
$content = fread($file, filesize("data.txt"));
fclose($file);
echo $content;
?>

🔸 Reading Line by Line

<?php
$file = fopen("list.txt", "r");
while(!feof($file)) {
    echo fgets($file) . "<br>";
}
fclose($file);
?>

🔹 Writing to Files

Save data to files using different methods:

🔸 Using file_put_contents()

<?php
// Write string to file (overwrites existing content)
$text = "Hello, World!";
file_put_contents("greeting.txt", $text);
echo "File written successfully!";
?>

🔸 Using fwrite()

<?php
$file = fopen("notes.txt", "w");
fwrite($file, "First line\n");
fwrite($file, "Second line\n");
fclose($file);
echo "Data saved!";
?>

🔸 Appending to Files

<?php
// Add content without deleting existing data
$newEntry = "New log entry\n";
file_put_contents("log.txt", $newEntry, FILE_APPEND);
?>

🔹 File Information Functions

Get useful information about files:

<?php
$filename = "document.txt";

// Check if file exists
if(file_exists($filename)) {
    echo "File exists!<br>";
    
    // Get file size in bytes
    echo "Size: " . filesize($filename) . " bytes<br>";
    
    // Check if readable
    echo "Readable: " . (is_readable($filename) ? "Yes" : "No") . "<br>";
    
    // Check if writable
    echo "Writable: " . (is_writable($filename) ? "Yes" : "No") . "<br>";
    
    // Get last modified time
    echo "Modified: " . date("Y-m-d H:i:s", filemtime($filename));
}
?>

🔹 Practical Example: Simple Counter

Create a visitor counter using file handling:

<?php
$counterFile = "counter.txt";

// Check if file exists, create if not
if(!file_exists($counterFile)) {
    file_put_contents($counterFile, "0");
}

// Read current count
$count = (int)file_get_contents($counterFile);

// Increment count
$count++;

// Save new count
file_put_contents($counterFile, $count);

// Display
echo "You are visitor number: " . $count;
?>

Output:

You are visitor number: 42

🧠 Test Your Knowledge

Which function reads an entire file into a string?