Directory Management
Directories are the foundation of a clean and organized file system. Trongate's File module provides a streamlined interface for managing folders, handling path validation and recursive creation automatically.
The Two Core Methods
All directory operations are accessed via $this->file from within your controllers:
- - Creates directories with specified permissions.
- - Returns a structured array of files and subdirectories.
Understanding Directory Permissions
Permissions control who can read, write, or enter your directories. In a web environment, your PHP code typically runs as the www-data or apache user. If this user does not have the correct permissions, your application will fail.
Understanding Octal Permissions: Read (4) + Write (2) + Execute (1)
Unix/Linux file permissions are represented numerically in octal format. Each permission level is calculated by adding three base values to create a single digit (0–7):
| Permission | Value | Description |
|---|---|---|
| Read | 4 | Allows listing the contents of the directory (e.g., seeing file names with ls). |
| Write | 2 | Allows creating, deleting, or renaming files inside the directory. |
| Execute | 1 | Allows entering the directory (cd into it) and accessing files/subdirectories inside (traversing the directory). |
By adding these values together, you determine the permission level for a category. Common examples:
- 4 (Read) + 1 (Execute) = 5 - Can list contents and enter the directory, but cannot modify anything.
- 4 (Read) + 2 (Write) + 1 (Execute) = 7 - Full control (read, write, and execute).
- 4 (Read) + 2 (Write) = 6 - Can read and modify contents, but not execute/traverse.
Note: The meaning of "execute" differs slightly between files and directories:
- On directories: Allows traversal and access to contents (required for
cdand most operations inside). - On files: Allows running the file as a program/script.
0755 for directories and 0644 for files.
The Full Octal Code: Owner, Group, and Others
We combine three (or four) digits to set permissions separately for the owner, group, and others:
0755
│││
││└─ Others (everyone else on the server): 5 → Read + Execute
│└── Group (users in the same group): 5 → Read + Execute
└─── Owner (you or the web server/PHP process): 7 → Full access (Read + Write + Execute)Security Warning: Never use 0777 in a production environment. This gives everyone on the server full read/write/execute access to your files and directories, creating a major security risk. Stick to 0755 for directories and 0644 for files in most cases.
Creating Directories
The method ensures your target folder exists and applies your chosen permissions.
// Create a directory inside modules/your_module/uploads
$this->file->create_directory('uploads');
// Create nested directories (e.g., uploads/2024/05)
$this->file->create_directory('uploads/2024/05', 0755, true);Listing Directories
The method returns a flat array of filenames. With the optional $recursive parameter set to true, subdirectories appear as keys containing their own nested arrays.
// Non-recursive: flat array of filenames
$contents = $this->file->list_directory('uploads');
/*
$contents structure (non-recursive):
[
'report.pdf',
'invoice_2024.csv',
'avatars', // directories are just names in the flat list
'profile.jpg'
]
*/
// Recursive: subdirectories become keys
$all = $this->file->list_directory('uploads', true);
/*
$all structure (recursive):
[
'report.pdf',
'invoice_2024.csv',
'avatars' => [
'user_1.jpg',
'user_2.jpg'
],
'profile.jpg'
]
*/Example: Iterating the Results
$items = $this->file->list_directory('uploads');
foreach ($items as $key => $value) {
if (is_array($value)) {
// $key is a subdirectory name, $value is its file list
echo 'Directory: ' . out($key) . '';
foreach ($value as $file) {
echo '- ' . out($file) . '';
}
} else {
// $value is a filename
echo out($value) . '';
}
}Deleting Directories
The method recursively removes a directory and all of its contents - files, subdirectories, everything.
This operation is irreversible. Unlike which removes a single file, wipes out the entire directory tree. There is no trash bin or undo. Use with extreme care, especially when the path is constructed from user input or database records.
// Remove a temporary processing directory
$this->file->delete_directory('temp/import_67f3a2');
// Check existence first, then delete
if ($this->file->exists('old_backups/january')) {
$this->file->delete_directory('old_backups/january');
}There is no “empty directory” requirement - handles all contents recursively. If you only need to clear a directory without removing the directory itself, use with a loop of calls instead.
Troubleshooting Ownership
If your code has 0755 permissions but still fails, the directory is likely owned by root instead of the web server. You can fix this via the terminal:
# Give ownership to the web server user
sudo chown -R www-data:www-data modules/your_module/uploadsThe "Check Before You Act" Pattern
Professional file management relies on defensive programming. You should never assume a directory exists just because you created it earlier in the script. Server configurations, automated cleanup tasks, or manual changes by an administrator can remove directories without warning.
Always verify existence using immediately before performing operations like listing files or uploading data. This ensures your application can handle missing paths gracefully - perhaps by recreating them or showing a helpful message - rather than crashing with a fatal system error.
We're continually improving the Trongate documentation. If anything is incorrect, unclear, incomplete, or could be better, we'd genuinely appreciate your input.
Share your thoughts in the Documentation Feedback.