File Handling and I/O Operations in PHP
File handling is essential for storing data, processing uploads, generating reports, and managing application state. PHP provides comprehensive file I/O capabilities through built-in functions and file stream wrappers.
This lesson covers everything from basic file operations to advanced techniques like streaming large files, working with CSV/JSON data, and securing file uploads.
PHP offers multiple approaches for reading and writing files, from simple one-liners to advanced stream handling.
Simple File Reading:
1<?php
2declare(strict_types=1);
3
4// Read entire file into string
5$content = file_get_contents('data.txt');
6echo $content;
7
8// Read file into array (one line per element)
9$lines = file('data.txt');
10foreach ($lines as $line) {
11 echo $line;
12}
13
14// Read file line by line (memory efficient)
15$file = fopen('data.txt', 'r');
16while (!feof($file)) {
17 $line = fgets($file);
18 echo $line;
19}
20fclose($file);
21
22// Read specific number of bytes
23$file = fopen('data.txt', 'r');
24$chunk = fread($file, 1024); // Read 1KB
25fclose($file);
26?>Simple File Writing:
1<?php
2// Write string to file (overwrites existing content)
3file_put_contents('output.txt', 'Hello, World!');
4
5// Append to file
6file_put_contents('log.txt', "Log entry\n", FILE_APPEND);
7
8// Write with exclusive lock
9file_put_contents(
10 'config.txt',
11 'Setting=Value',
12 LOCK_EX
13);
14
15// Write using file handle
16$file = fopen('data.txt', 'w');
17fwrite($file, "Line 1\n");
18fwrite($file, "Line 2\n");
19fclose($file);
20?>File Modes:
1<?php
2// 'r' - Read only, pointer at beginning
3// 'r+' - Read/write, pointer at beginning
4// 'w' - Write only, truncates file or creates new
5// 'w+' - Read/write, truncates file or creates new
6// 'a' - Append, pointer at end, creates if doesn't exist
7// 'a+' - Read/append, pointer at end, creates if doesn't exist
8// 'x' - Create and open for write only, fails if exists
9// 'x+' - Create and open for read/write, fails if exists
10// 'c' - Open for writing, creates if doesn't exist, doesn't truncate
11// 'c+' - Open for read/write, creates if doesn't exist, doesn't truncate
12
13$file = fopen('data.txt', 'r+');
14// Read and write operations
15fclose($file);
16?>Binary File Handling:
1<?php
2// Read binary file
3$image = file_get_contents('photo.jpg');
4
5// Write binary file
6file_put_contents('copy.jpg', $image);
7
8// Read binary with chunks
9$source = fopen('video.mp4', 'rb');
10$dest = fopen('copy.mp4', 'wb');
11
12while (!feof($source)) {
13 $chunk = fread($source, 8192); // 8KB chunks
14 fwrite($dest, $chunk);
15}
16
17fclose($source);
18fclose($dest);
19?>File Locking:
1<?php
2function appendToLog(string $message): void {
3 $file = fopen('app.log', 'a');
4
5 // Acquire exclusive lock
6 if (flock($file, LOCK_EX)) {
7 fwrite($file, date('Y-m-d H:i:s') . " - $message\n");
8
9 // Release lock
10 flock($file, LOCK_UN);
11 }
12
13 fclose($file);
14}
15
16// Safe for concurrent writes
17appendToLog("User logged in");
18appendToLog("User logged out");
19?>PHP provides comprehensive functions for working with the file system.
File Information:
1<?php
2declare(strict_types=1);
3
4$file = 'document.pdf';
5
6// Check if file exists
7if (file_exists($file)) {
8 echo "File exists\n";
9}
10
11// Check if path is a file
12if (is_file($file)) {
13 echo "Is a file\n";
14}
15
16// Check if path is a directory
17if (is_dir('uploads')) {
18 echo "Is a directory\n";
19}
20
21// Check if file is readable/writable
22if (is_readable($file)) {
23 echo "File is readable\n";
24}
25
26if (is_writable($file)) {
27 echo "File is writable\n";
28}
29
30// Get file size
31$size = filesize($file);
32echo "Size: " . number_format($size) . " bytes\n";
33
34// Get file modification time
35$mtime = filemtime($file);
36echo "Modified: " . date('Y-m-d H:i:s', $mtime) . "\n";
37
38// Get file permissions
39$perms = fileperms($file);
40echo "Permissions: " . substr(sprintf('%o', $perms), -4) . "\n";
41?>File Operations:
1<?php
2// Copy file
3copy('source.txt', 'destination.txt');
4
5// Rename/move file
6rename('old_name.txt', 'new_name.txt');
7
8// Delete file
9unlink('temp.txt');
10
11// Create symbolic link
12symlink('target.txt', 'link.txt');
13
14// Get file extension
15$ext = pathinfo('document.pdf', PATHINFO_EXTENSION);
16echo "Extension: $ext\n"; // pdf
17
18// Get filename without extension
19$name = pathinfo('document.pdf', PATHINFO_FILENAME);
20echo "Filename: $name\n"; // document
21
22// Get directory name
23$dir = dirname('/var/www/html/index.php');
24echo "Directory: $dir\n"; // /var/www/html
25
26// Get base name
27$base = basename('/var/www/html/index.php');
28echo "Basename: $base\n"; // index.php
29?>Directory Operations:
1<?php
2// Create directory
3mkdir('uploads');
4
5// Create nested directories
6mkdir('uploads/images/thumbnails', 0755, true);
7
8// Remove empty directory
9rmdir('temp');
10
11// Change current directory
12chdir('/var/www');
13echo "Current directory: " . getcwd() . "\n";
14
15// List directory contents
16$files = scandir('.');
17foreach ($files as $file) {
18 echo "$file\n";
19}
20
21// Recursive directory iterator
22function listFilesRecursive(string $dir): void {
23 $items = scandir($dir);
24
25 foreach ($items as $item) {
26 if ($item === '.' || $item === '..') {
27 continue;
28 }
29
30 $path = $dir . DIRECTORY_SEPARATOR . $item;
31
32 if (is_dir($path)) {
33 echo "[DIR] $path\n";
34 listFilesRecursive($path);
35 } else {
36 echo "[FILE] $path\n";
37 }
38 }
39}
40
41listFilesRecursive('.');
42?>Glob Patterns:
1<?php
2// Find all PHP files
3$phpFiles = glob('*.php');
4
5// Find all files in subdirectories
6$allFiles = glob('**/*.txt', GLOB_BRACE);
7
8// Find files with multiple patterns
9$images = glob('{*.jpg,*.png,*.gif}', GLOB_BRACE);
10
11// Check if files exist
12if (count($phpFiles) > 0) {
13 echo "Found " . count($phpFiles) . " PHP files\n";
14}
15
16// Process each file
17foreach ($images as $image) {
18 echo "Image: $image\n";
19}
20?>CSV (Comma-Separated Values) files are commonly used for data import/export.
Reading CSV Files:
1<?php
2declare(strict_types=1);
3
4// Simple CSV reading
5$file = fopen('data.csv', 'r');
6
7// Read header
8$header = fgetcsv($file);
9
10// Read data rows
11$data = [];
12while (($row = fgetcsv($file)) !== false) {
13 $data[] = array_combine($header, $row);
14}
15
16fclose($file);
17
18print_r($data);
19
20// Using callback
21function processCSV(string $filename, callable $callback): void {
22 $file = fopen($filename, 'r');
23 $header = fgetcsv($file);
24
25 while (($row = fgetcsv($file)) !== false) {
26 $callback(array_combine($header, $row));
27 }
28
29 fclose($file);
30}
31
32processCSV('users.csv', function($user) {
33 echo "Processing: {$user['name']}\n";
34});
35?>Writing CSV Files:
1<?php
2$users = [
3 ['id' => 1, 'name' => 'John Doe', 'email' => '[email protected]'],
4 ['id' => 2, 'name' => 'Jane Smith', 'email' => '[email protected]'],
5 ['id' => 3, 'name' => 'Bob Johnson', 'email' => '[email protected]']
6];
7
8$file = fopen('export.csv', 'w');
9
10// Write header
11fputcsv($file, ['ID', 'Name', 'Email']);
12
13// Write data
14foreach ($users as $user) {
15 fputcsv($file, $user);
16}
17
18fclose($file);
19
20echo "CSV file created: export.csv\n";
21?>Advanced CSV Processing:
1<?php
2class CSVReader {
3 private $file;
4 private array $header = [];
5
6 public function __construct(string $filename) {
7 $this->file = fopen($filename, 'r');
8 $this->header = fgetcsv($this->file) ?: [];
9 }
10
11 public function __destruct() {
12 if (is_resource($this->file)) {
13 fclose($this->file);
14 }
15 }
16
17 public function getRows(): \Generator {
18 while (($row = fgetcsv($this->file)) !== false) {
19 yield array_combine($this->header, $row);
20 }
21 }
22
23 public function filter(callable $callback): array {
24 $results = [];
25 foreach ($this->getRows() as $row) {
26 if ($callback($row)) {
27 $results[] = $row;
28 }
29 }
30 return $results;
31 }
32
33 public function map(callable $callback): array {
34 $results = [];
35 foreach ($this->getRows() as $row) {
36 $results[] = $callback($row);
37 }
38 return $results;
39 }
40}
41
42// Usage
43$csv = new CSVReader('data.csv');
44
45// Filter rows
46$filtered = $csv->filter(fn($row) => $row['age'] > 18);
47
48// Transform rows
49$names = $csv->map(fn($row) => $row['name']);
50?>JSON is the standard format for storing and exchanging structured data.
Reading JSON Files:
1<?php
2declare(strict_types=1);
3
4// Read JSON file
5$json = file_get_contents('config.json');
6$data = json_decode($json, true);
7
8// Check for errors
9if (json_last_error() !== JSON_ERROR_NONE) {
10 throw new Exception('JSON decode error: ' . json_last_error_msg());
11}
12
13print_r($data);
14
15// With error handling
16function readJSON(string $filename): array {
17 if (!file_exists($filename)) {
18 throw new Exception("File not found: $filename");
19 }
20
21 $json = file_get_contents($filename);
22 $data = json_decode($json, true);
23
24 if (json_last_error() !== JSON_ERROR_NONE) {
25 throw new Exception(
26 "Invalid JSON in $filename: " . json_last_error_msg()
27 );
28 }
29
30 return $data;
31}
32
33try {
34 $config = readJSON('config.json');
35} catch (Exception $e) {
36 echo "Error: " . $e->getMessage() . "\n";
37}
38?>Writing JSON Files:
1<?php
2$data = [
3 'app' => [
4 'name' => 'My Application',
5 'version' => '1.0.0',
6 'debug' => true
7 ],
8 'database' => [
9 'host' => 'localhost',
10 'port' => 3306,
11 'name' => 'myapp'
12 ]
13];
14
15// Write JSON with pretty formatting
16file_put_contents(
17 'config.json',
18 json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
19);
20
21// Write JSON safely
22function writeJSON(string $filename, array $data): void {
23 $json = json_encode(
24 $data,
25 JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
26 );
27
28 if ($json === false) {
29 throw new Exception('JSON encode error: ' . json_last_error_msg());
30 }
31
32 $result = file_put_contents($filename, $json, LOCK_EX);
33
34 if ($result === false) {
35 throw new Exception("Failed to write file: $filename");
36 }
37}
38
39writeJSON('output.json', $data);
40?>JSON Data Store:
1<?php
2class JSONStore {
3 public function __construct(private string $filename) {
4 if (!file_exists($filename)) {
5 file_put_contents($filename, '[]');
6 }
7 }
8
9 public function read(): array {
10 $json = file_get_contents($this->filename);
11 return json_decode($json, true) ?: [];
12 }
13
14 public function write(array $data): void {
15 $json = json_encode($data, JSON_PRETTY_PRINT);
16 file_put_contents($this->filename, $json, LOCK_EX);
17 }
18
19 public function add(array $item): void {
20 $data = $this->read();
21 $data[] = $item;
22 $this->write($data);
23 }
24
25 public function find(callable $callback): ?array {
26 $data = $this->read();
27 foreach ($data as $item) {
28 if ($callback($item)) {
29 return $item;
30 }
31 }
32 return null;
33 }
34
35 public function update(callable $finder, array $updates): bool {
36 $data = $this->read();
37 foreach ($data as $key => $item) {
38 if ($finder($item)) {
39 $data[$key] = array_merge($item, $updates);
40 $this->write($data);
41 return true;
42 }
43 }
44 return false;
45 }
46
47 public function delete(callable $finder): bool {
48 $data = $this->read();
49 $originalCount = count($data);
50
51 $data = array_filter($data, fn($item) => !$finder($item));
52
53 if (count($data) < $originalCount) {
54 $this->write(array_values($data));
55 return true;
56 }
57
58 return false;
59 }
60}
61
62// Usage
63$store = new JSONStore('users.json');
64
65// Add user
66$store->add(['id' => 1, 'name' => 'John', 'email' => '[email protected]']);
67
68// Find user
69$user = $store->find(fn($u) => $u['id'] === 1);
70
71// Update user
72$store->update(
73 fn($u) => $u['id'] === 1,
74 ['email' => '[email protected]']
75);
76
77// Delete user
78$store->delete(fn($u) => $u['id'] === 1);
79?>Handling file uploads securely is critical for application security.
Basic File Upload:
1<?php
2declare(strict_types=1);
3
4if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['upload'])) {
5 $file = $_FILES['upload'];
6
7 // Check for upload errors
8 if ($file['error'] !== UPLOAD_ERR_OK) {
9 $error = match($file['error']) {
10 UPLOAD_ERR_INI_SIZE => 'File too large (server limit)',
11 UPLOAD_ERR_FORM_SIZE => 'File too large (form limit)',
12 UPLOAD_ERR_PARTIAL => 'File partially uploaded',
13 UPLOAD_ERR_NO_FILE => 'No file uploaded',
14 default => 'Upload error'
15 };
16 throw new Exception($error);
17 }
18
19 // Move uploaded file
20 $destination = 'uploads/' . basename($file['name']);
21 if (!move_uploaded_file($file['tmp_name'], $destination)) {
22 throw new Exception('Failed to move uploaded file');
23 }
24
25 echo "File uploaded: $destination\n";
26}
27?>Secure File Upload:
1<?php
2class FileUploader {
3 private int $maxSize = 5242880; // 5MB
4 private array $allowedTypes = [
5 'image/jpeg',
6 'image/png',
7 'image/gif'
8 ];
9 private string $uploadDir = 'uploads/';
10
11 public function upload(array $file): string {
12 // Validate upload
13 $this->validateUpload($file);
14
15 // Generate unique filename
16 $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
17 $filename = bin2hex(random_bytes(16)) . '.' . $extension;
18 $destination = $this->uploadDir . $filename;
19
20 // Create upload directory if needed
21 if (!is_dir($this->uploadDir)) {
22 mkdir($this->uploadDir, 0755, true);
23 }
24
25 // Move file
26 if (!move_uploaded_file($file['tmp_name'], $destination)) {
27 throw new Exception('Failed to save file');
28 }
29
30 return $destination;
31 }
32
33 private function validateUpload(array $file): void {
34 // Check for errors
35 if ($file['error'] !== UPLOAD_ERR_OK) {
36 throw new Exception('Upload error');
37 }
38
39 // Check file size
40 if ($file['size'] > $this->maxSize) {
41 throw new Exception('File too large. Max: 5MB');
42 }
43
44 // Check MIME type
45 $finfo = finfo_open(FILEINFO_MIME_TYPE);
46 $mimeType = finfo_file($finfo, $file['tmp_name']);
47 finfo_close($finfo);
48
49 if (!in_array($mimeType, $this->allowedTypes)) {
50 throw new Exception('Invalid file type');
51 }
52
53 // Check file extension
54 $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
55 $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
56
57 if (!in_array($extension, $allowedExtensions)) {
58 throw new Exception('Invalid file extension');
59 }
60 }
61}
62
63// Usage
64try {
65 $uploader = new FileUploader();
66 $path = $uploader->upload($_FILES['image']);
67 echo "File saved: $path\n";
68} catch (Exception $e) {
69 echo "Upload failed: " . $e->getMessage() . "\n";
70}
71?>Image Upload with Validation:
1<?php
2class ImageUploader extends FileUploader {
3 public function upload(array $file): string {
4 parent::upload($file);
5
6 // Additional image validation
7 $imageInfo = getimagesize($file['tmp_name']);
8
9 if ($imageInfo === false) {
10 throw new Exception('Invalid image file');
11 }
12
13 [$width, $height] = $imageInfo;
14
15 // Check dimensions
16 if ($width > 4000 || $height > 4000) {
17 throw new Exception('Image too large. Max: 4000x4000');
18 }
19
20 if ($width < 100 || $height < 100) {
21 throw new Exception('Image too small. Min: 100x100');
22 }
23
24 // Continue with upload
25 return parent::upload($file);
26 }
27}
28?>Building a Complete File Manager System
1<?php
2declare(strict_types=1);
3
4/**
5 * Complete File Manager System
6 *
7 * Demonstrates:
8 * - File and directory operations
9 * - CSV and JSON file handling
10 * - Secure file uploads
11 * - File search and filtering
12 * - Error handling
13 * - Data persistence
14 */
15
16// ==================== FILE MANAGER ====================
17
18class FileManager {
19 public function __construct(private string $baseDir) {
20 if (!is_dir($baseDir)) {
21 mkdir($baseDir, 0755, true);
22 }
23 }
24
25 public function listFiles(string $subDir = ''): array {
26 $path = $this->getFullPath($subDir);
27 $files = [];
28
29 if (!is_dir($path)) {
30 return $files;
31 }
32
33 $items = scandir($path);
34
35 foreach ($items as $item) {
36 if ($item === '.' || $item === '..') {
37 continue;
38 }
39
40 $fullPath = $path . DIRECTORY_SEPARATOR . $item;
41 $relativePath = $subDir ? $subDir . '/' . $item : $item;
42
43 $files[] = [
44 'name' => $item,
45 'path' => $relativePath,
46 'type' => is_dir($fullPath) ? 'directory' : 'file',
47 'size' => is_file($fullPath) ? filesize($fullPath) : 0,
48 'modified' => filemtime($fullPath)
49 ];
50 }
51
52 return $files;
53 }
54
55 public function createDirectory(string $name): bool {
56 $path = $this->getFullPath($name);
57
58 if (is_dir($path)) {
59 throw new \Exception("Directory already exists: $name");
60 }
61
62 return mkdir($path, 0755, true);
63 }
64
65 public function deleteFile(string $path): bool {
66 $fullPath = $this->getFullPath($path);
67
68 if (!file_exists($fullPath)) {
69 throw new \Exception("File not found: $path");
70 }
71
72 if (is_dir($fullPath)) {
73 throw new \Exception("Cannot delete directory as file: $path");
74 }
75
76 return unlink($fullPath);
77 }
78
79 public function deleteDirectory(string $path): bool {
80 $fullPath = $this->getFullPath($path);
81
82 if (!is_dir($fullPath)) {
83 throw new \Exception("Directory not found: $path");
84 }
85
86 $this->deleteRecursive($fullPath);
87 return true;
88 }
89
90 private function deleteRecursive(string $dir): void {
91 $items = scandir($dir);
92
93 foreach ($items as $item) {
94 if ($item === '.' || $item === '..') {
95 continue;
96 }
97
98 $path = $dir . DIRECTORY_SEPARATOR . $item;
99
100 if (is_dir($path)) {
101 $this->deleteRecursive($path);
102 } else {
103 unlink($path);
104 }
105 }
106
107 rmdir($dir);
108 }
109
110 public function getFileContent(string $path): string {
111 $fullPath = $this->getFullPath($path);
112
113 if (!file_exists($fullPath)) {
114 throw new \Exception("File not found: $path");
115 }
116
117 return file_get_contents($fullPath);
118 }
119
120 public function writeFile(string $path, string $content): bool {
121 $fullPath = $this->getFullPath($path);
122 $dir = dirname($fullPath);
123
124 if (!is_dir($dir)) {
125 mkdir($dir, 0755, true);
126 }
127
128 return file_put_contents($fullPath, $content, LOCK_EX) !== false;
129 }
130
131 public function search(string $pattern): array {
132 $fullPath = $this->baseDir . '/' . $pattern;
133 $files = glob($fullPath);
134 $results = [];
135
136 foreach ($files as $file) {
137 $relativePath = str_replace($this->baseDir . '/', '', $file);
138 $results[] = [
139 'name' => basename($file),
140 'path' => $relativePath,
141 'type' => is_dir($file) ? 'directory' : 'file',
142 'size' => is_file($file) ? filesize($file) : 0
143 ];
144 }
145
146 return $results;
147 }
148
149 private function getFullPath(string $path): string {
150 $fullPath = $this->baseDir . DIRECTORY_SEPARATOR . $path;
151 $realPath = realpath($fullPath) ?: $fullPath;
152
153 // Prevent directory traversal
154 if (!str_starts_with($realPath, $this->baseDir)) {
155 throw new \Exception("Invalid path: $path");
156 }
157
158 return $fullPath;
159 }
160}
161
162// ==================== CSV MANAGER ====================
163
164class CSVManager {
165 public function export(string $filename, array $data): void {
166 if (empty($data)) {
167 throw new \Exception("No data to export");
168 }
169
170 $file = fopen($filename, 'w');
171
172 // Write header
173 fputcsv($file, array_keys($data[0]));
174
175 // Write rows
176 foreach ($data as $row) {
177 fputcsv($file, $row);
178 }
179
180 fclose($file);
181 }
182
183 public function import(string $filename): array {
184 if (!file_exists($filename)) {
185 throw new \Exception("File not found: $filename");
186 }
187
188 $file = fopen($filename, 'r');
189 $header = fgetcsv($file);
190 $data = [];
191
192 while (($row = fgetcsv($file)) !== false) {
193 $data[] = array_combine($header, $row);
194 }
195
196 fclose($file);
197 return $data;
198 }
199}
200
201// ==================== JSON DATABASE ====================
202
203class JSONDatabase {
204 public function __construct(private string $file) {
205 if (!file_exists($file)) {
206 file_put_contents($file, '[]');
207 }
208 }
209
210 public function findAll(): array {
211 $json = file_get_contents($this->file);
212 return json_decode($json, true) ?: [];
213 }
214
215 public function findById(int $id): ?array {
216 $records = $this->findAll();
217 foreach ($records as $record) {
218 if (($record['id'] ?? null) === $id) {
219 return $record;
220 }
221 }
222 return null;
223 }
224
225 public function insert(array $data): array {
226 $records = $this->findAll();
227 $data['id'] = $this->getNextId($records);
228 $records[] = $data;
229 $this->save($records);
230 return $data;
231 }
232
233 public function update(int $id, array $data): bool {
234 $records = $this->findAll();
235 foreach ($records as $key => $record) {
236 if (($record['id'] ?? null) === $id) {
237 $records[$key] = array_merge($record, $data);
238 $this->save($records);
239 return true;
240 }
241 }
242 return false;
243 }
244
245 public function delete(int $id): bool {
246 $records = $this->findAll();
247 $filtered = array_filter($records, fn($r) => ($r['id'] ?? null) !== $id);
248
249 if (count($filtered) < count($records)) {
250 $this->save(array_values($filtered));
251 return true;
252 }
253
254 return false;
255 }
256
257 private function save(array $data): void {
258 $json = json_encode($data, JSON_PRETTY_PRINT);
259 file_put_contents($this->file, $json, LOCK_EX);
260 }
261
262 private function getNextId(array $records): int {
263 if (empty($records)) {
264 return 1;
265 }
266
267 $ids = array_column($records, 'id');
268 return max($ids) + 1;
269 }
270}
271
272// ==================== DEMO ====================
273
274echo str_repeat("=", 60) . "\n";
275echo " š FILE MANAGER SYSTEM DEMO\n";
276echo str_repeat("=", 60) . "\n\n";
277
278// Setup
279$fm = new FileManager('storage');
280$csv = new CSVManager();
281$db = new JSONDatabase('storage/database.json');
282
283// Test 1: Create directories and files
284echo "š Test 1: Creating files and directories\n";
285echo str_repeat("-", 60) . "\n";
286
287$fm->createDirectory('documents');
288$fm->createDirectory('reports');
289$fm->writeFile('documents/readme.txt', 'Welcome to the file manager!');
290$fm->writeFile('reports/monthly.txt', 'Monthly report data...');
291
292echo "Created directories and files\n";
293
294// Test 2: List files
295echo "\nš Test 2: Listing files\n";
296echo str_repeat("-", 60) . "\n";
297
298$files = $fm->listFiles();
299foreach ($files as $file) {
300 $type = $file['type'] === 'directory' ? '[DIR]' : '[FILE]';
301 $size = $file['type'] === 'file' ? " ({$file['size']} bytes)" : '';
302 echo "$type {$file['name']}$size\n";
303}
304
305// Test 3: CSV Export/Import
306echo "\nš Test 3: CSV Operations\n";
307echo str_repeat("-", 60) . "\n";
308
309$users = [
310 ['id' => 1, 'name' => 'John Doe', 'email' => '[email protected]'],
311 ['id' => 2, 'name' => 'Jane Smith', 'email' => '[email protected]'],
312 ['id' => 3, 'name' => 'Bob Johnson', 'email' => '[email protected]']
313];
314
315$csv->export('storage/users.csv', $users);
316echo "Exported users to CSV\n";
317
318$imported = $csv->import('storage/users.csv');
319echo "Imported " . count($imported) . " users from CSV\n";
320
321// Test 4: JSON Database
322echo "\nš¾ Test 4: JSON Database\n";
323echo str_repeat("-", 60) . "\n";
324
325// Insert records
326$user1 = $db->insert(['name' => 'Alice', 'age' => 25]);
327$user2 = $db->insert(['name' => 'Charlie', 'age' => 30]);
328
329echo "Inserted user: {$user1['name']} (ID: {$user1['id']})\n";
330echo "Inserted user: {$user2['name']} (ID: {$user2['id']})\n";
331
332// Find all
333$all = $db->findAll();
334echo "Total records: " . count($all) . "\n";
335
336// Update
337$db->update($user1['id'], ['age' => 26]);
338echo "Updated user {$user1['id']}'s age to 26\n";
339
340// Find by ID
341$found = $db->findById($user1['id']);
342echo "Found user: {$found['name']}, age {$found['age']}\n";
343
344// Test 5: Search files
345echo "\nš Test 5: Searching files\n";
346echo str_repeat("-", 60) . "\n";
347
348$results = $fm->search('*.txt');
349echo "Found " . count($results) . " text files:\n";
350foreach ($results as $result) {
351 echo " - {$result['path']}\n";
352}
353
354// Test 6: Read file content
355echo "\nš Test 6: Reading file content\n";
356echo str_repeat("-", 60) . "\n";
357
358$content = $fm->getFileContent('documents/readme.txt');
359echo "Content: $content\n";
360
361// Test 7: Delete operations
362echo "\nšļø Test 7: Deleting files\n";
363echo str_repeat("-", 60) . "\n";
364
365$fm->deleteFile('reports/monthly.txt');
366echo "Deleted file: reports/monthly.txt\n";
367
368$remaining = $fm->listFiles('reports');
369echo "Remaining files in reports: " . count($remaining) . "\n";
370
371echo "\n" . str_repeat("=", 60) . "\n";
372echo "ā
FILE MANAGER DEMO COMPLETE!\n";
373echo str_repeat("=", 60) . "\n";
374echo "\nšÆ Features Demonstrated:\n";
375echo " ⢠File and directory management\n";
376echo " ⢠CSV export/import\n";
377echo " ⢠JSON database (CRUD operations)\n";
378echo " ⢠File search with patterns\n";
379echo " ⢠Safe path handling\n";
380echo " ⢠File locking for concurrent access\n";
381?>This file manager system demonstrates:
1. FileManager Class:
2. CSVManager Class:
3. JSONDatabase Class:
4. Security Features:
This pattern is useful for small applications needing simple data persistence!
Your progress is saved in this browser, on this device only.