Current Location: Home> Latest Articles> PHP File System Functions Guide: File and Directory Operations Tutorial

PHP File System Functions Guide: File and Directory Operations Tutorial

M66 2025-07-10

PHP File System Functions Guide

PHP provides a set of file system functions that allow developers to easily interact with files and directories. Common file operations include opening, reading, writing, deleting, renaming, and more, while directory operations include creating, deleting, listing files, checking directories, and changing working directories. This article will help you understand how to use these functions and how to apply them in real projects through examples.

File Operations

PHP offers several useful file operation functions. Some of the most common ones include:

Example: Writing to a File

<?php
$file = 'my_file.txt';
$data = 'Hello, world!';
$handle = fopen($file, 'w');
fwrite($handle, $data);
fclose($handle);
echo 'File written';
?>

Directory Operations

Similarly, PHP offers several functions to interact with directories:

  • mkdir(): Create a new directory
  • rmdir(): Delete an empty directory
  • scandir(): List the contents of a directory
  • is_dir(): Check if a path is a directory
  • chdir(): Change the current working directory

Example: Creating a Directory

<?php
$directory = 'new_directory';
mkdir($directory);
echo 'Directory created';
?>

Real-World Example: Uploading Files to a Server

Here’s an example of how to upload a file using PHP file system functions:

<?php
if ($_FILES['my_file']['error'] === 0) {
    $target_dir = 'uploads/';
    $target_file = $target_dir . basename($_FILES['my_file']['name']);

    // Check if file already exists
    if (file_exists($target_file)) {
        echo 'File already exists';
    } else {
        // Move the uploaded file to the target directory
        if (move_uploaded_file($_FILES['my_file']['tmp_name'], $target_file)) {
            echo 'File uploaded successfully';
        } else {
            echo 'File upload failed';
        }
    }
}
?>

Conclusion

This article covered how to use PHP file system functions for managing files and directories, along with real-world examples of file uploads. By mastering these basic operations, you can efficiently handle file and directory tasks in PHP. Stay tuned for more PHP development tips on our website.