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%

2. Directories & File Info

Lesson 22 of 36 in the free Web Based Programming notes on Siksha Sarovar, written by Rohit Jangra.

Directory Management & File Information in PHP

1. What is a Directory?

Definition: A Directory (also called a folder) is a container in a file system used to organize files and subdirectories. PHP provides a rich set of functions to programmatically create, navigate, list, and delete directories.

Path Types:

TypeDescriptionExample
Absolute PathFull path from the root of the file systemC:/xampp/htdocs/myapp/uploads/
Relative PathPath relative to the location of the current PHP script./uploads/ or ../images/

2. Core Directory Functions

a) mkdir() — Create a Directory:

// Create a single directory
if (!file_exists("uploads")) {
  mkdir("uploads", 0777); // 0777 = full permissions
  echo "Directory 'uploads' created!";
}

// Create nested directories (recursive)
mkdir("uploads/images/thumbnails", 0777, true); // true = recursive

b) rmdir() — Remove a Directory: rmdir() only works on empty directories. To delete a directory with files, delete the files first.

if (is_dir("temp_folder") && count(scandir("temp_folder")) == 2) {
  rmdir("temp_folder"); // Only succeeds if empty (2 = . and ..)
  echo "Directory deleted!";
}

c) scandir() — List Directory Contents: Returns an array of all filenames and subdirectory names in a given path (always includes . and ..).

$files = scandir("uploads");
foreach ($files as $file) {
  if ($file != "." && $file != "..") { // Skip . and ..
    echo $file . "<br>";
  }
}

d) getcwd() — Get Current Working Directory:

echo getcwd(); // e.g., C:/xampp/htdocs/myapp

e) chdir() — Change Current Directory:

chdir("uploads");
echo getcwd(); // C:/xampp/htdocs/myapp/uploads

3. File Information Functions

FunctionReturn ValueUse Case
file_exists($path)bool (true/false)Check if file or directory exists
is_file($path)boolCheck if path points to a regular file
is_dir($path)boolCheck if path points to a directory
filesize($path)int (bytes)Get size of a file in bytes
filetype($path)string ('file','dir','link')Get the type of a file system entry
filemtime($path)int (Unix timestamp)Get the last modified time
pathinfo($path)arrayGet dirname, basename, extension, filename
realpath($path)stringResolve to absolute canonical path
$file = "uploads/photo.jpg";

if (file_exists($file)) {
  echo "File: " . basename($file) . "<br>";          // photo.jpg
  echo "Size: " . filesize($file) . " bytes<br>";    // e.g., 45210 bytes
  echo "Extension: " . pathinfo($file, PATHINFO_EXTENSION) . "<br>"; // jpg
  echo "Modified: " . date("d M Y", filemtime($file)) . "<br>";
} else {
  echo "File not found!";
}

4. File Upload Process (Complete Walkthrough)

File uploads are handled via a multipart HTML form and the $_FILES superglobal.

Step 1: HTML Form The form MUST have method="POST" and enctype="multipart/form-data".

<form action="upload.php" method="POST" enctype="multipart/form-data">
  Select file: <input type="file" name="uploadedFile"><br>
  <input type="submit" value="Upload File">
</form>

Step 2: Understanding $_FILES

KeyDescription
$_FILES['name']['name']Original name of the file on the client
$_FILES['name']['type']MIME type (e.g., image/jpeg, text/plain)
$_FILES['name']['size']Size in bytes
$_FILES['name']['tmp_name']Temp path where file is stored on server
$_FILES['name']['error']Error code (0 = no error)

Step 3: PHP (upload.php) with Validation:

<?php
$targetDir = "uploads/";
$fileName  = basename($_FILES["uploadedFile"]["name"]);
$filePath  = $targetDir . $fileName;
$fileType  = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
$fileSize  = $_FILES["uploadedFile"]["size"];

// Validate: allowed types and max size (2MB)
$allowedTypes = ["jpg", "jpeg", "png", "pdf"];
$maxSize      = 2 * 1024 * 1024; // 2MB

if (!in_array($fileType, $allowedTypes)) {
  echo "Error: Only JPG, PNG, and PDF files are allowed.";
} elseif ($fileSize > $maxSize) {
  echo "Error: File is too large (max 2MB).";
} elseif (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $filePath)) {
  echo "File '{$fileName}' uploaded successfully!";
} else {
  echo "Upload failed. Please try again.";
}
?>