Skip to content

PHP Tutorial File Handling Exercise

Practice: File Handling Exercises

Lesson 175 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Try each exercise before you open the solution. The code creates its own sample files, so you can run it as it is.

Exercise 1: count the lines

Create a file with five lines of text, then print how many lines it has and the length of the longest one.

Show a possible solution
index.php
PHP
<?php
file_put_contents("poem.txt", "one\ntwo words\nthree\nfour four\nfive\n");

$lines = file("poem.txt", FILE_IGNORE_NEW_LINES);

$longest = max(array_map("strlen", $lines));

echo count($lines) . " lines, longest has $longest characters";
Output
OUTPUT
5 lines, longest has 9 characters

Exercise 2: a simple log reader

A log file has lines like 2026-01-05 ERROR Disk full. Print only the lines that contain ERROR, and how many there are.

Show a possible solution
index.php
PHP
<?php
file_put_contents("app.log",
    "2026-01-05 INFO Started\n" .
    "2026-01-05 ERROR Disk full\n" .
    "2026-01-06 INFO Saved\n" .
    "2026-01-06 ERROR Timeout\n"
);

$errors = [];
$handle = fopen("app.log", "r");

while (($line = fgets($handle)) !== false) {
    if (str_contains($line, " ERROR ")) {
        $errors[] = trim($line);
    }
}

fclose($handle);

echo implode("\n", $errors) . "\n";
echo count($errors) . " errors";
Output
OUTPUT
2026-01-05 ERROR Disk full
2026-01-06 ERROR Timeout
2 errors

Exercise 3: total a CSV column

A CSV file sales.csv has the columns item,price,qty. Print the total of price times qty.

Show a possible solution
index.php
PHP
<?php
file_put_contents("sales.csv", "item,price,qty\nPen,12,5\nBook,250,2\nBag,799,1\n");

$handle = fopen("sales.csv", "r");
fgetcsv($handle, 0, ",", '"', "\\");   // skip the header

$total = 0;

while (($row = fgetcsv($handle, 0, ",", '"', "\\")) !== false) {
    [$item, $price, $qty] = $row;
    $total += (float) $price * (int) $qty;
}

fclose($handle);

echo "Total: $total";
Output
OUTPUT
Total: 1359

Exercise 4: a safe guestbook

Write a function addEntry(string $name, string $message): void that appends one line to guestbook.txt in the form name: message. New lines inside the text must not create extra entries. Show the file after adding an entry with a line break in the message.

Show a possible solution
index.php
PHP
<?php
function addEntry(string $name, string $message): void
{
    $clean = fn(string $text): string => trim(str_replace(["\r", "\n"], " ", $text));

    $line = $clean($name) . ": " . $clean($message) . PHP_EOL;

    file_put_contents("guestbook.txt", $line, FILE_APPEND | LOCK_EX);
}

addEntry("Ana", "Hello!");
addEntry("Ben", "First line\nSecond line");

echo file_get_contents("guestbook.txt");
Output
OUTPUT
Ana: Hello!
Ben: First line Second line

Exercise 5: list and clean up

Create three .tmp files in a folder called cache, list them with glob(), then delete them all and show how many files are left.

Show a possible solution
index.php
PHP
<?php
mkdir("cache");

foreach (["a", "b", "c"] as $name) {
    file_put_contents("cache/$name.tmp", "data");
}

$files = glob("cache/*.tmp");
echo count($files) . " files: " . implode(", ", array_map("basename", $files)) . "\n";

foreach ($files as $file) {
    unlink($file);
}

echo count(glob("cache/*.tmp")) . " files left";
Output
OUTPUT
3 files: a.tmp, b.tmp, c.tmp
0 files left