Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Practical 18: PHP Library Functions for Files and Directories

Lesson 25 of 35 in the free Web Based Programming Lab notes on Siksha Sarovar, written by Rohit Jangra.

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) returns true for 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 returns true/false.
  • Directories: mkdir($p) creates one (warning and false if it already exists — pair it with is_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 to scandir().

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

  1. Start Apache from the XAMPP Control Panel (or just open a terminal).
  2. Save the snippet as p18_file_library.php in C:\xampp\htdocs\wbplab.
  3. Open http://localhost/wbplab/p18_file_library.php, or run php p18_file_library.php.
  4. 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

  • $baseDir is the system temp directory plus wbp_lib_demo_ and a uniqid() suffix; mkdir($baseDir) creates that sandbox for the run.
  • file_put_contents($fileA, "Line 1\nLine 2") creates notes.txt with two lines — 13 bytes: six characters per line plus one newline.
  • copy($fileA, $fileB) duplicates it as notes_copy.txt; rename($fileB, $renamed) then turns the copy into notes_final.txt — after this the old name no longer exists.
  • The echo block reports basename() (notes.txt), the pathinfo() extension (txt), file_exists() rendered as YES/NO through a ternary, and filesize() 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 can rmdir($baseDir) succeed, because rmdir refuses 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

  1. What does scandir() return that a listing usually filters out? The pseudo-entries . (current directory) and .. (parent), which appear in every directory listing.
  2. rename() vs copy()? 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.
  3. Why can rmdir() fail on an existing directory? It removes only empty directories; the contents must first be unlink()ed (or removed recursively).
  4. What happens if unlink() is called on a directory? It fails with a warning — unlink() handles files only; directories need rmdir().
  5. What do filesize() and filemtime() return, and what is the stat cache? Byte count and last-modified Unix timestamp; PHP caches these per path, so clearstatcache() is needed for fresh values after outside changes.
  6. When would glob() beat scandir()? When only matching files are wanted — glob("*.txt") returns pre-filtered paths with no manual loop over every entry.

CO Mapping

CO1, CO2