PHP code example of webfiori / file

1. Go to this page and download the library: Download webfiori/file library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

webfiori / file example snippets



WebFiori\File\File;

// Basic file operations
$file = new File('path/to/document.txt');
$file->read();
echo $file->getRawData();


WebFiori\File\FileUploader;

// File upload
$uploader = new FileUploader('/uploads');
$uploader->addExts(['jpg', 'png', 'pdf']);
$uploadedFiles = $uploader->uploadAsFileObj();


use WebFiori\File\File;

// Read entire file
$file = new File('/path/to/file.txt');
$file->read();
$content = $file->getRawData();

// Read specific byte range
$file->read(10, 100); // Read bytes 10-100
$partialContent = $file->getRawData();

// Check if file exists
if ($file->isExist()) {
    echo "File size: " . $file->getSize() . " bytes\n";
    echo "MIME type: " . $file->getMIME() . "\n";
    echo "Last modified: " . $file->getLastModified() . "\n";
}


use WebFiori\File\File;

// Create new file
$file = new File('/path/to/new-file.txt');
$file->create();
$file->setRawData('Hello, World!');
$file->write();

// Append to existing file
$file->setRawData("\nAppended content");
$file->write(true); // true = append mode

// Override file content
$file->setRawData('New content');
$file->write(false); // false = override mode


use WebFiori\File\File;

$file = new File('document.pdf', '/uploads');

// Get file properties
echo "Name: " . $file->getName() . "\n";
echo "Extension: " . $file->getExtension() . "\n";
echo "Directory: " . $file->getDir() . "\n";
echo "Full path: " . $file->getAbsolutePath() . "\n";
echo "MIME type: " . $file->getMIME() . "\n";
echo "Size: " . $file->getSize() . " bytes\n";

// Get last modified time
echo "Modified: " . $file->getLastModified('Y-m-d H:i:s') . "\n";

// Convert to different formats
$bytesArray = $file->toBytesArray();
$hexArray = $file->toHexArray();
$jsonData = $file->toJSON();


use WebFiori\File\FileUploader;
use WebFiori\File\Exceptions\FileException;

try {
    $uploader = new FileUploader('/var/www/uploads');
    
    // Set allowed file types
    $uploader->addExts(['jpg', 'png', 'gif', 'pdf', 'docx']);
    
    // Set the HTML form input name
    $uploader->setAssociatedFileName('user_files');
    
    // Upload files
    $results = $uploader->upload();
    
    foreach ($results as $result) {
        if ($result['uploaded']) {
            echo "✅ {$result['name']} uploaded successfully\\n";
        } else {
            echo "❌ {$result['name']} failed: {$result['upload-error']}\\n";
        }
    }
} catch (FileException $e) {
    echo "Upload error: " . $e->getMessage();
}


use WebFiori\File\FileUploader;
use WebFiori\File\UploadedFile;

$uploader = new FileUploader('/uploads');
$uploader->addExts(['jpg', 'png']);

$uploadedFiles = $uploader->uploadAsFileObj();

foreach ($uploadedFiles as $file) {
    if ($file instanceof UploadedFile) {
        if ($file->isUploaded()) {
            echo "File: " . $file->getName() . "\n";
            echo "Size: " . $file->getSize() . " bytes\n";
            echo "MIME: " . $file->getMIME() . "\n";
            echo "Replaced existing: " . ($file->isReplace() ? 'Yes' : 'No') . "\n";
            
            // Process the uploaded file
            $file->read();
            $content = $file->getRawData();
        } else {
            echo "Upload failed: " . $file->getUploadError() . "\n";
        }
    }
}


use WebFiori\File\FileUploader;

$uploader = new FileUploader('/uploads');

// Configure allowed file types
$uploader->addExts(['jpg', 'png', 'gif', 'pdf', 'docx']);

// Remove specific extensions
$uploader->removeExt('gif');

// Set form input name
$uploader->setAssociatedFileName('user_files');

// Get current configuration
$allowedTypes = $uploader->getExts();
$uploadDir = $uploader->getUploadDir();
$inputName = $uploader->getAssociatedFileName();

// Get maximum upload size (from PHP configuration)
$maxSize = FileUploader::getMaxFileSize(); // Returns size in KB


use WebFiori\File\File;

$file = new File('image.jpg');
$file->read();

// Get Base64 encoded content
$encoded = $file->getRawData(true);
echo "Base64: " . $encoded;

// Decode Base64 data
$file2 = new File();
$file2->setRawData($encoded, true); // true = decode from Base64
$decoded = $file2->getRawData();

// Write encoded file
$file->writeEncoded(); // Creates 'image.jpg.bin' with Base64 content

// Read and decode encoded file
$encodedFile = new File('image.jpg.bin');
$encodedFile->readDecoded();
$originalData = $encodedFile->getRawData();


use WebFiori\File\File;

// Serve file for download
$file = new File('/path/to/document.pdf');
$file->read();
$file->view(true); // true = force download

// Serve file inline (display in browser)
$file->view(false); // false = display inline

// The view() method automatically:
// - Sets appropriate Content-Type header
// - Handles Content-Range for partial requests
// - Sets Content-Disposition header
// - Outputs file content


use WebFiori\File\File;

// Process large file in chunks
$file = new File('/path/to/large-file.mp4');
$file->read();

// Get 1KB chunks, Base64 encoded
$chunks = $file->getChunks(1024, true);

foreach ($chunks as $index => $chunk) {
    echo "Processing chunk " . ($index + 1) . "/" . count($chunks) . "\\n";
    
    // Store chunk in database or process separately
    // Each chunk is Base64 encoded and 1KB in size
    storeChunkInDatabase($index, $chunk);
}

// Get raw chunks (not encoded)
$rawChunks = $file->getChunks(1024, false);


use WebFiori\File\MIME;

// Get MIME type by extension
$mimeType = MIME::getType('jpg'); // Returns: image/jpeg
$pdfMime = MIME::getType('pdf');  // Returns: application/pdf
$txtMime = MIME::getType('txt');  // Returns: text/plain

// Unknown extensions return default MIME type
$unknownMime = MIME::getType('xyz'); // Returns: application/octet-stream

// The library supports common file extensions including:
// - Images: jpg, png, gif, bmp, svg, webp, tiff
// - Documents: pdf, doc, docx, xls, xlsx, ppt, pptx
// - Audio: mp3, wav, ogg, flac, aac
// - Video: mp4, avi, mov, wmv, flv
// - Archives: zip, rar, 7z, tar, gz
// - And many more...

public function __construct(string $fName = '', string $fPath = '')


use WebFiori\File\File;
use WebFiori\File\Exceptions\FileException;

try {
    $file = new File('/path/to/nonexistent.txt');
    $file->read();
} catch (FileException $e) {
    echo "Error: " . $e->getMessage();
    // Handle specific error scenarios
    switch ($e->getCode()) {
        case 0:
            // File not found
            break;
        default:
            // Other errors
            break;
    }
}


use WebFiori\File\FileUploader;

$uploader = new FileUploader('/secure/uploads');

// 1. Restrict file types
$uploader->addExts(['jpg', 'png', 'pdf']); // Only allow safe file types

// 2. Validate file size (handled by PHP settings)
// Set in php.ini: upload_max_filesize = 5M

// 3. Use secure upload directory outside web root
// Store files outside public_html or www directories

// 4. Sanitize file names (handled automatically)
// The library normalizes file paths and names


use WebFiori\File\File;

// For large files, use chunked processing
$file = new File('/path/to/large-video.mp4');
$file->read();

// Process in 1MB chunks to avoid memory issues
$chunks = $file->getChunks(1024 * 1024, false);
foreach ($chunks as $chunk) {
    // Process each chunk separately
    processChunk($chunk);
}


use WebFiori\File\File;

$file = new File('/path/to/document.pdf');
$file->read();

// Enable range requests for better streaming
$file->view(false); // Serves with proper HTTP headers