Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

PHP File Handling

PHP can create, read, write, and delete files on the server. Always check if a file exists before operating on it and handle errors gracefully.

Reading and Writing Files

file_get_contents() and file_put_contents() are the simplest way to read/write entire files. For more control, use fopen()/fclose().

Read & Write Files
<?php
$file = "data.txt";

// Write (overwrites existing content)
file_put_contents($file, "Hello, World!\n");

// Append to file
file_put_contents($file, "Second line\n", FILE_APPEND);

// Read entire file as string
$content = file_get_contents($file);
echo $content;

// Read file into array (one element per line)
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
    echo $line . "\n";
}

// fopen / fwrite / fclose — low-level control
$handle = fopen("log.txt", "a"); // 'a' = append mode
if ($handle) {
    fwrite($handle, date("Y-m-d H:i:s") . " - Event logged\n");
    fclose($handle);
}
?>

File Information & Management

PHP provides functions to check file existence, get file size, rename, delete, and work with directories.

File Info & Management
<?php
$file = "data.txt";

// Check existence
if (file_exists($file)) {
    echo "File exists\n";
    echo "Size: " . filesize($file) . " bytes\n";
    echo "Is file: " . (is_file($file) ? "yes" : "no") . "\n";
    echo "Is dir: "  . (is_dir($file)  ? "yes" : "no") . "\n";
    echo "Readable: " . (is_readable($file) ? "yes" : "no") . "\n";
}

// Rename / move
rename("old.txt", "new.txt");

// Delete
if (file_exists("temp.txt")) {
    unlink("temp.txt");
}

// Directory operations
mkdir("uploads", 0755, true);  // create recursively
$files = scandir("uploads");   // list directory contents
foreach ($files as $f) {
    if ($f !== "." && $f !== "..") echo $f . "\n";
}
rmdir("empty_folder"); // remove empty directory
?>

fopen() Modes Reference

fopen Modes
<?php
// fopen() mode reference:
// "r"  — read only, pointer at start
// "r+" — read/write, pointer at start
// "w"  — write only, truncate or create
// "w+" — read/write, truncate or create
// "a"  — write only, pointer at end (append)
// "a+" — read/write, pointer at end
// "x"  — create and write, fails if exists
// "x+" — create and read/write, fails if exists

// Reading line by line
$handle = fopen("data.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        echo trim($line) . "\n";
    }
    fclose($handle);
}

// Reading CSV
$csv = fopen("users.csv", "r");
while (($row = fgetcsv($csv)) !== false) {
    echo implode(", ", $row) . "\n";
}
fclose($csv);
?>

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.