Codeskill

Learn to code, step by step

File Handling in PHP: Reading and Writing Files

Reading, writing, and checking files on the server.

Understanding file handling in PHP

File handling means reading from and writing to files on the server – logs, config files, user uploads, CSV exports, that sort of thing.

Opening a file

Before you read or write, open the file with fopen(). You pass the file path and a mode:

File open modes

  • 'r': open for reading only; start at the beginning of the file.
  • 'w': open for writing only; start at the beginning and truncate the file to zero length. Creates the file if it does not exist.
  • 'a': open for writing only; start at the end of the file. Creates the file if it does not exist.

Example:

<?php
$file = fopen("example.txt", "r") or die("Unable to open file!");
?>

Reading from a file

Once a file is open, several functions can read its contents:

Using fread()

Reads up to a specified number of bytes:

<?php
echo fread($file, filesize("example.txt"));
fclose($file);
?>

Using fgets()

Reads one line at a time:

<?php
echo fgets($file);
fclose($file);
?>

Writing to a file

Use fwrite() or the shorter file_put_contents():

Using fwrite()

Writes a string to an open file handle:

<?php
$file = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Hello, PHP World!\n";
fwrite($file, $txt);
fclose($file);
?>

Using file_put_contents()

Combines fopen(), fwrite(), and fclose() in one call:

<?php
file_put_contents("newfile.txt", "Hello, PHP World!", FILE_APPEND);
?>

Appending to a file

To add content without wiping what’s already there, open in append mode ('a'):

<?php
$file = fopen("newfile.txt", "a") or die("Unable to open file!");
$txt = "Adding more content.\n";
fwrite($file, $txt);
fclose($file);
?>

Checking for file existence and size

Worth checking before you read or write:

Using file_exists()

<?php
if(file_exists("example.txt")) {
    echo "File exists.";
} else {
    echo "File does not exist.";
}
?>

Using filesize()

<?php
echo "File size is " . Filesize("example.txt") . " bytes";
?>

Deleting a file

Remove a file with unlink():

<?php
if (file_exists("deletefile.txt")) {
    unlink("deletefile.txt");
    echo "File deleted.";
} else {
    echo "File does not exist.";
}
?>

Working with CSV files

PHP handles CSV (comma-separated values) files too – common for spreadsheets and simple data exports:

Reading from a CSV file

<?php
$file = fopen("example.csv", "r");
while (($data = fgetcsv($file, 1000, ",")) !== FALSE) {
    print_r($data);
}
fclose($file);
?>

Writing to a CSV file

<?php
$list = array(
    array('Alice', 'Doe', 'alice@example.com'),
    array('Bob', 'Smith', 'bob@example.com')
);

$file = fopen('users.csv', 'w');
foreach ($list as $fields) {
    fputcsv($file, $fields);
}
fclose($file);
?>

Best practices and security

A few habits worth keeping:

  • Validate and sanitise inputs when reading and writing files.
  • Check file types and sizes on uploads.
  • Handle errors gracefully when a file cannot be opened or read.
  • Be careful with file paths to avoid directory traversal attacks.

File handling turns up everywhere in PHP – logs, config, exports, uploads. These functions cover the everyday read/write cases.

PreviousSessions and Cookies: Managing User State in PHP