PHP Filesystem

Reading, writing, and managing files in PHP

📄 What is PHP Filesystem?

PHP Filesystem functions enable you to create, read, write, and delete files on your server. These powerful tools allow file uploads, data storage, log management, and content manipulation for dynamic web applications.


<?php
// Read file contents
$content = file_get_contents("data.txt");
echo $content;
?>
                                    

Output:

Hello from data.txt file!

Key File Functions

📖

fopen()

Opens a file for reading/writing

<?php
$file = fopen("data.txt", "r");
?>
✍️

fwrite()

Writes data to a file

<?php
fwrite($file, "Hello!");
?>
📚

fread()

Reads file contents

<?php
$data = fread($file, 100);
?>
🔒

fclose()

Closes an open file

<?php
fclose($file);
?>

🔹 Reading Files

PHP offers multiple ways to read file contents. file_get_contents() reads the entire file into a string, perfect for small files. For larger files, use fopen() with fread() to read in chunks, preventing memory issues.

<?php
// Method 1: Read entire file
$content = file_get_contents("info.txt");
echo $content;

// Method 2: Read line by line
$file = fopen("info.txt", "r");
while(!feof($file)) {
    echo fgets($file) . "<br>";
}
fclose($file);
?>

Output:

Line 1 of file
Line 2 of file
Line 3 of file

🔹 Writing to Files

Create and write to files using file_put_contents() for simple operations or fopen() with fwrite() for more control. Use 'w' mode to overwrite, 'a' to append. Always check if the write operation succeeded.

<?php
// Method 1: Simple write
file_put_contents("output.txt", "Hello World!");

// Method 2: Append to file
$file = fopen("log.txt", "a");
fwrite($file, "New log entry\n");
fclose($file);

echo "File written successfully!";
?>

Output:

File written successfully!

🔹 Checking File Existence

Always verify files exist before attempting operations using file_exists(). This prevents errors and allows you to create files when needed. Combine with is_file() to ensure it's actually a file, not a directory.

<?php
// Check if file exists
if(file_exists("data.txt")) {
    echo "File exists!";
} else {
    echo "File not found!";
}

// Check if it's a file
if(is_file("data.txt")) {
    echo " And it's a file.";
}
?>

Output:

File exists! And it's a file.

🔹 Deleting Files

Remove files from your server using unlink(). Always check if the file exists first to avoid errors. This operation is permanent and cannot be undone, so use it carefully, especially in production environments.

<?php
// Delete a file
if(file_exists("temp.txt")) {
    if(unlink("temp.txt")) {
        echo "File deleted successfully!";
    } else {
        echo "Failed to delete file.";
    }
} else {
    echo "File does not exist.";
}
?>

Output:

File deleted successfully!

🔹 File Information

Get detailed file information using various PHP functions. filesize() returns bytes, filemtime() shows last modification time, and pathinfo() provides name, extension, and directory details. Useful for file management systems.

<?php
$file = "document.pdf";

// Get file size
echo "Size: " . filesize($file) . " bytes\n";

// Get last modified time
echo "Modified: " . date("Y-m-d", filemtime($file)) . "\n";

// Get file info
$info = pathinfo($file);
echo "Name: " . $info['filename'] . "\n";
echo "Extension: " . $info['extension'];
?>

Output:

Size: 2048 bytes
Modified: 2025-03-10
Name: document
Extension: pdf

🔹 Copying and Renaming Files

Use copy() to duplicate files and rename() to move or rename them. Both functions return true on success. These operations are useful for backups, file organization, and creating file versions in your applications.

<?php
// Copy a file
if(copy("original.txt", "backup.txt")) {
    echo "File copied!\n";
}

// Rename/move a file
if(rename("old_name.txt", "new_name.txt")) {
    echo "File renamed!";
}
?>

Output:

File copied!
File renamed!

🔹 File Permissions

Check and modify file permissions using chmod() and is_readable()/is_writable(). Proper permissions are crucial for security. Use chmod() carefully as incorrect permissions can expose sensitive data or prevent legitimate access.

<?php
// Check permissions
if(is_readable("data.txt")) {
    echo "File is readable\n";
}

if(is_writable("data.txt")) {
    echo "File is writable\n";
}

// Change permissions (use carefully!)
chmod("data.txt", 0644);
echo "Permissions updated!";
?>

Output:

File is readable
File is writable
Permissions updated!

🧠 Test Your Knowledge

Which function reads an entire file into a string?