R
Rishtaara
PHP Fundamentals
Lesson 16 of 32Article18 min

File Handling — Open, Read, Create & Write

fopen() opens a file. fread() or fgets() reads content. file_get_contents() is a shortcut for small files. Always fclose() when done.

Open and Read Files

fopen() opens a file. fread() or fgets() reads content. file_get_contents() is a shortcut for small files. Always fclose() when done.

Real-life example: Reading a file is opening a notebook and copying notes into your working memory.

Read a text file
<?php
$path = "notes.txt";

// Shortcut
$content = file_get_contents($path);
echo $content;

// Line by line
$handle = fopen($path, "r");
while (($line = fgets($handle)) !== false) {
  echo trim($line) . "\n";
}
fclose($handle);
?>

Create and Write Files

Use fopen($path, 'w') to create/overwrite or 'a' to append. file_put_contents() is simpler for quick writes.

Real-life example: Writing a file is saving a diary entry — new page (w) or add to today's page (a).

Write and append
<?php
$log = "User logged in at " . date("H:i:s") . "\n";

// Append to log file
file_put_contents("app.log", $log, FILE_APPEND);

// Overwrite
file_put_contents("config.txt", "debug=false");
?>

File existence and permissions

Check file_exists(), is_readable(), and is_writable() before operations. Handle errors when folders are missing.

Real-life example: Checking permissions is knocking before entering a room — polite and prevents crashes.

Safe file check
<?php
$file = "data.json";

if (file_exists($file) && is_readable($file)) {
  $data = file_get_contents($file);
  echo $data;
} else {
  echo "File not found or not readable.";
}
?>