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:
| Type | Description | Example |
|---|---|---|
| Absolute Path | Full path from the root of the file system | C:/xampp/htdocs/myapp/uploads/ |
| Relative Path | Path 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
| Function | Return Value | Use Case |
|---|---|---|
file_exists($path) | bool (true/false) | Check if file or directory exists |
is_file($path) | bool | Check if path points to a regular file |
is_dir($path) | bool | Check 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) | array | Get dirname, basename, extension, filename |
realpath($path) | string | Resolve 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
| Key | Description |
|---|---|
$_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.";
}
?>