Filesystem in PHP
? Filesystem in PHP
PHP’s filesystem functions allow you to create, read, write, delete, and manipulate directories and files on the server. It’s commonly used in content management systems, file upload tools, and log systems.
? 1. Check File or Directory Exists
if (file_exists("file.txt")) { echo "File exists.";}if (is_dir("folder")) { echo "It's a directory.";}? 2. Create and Delete a File
// Create filefile_put_contents("newfile.txt", "Hello World!");// Delete fileunlink("newfile.txt");? 3. Create and Delete a Directory
// Create directorymkdir("myfolder");// Delete directoryrmdir("myfolder");?
rmdir()only deletes empty folders.
? 4. Scan Directory Contents
$files = scandir("uploads");foreach ($files as $file) { echo $file . "<br>";}Returns an array of file/folder names.
? 5. Copy, Rename, Move Files
// Copycopy("file1.txt", "file2.txt");// Rename or moverename("file2.txt", "moved/file2.txt");? 6. Read File Metadata
$info = stat("file.txt");echo "Size: " . $info['size'] . " bytes";? 7. Change Permissions
chmod("file.txt", 0644); // Read/write for owner, read for others? 8. Disk Space Information
echo "Free space: " . disk_free_space("/") . " bytes";echo "Total space: " . disk_total_space("/") . " bytes";? Example: List Only Files (Ignore . and ..)
$dir = "uploads";$files = array_diff(scandir($dir), array('.', '..'));foreach ($files as $file) { if (is_file("$dir/$file")) { echo $file . "<br>"; }}? Best Practices
Always validate file/directory names to avoid path traversal issues.
Check permissions before reading/writing.
Be careful with
chmodandunlink.