← Back to Chapters

PHP FileSystem Functions

? PHP FileSystem Functions

? Quick Overview

PHP provides a range of functions that allow you to interact with the file system, such as reading, writing, renaming, and deleting files, as well as checking file information. These functions are essential when working with files and directories in a web application.

? Key Concepts

  • Files can be created, read, updated, and deleted using built-in PHP functions.
  • Directories can be checked, created, and removed programmatically.
  • File existence and permissions should always be verified.

? Syntax & Theory

  • fopen() – Opens a file or URL
  • fread() – Reads from an open file
  • fwrite() – Writes to a file
  • fclose() – Closes an open file
  • file_get_contents() – Reads entire file content
  • file_put_contents() – Writes data to a file
  • rename() – Renames files or directories
  • unlink() – Deletes a file
  • file_exists() – Checks existence
  • is_dir() – Checks directory
  • mkdir() – Creates directory
  • rmdir() – Removes empty directory

? Code Example

? View Code Example
// Demonstrates file write, read, and delete operations
<?php
$file = "example.txt";
$content = "Hello, this is a test file.";

if (file_put_contents($file, $content)) {
echo "File written successfully<br>";
}

if (file_exists($file)) {
$data = file_get_contents($file);
echo "File Content: $data<br>";
}

if (unlink($file)) {
echo "File deleted successfully<br>";
}
?>

? Live Output / Explanation

The script creates a text file, writes content into it, reads the content back, and finally deletes the file. Each step checks success before moving forward.

? Interactive Concept

Think of PHP FileSystem functions as automated file managers — they perform file operations dynamically without manual intervention.

? Use Cases

  • Uploading and saving user files
  • Logging application data
  • Generating reports dynamically
  • Managing backups and temporary files

✅ Tips & Best Practices

  • Use file_put_contents() for quick file writes
  • Check file existence before reading or deleting
  • Handle permissions carefully to avoid runtime errors
  • Use chunk-based reading for large files

? Try It Yourself

  • Write multiple lines into a file and read them back
  • Create a directory and write a file inside it
  • Allow users to delete files via form submission
  • Experiment with directory creation and removal