Filesystem Management

Back

Loading concept...

πŸ—‚οΈ PHP Filesystem Management: Your Digital File Cabinet Adventure!


🎭 The Story: Meet Your Digital Filing Cabinet

Imagine you have a magical filing cabinet in your room. This cabinet can:

  • Copy papers (make exact duplicates)
  • Move papers from one drawer to another
  • Delete papers you don’t need
  • Create new drawers (folders)
  • List everything inside a drawer
  • Remove entire drawers
  • Read labels on folders to know where things are

PHP gives you superpowers to do ALL of this with files on a computer! Let’s learn each power, one at a time.


πŸ“‹ File Copying: Making Twins!

What is File Copying?

Think of photocopying a drawing. You put your drawing in the machine, press a button, and now you have TWO identical drawings!

In PHP, we use copy() to make an exact twin of any file.

The Magic Spell

copy("original.txt", "twin.txt");

What happens:

  • original.txt stays exactly where it is
  • A new file twin.txt appears with the same content

Real Example

<?php
// Copy a photo to a backup folder
$source = "photos/birthday.jpg";
$destination = "backup/birthday.jpg";

if (copy($source, $destination)) {
    echo "Photo copied! βœ“";
} else {
    echo "Oops, something went wrong!";
}
?>

πŸ”‘ Key Points

What How
Function copy($from, $to)
Returns true if success, false if fail
Original Stays untouched

🚚 File Moving and Renaming: The Great Migration!

What is Moving/Renaming?

Imagine picking up your toy box and carrying it to another room. The toy box is now in the NEW room, and the OLD room is empty!

Renaming is like putting a new name tag on your toy box.

PHP uses rename() for BOTH moving AND renaming!

The Magic Spell

// Moving a file
rename("room1/toy.txt", "room2/toy.txt");

// Renaming a file
rename("old_name.txt", "new_name.txt");

// Move AND rename at once!
rename("room1/old.txt", "room2/new.txt");

Real Example

<?php
// Move a downloaded file to Documents
$old = "downloads/report.pdf";
$new = "documents/report.pdf";

if (rename($old, $new)) {
    echo "File moved successfully! 🚚";
} else {
    echo "Moving failed!";
}

// Just rename a file
rename("draft.txt", "final.txt");
echo "File renamed! ✏️";
?>

πŸ’‘ Remember

  • rename() = Moving truck + Name tag changer
  • Original location becomes empty
  • File ends up at new location

πŸ—‘οΈ File Deletion: The Eraser Power!

What is File Deletion?

Like using an eraser on a drawing β€” poof! It’s gone forever!

PHP uses unlink() to delete files. (Strange name, right? Think of it as β€œunlinking” the file from existence!)

The Magic Spell

unlink("unwanted_file.txt");

Real Example

<?php
$file = "temp/old_data.txt";

// Safety check: Does file exist?
if (file_exists($file)) {
    if (unlink($file)) {
        echo "File deleted! πŸ—‘οΈ";
    } else {
        echo "Couldn't delete!";
    }
} else {
    echo "File doesn't exist!";
}
?>

⚠️ Warning!

  • Deleted files are GONE FOREVER
  • No recycle bin!
  • Always check with file_exists() first!

πŸ“ Directory Creation: Building New Drawers!

What is Directory Creation?

Like adding a new drawer to your filing cabinet! You need a place to organize new papers.

PHP uses mkdir() (make directory) to create folders.

The Magic Spell

mkdir("new_folder");

Real Example

<?php
// Create a simple folder
mkdir("photos");

// Create nested folders (parent folders too!)
// The "true" means "create parents if needed"
mkdir("projects/2024/january", 0755, true);

echo "Folders created! πŸ“";
?>

🎯 The Three Inputs

mkdir($path, $permissions, $recursive);
Input What It Does
$path Folder name/path
$permissions Who can access (0755 = everyone can read)
$recursive true = create parent folders too

πŸ“œ Directory Listing: What’s Inside?

What is Directory Listing?

Like opening a drawer and seeing all the papers inside! You want to know what files are in a folder.

PHP gives us several ways:

  • scandir() β€” Quick list
  • opendir() + readdir() β€” Read one by one

The Magic Spells

Quick Way (scandir):

<?php
$files = scandir("my_folder");
print_r($files);
// Shows: [".", "..", "file1.txt", "file2.txt"]
?>

One-by-One Way:

<?php
$folder = opendir("my_folder");

while ($file = readdir($folder)) {
    if ($file != "." && $file != "..") {
        echo $file . "\n";
    }
}

closedir($folder);
?>

πŸ” What are . and ..?

Symbol Meaning
. Current folder (this drawer)
.. Parent folder (the cabinet)

🧹 Directory Deletion: Removing Drawers!

What is Directory Deletion?

Like removing an entire drawer from your cabinet! But there’s a rule: the drawer must be EMPTY first!

PHP uses rmdir() to delete folders.

The Magic Spell

rmdir("empty_folder");

Real Example

<?php
$folder = "old_projects";

// Check if folder is empty first
if (is_dir($folder)) {
    // Try to delete
    if (rmdir($folder)) {
        echo "Folder removed! 🧹";
    } else {
        echo "Folder not empty!";
    }
}
?>

🚨 Important Rule!

  • rmdir() only works on EMPTY folders
  • To delete a folder with files, you must:
    1. Delete all files inside first
    2. Then delete the folder

Delete Folder with Contents

<?php
function deleteFolder($path) {
    $files = scandir($path);

    foreach ($files as $file) {
        if ($file == "." || $file == "..") {
            continue;
        }

        $fullPath = $path . "/" . $file;

        if (is_dir($fullPath)) {
            deleteFolder($fullPath);
        } else {
            unlink($fullPath);
        }
    }

    rmdir($path);
}

deleteFolder("old_project");
echo "Everything deleted! πŸ’¨";
?>

🏷️ Path Information: Reading the Labels!

What is Path Information?

Like reading the label on a folder that tells you:

  • What’s the folder name?
  • What’s the file name?
  • What’s the file type?

PHP gives us handy functions to break apart file paths!

The Magic Functions

<?php
$path = "/home/user/docs/report.pdf";

// Get just the file name
echo basename($path);
// Output: report.pdf

// Get just the folder path
echo dirname($path);
// Output: /home/user/docs

// Get everything in pieces
$info = pathinfo($path);
print_r($info);
?>

🧩 pathinfo() Returns All Pieces!

$info = pathinfo("/home/user/report.pdf");
Key Value Meaning
dirname /home/user Folder path
basename report.pdf Full file name
extension pdf File type
filename report Name without extension

Real Example

<?php
$file = "uploads/photos/vacation.jpg";

// Extract each part
echo "Folder: " . dirname($file);
// Folder: uploads/photos

echo "File: " . basename($file);
// File: vacation.jpg

$parts = pathinfo($file);
echo "Type: " . $parts['extension'];
// Type: jpg

echo "Name only: " . $parts['filename'];
// Name only: vacation
?>

πŸ—ΊοΈ The Complete Picture

graph LR A["πŸ“ PHP Filesystem"] --> B["πŸ“„ File Operations"] A --> C["πŸ“‚ Directory Operations"] A --> D["🏷️ Path Operations"] B --> B1["copy - Make twins"] B --> B2["rename - Move/Rename"] B --> B3["unlink - Delete"] C --> C1["mkdir - Create folder"] C --> C2["scandir - List contents"] C --> C3["rmdir - Delete folder"] D --> D1["basename - Get filename"] D --> D2["dirname - Get folder path"] D --> D3["pathinfo - Get all parts"]

🎯 Quick Reference Table

Task Function Example
Copy file copy() copy("a.txt", "b.txt")
Move file rename() rename("old/a.txt", "new/a.txt")
Rename file rename() rename("old.txt", "new.txt")
Delete file unlink() unlink("trash.txt")
Create folder mkdir() mkdir("photos", 0755, true)
List folder scandir() $files = scandir("folder")
Delete folder rmdir() rmdir("empty_folder")
Get filename basename() basename("/path/file.txt")
Get folder dirname() dirname("/path/file.txt")
Get all parts pathinfo() pathinfo("/path/file.txt")

🌟 You Did It!

You now have the power to:

  • βœ… Copy files like a photocopier
  • βœ… Move and rename files like a moving truck
  • βœ… Delete files like an eraser
  • βœ… Create folders like adding drawers
  • βœ… List folder contents like reading labels
  • βœ… Remove folders like taking out drawers
  • βœ… Read path information like a detective

Your filing cabinet has no limits now! πŸŽ‰

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.