Current Location: Home> Latest Articles> PHP Functions Library: File and Directory Handling Functions Explained

PHP Functions Library: File and Directory Handling Functions Explained

M66 2025-07-12

File and Directory Handling Functions in the PHP Functions Library

PHP provides powerful file and directory handling capabilities through its built-in function library. With these functions, you can easily perform operations like reading, writing, and deleting files, as well as creating, deleting, and scanning directories. In this article, we will introduce the most commonly used file and directory handling functions in PHP and demonstrate their usage with practical examples.

File Handling Functions

Directory Handling Functions

  • mkdir(): Creates a new directory.
  • rmdir(): Deletes an empty directory.
  • scandir(): Scans a directory and returns an array of filenames, including files and subdirectories.
  • is_dir(): Checks if a path is a directory.
  • opendir(): Opens a directory and returns a directory handle.
  • readdir(): Reads the next file or subdirectory name from a directory handle.

Practical Examples

Reading File Content:

$content = file_get_contents('myfile.txt');

Writing to a File:

file_put_contents('myfile.txt', 'This is a new file.');

Creating a Directory:

mkdir('new_directory');

Scanning Files and Subdirectories:

$files = scandir('directory_path');

Deleting a File:

unlink('filename.txt');

These are the common file and directory handling functions in PHP, along with practical examples. Mastering these functions will help developers perform file and directory operations more efficiently.