PHP code example of enjoys / upload

1. Go to this page and download the library: Download enjoys/upload 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/ */

    

enjoys / upload example snippets



use Psr\Http\Message\ServerRequestInterface;

/** @var Psr\Http\Message\UploadedFileInterface $uploadedFile */
/** @var League\Flysystem\Filesystem $filesystem */

$file = new Enjoys\Upload\UploadProcessing($uploadedFile, $filesystem);

try {
    $file->upload();       
} catch (\Exception $e) {
    // Handle exception
}

/** @var Enjoys\Upload\UploadProcessing $file */
/** @var Enjoys\Upload\RuleInterface $rule */

$file->addRule($rule); // Add before calling upload()
$file->upload();

$rule = new Enjoys\Upload\Rule\Extension();
$rule->allow('png'); // Single extension
$rule->allow('png, jpg'); // Comma-separated
$rule->allow(['png', 'jpg']); // Array of extensions

$rule = new Enjoys\Upload\Rule\Size();
$rule->setMaxSize(10 * 1024 * 1024) // 10MB
     ->setMinSize(1 * 1024 * 1024); // 1MB (values in bytes)

$rule = new Enjoys\Upload\Rule\MediaType();
$rule->allow('image/*') // All image types
     ->allow('application/pdf') // PDF files
     ->allow('*/vnd.openxmlformats-officedocument.*'); // Office documents
$rule->allow('*'); // All types

use Enjoys\Upload\Event\AfterUploadEvent;
use Psr\EventDispatcher\EventDispatcherInterface;

/** @var EventDispatcherInterface $dispatcher */

// Initialize with event dispatcher
$upload = new UploadProcessing($uploadedFile, $filesystem, $dispatcher);

// Add event listener
$dispatcher->addListener(
    AfterUploadEvent::class,
    function (AfterUploadEvent $event) {
        logger()->info("File uploaded to: " . $event->uploadProcessing->getTargetPath());
    }
);

$upload->upload();

$dispatcher->addListener(
    BeforeUploadEvent::class,
    function (BeforeUploadEvent $event) {
        if ($shouldStop) {
            $event->stopPropagation(); // Stops other listeners
        }
    }
);