Aim
To use PHP's built-in library functions for files and directories — creating, copying, renaming, inspecting, listing and deleting — in one self-cleaning demonstration.
Theory
PHP's filesystem library divides into three families:
- Information:
file_exists($p)returnstruefor files and directories;filesize($p)gives the size in bytes;filemtime($p)the last-modified Unix timestamp;basename($p)the final path component;dirname($p)the parent directory;pathinfo($p, PATHINFO_EXTENSION)extracts one component (extension, filename, dirname) from a path. These results are cached per request —clearstatcache()refreshes them after external changes. - File manipulation:
copy($src, $dst)duplicates a file and returns a boolean;rename($old, $new)renames or moves — it is PHP's move function;unlink($p)deletes a file (never a directory) and returnstrue/false. - Directories:
mkdir($p)creates one (warning andfalseif it already exists — pair it withis_dir());rmdir($p)removes one only if it is empty;scandir($p)returns an alphabetically sorted array of entries including the pseudo-entries.and..;glob("*.txt")returns an array of paths matching a shell-style pattern — a pre-filtered alternative toscandir().
Almost all of these return false on failure, so production code wraps them in checks. The demo also uses uniqid() so every run works inside a brand-new directory and can never collide with a previous run.
Requirements
- XAMPP/WAMP with Apache and PHP 8.x, or the PHP CLI / an online PHP compiler
- Code editor (VS Code); browser or terminal
Procedure
- Start Apache from the XAMPP Control Panel (or just open a terminal).
- Save the snippet as
p18_file_library.phpinC:\xampp\htdocs\wbplab. - Open
http://localhost/wbplab/p18_file_library.php, or runphp p18_file_library.php. - Read the output top to bottom — it narrates each function call; because the script deletes everything it made at the end, it can be re-run cleanly any number of times.
Explanation of the Code
$baseDiris the system temp directory pluswbp_lib_demo_and auniqid()suffix;mkdir($baseDir)creates that sandbox for the run.file_put_contents($fileA, "Line 1\nLine 2")createsnotes.txtwith two lines — 13 bytes: six characters per line plus one newline.copy($fileA, $fileB)duplicates it asnotes_copy.txt;rename($fileB, $renamed)then turns the copy intonotes_final.txt— after this the old name no longer exists.- The echo block reports
basename()(notes.txt), thepathinfo()extension (txt),file_exists()rendered asYES/NOthrough a ternary, andfilesize()in bytes. - The
foreach (scandir($baseDir) …)loop lists the directory while explicitly skipping.and..— the standard idiom. - Cleanup order matters: both files are removed with
unlink()first, and only then canrmdir($baseDir)succeed, becausermdirrefuses non-empty directories.
Expected Output
Directory created: with a path ending in wbp_lib_demo_<unique-id> (different every run), then basename(fileA): notes.txt, pathinfo(fileA) extension: txt, file_exists(fileA): YES and filesize(fileA): 13 bytes. The Directory listing using scandir(): block shows exactly two bullets — - notes.txt and - notes_final.txt (the copy exists only under its renamed name). The run ends with Cleanup completed.
🎯 Viva Questions
- What does
scandir()return that a listing usually filters out? The pseudo-entries.(current directory) and..(parent), which appear in every directory listing. rename()vscopy()?copy()duplicates and leaves the source in place;rename()moves — the old path disappears — and it works across directories, making it PHP's move function.- Why can
rmdir()fail on an existing directory? It removes only empty directories; the contents must first beunlink()ed (or removed recursively). - What happens if
unlink()is called on a directory? It fails with a warning —unlink()handles files only; directories needrmdir(). - What do
filesize()andfilemtime()return, and what is the stat cache? Byte count and last-modified Unix timestamp; PHP caches these per path, soclearstatcache()is needed for fresh values after outside changes. - When would
glob()beatscandir()? When only matching files are wanted —glob("*.txt")returns pre-filtered paths with no manual loop over every entry.
CO Mapping
CO1, CO2