PHP code example of nandung / s3-manager

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

    

nandung / s3-manager example snippets


return [
    // Global storage quota (in bytes), null for unlimited
    'global_quota' => env('S3_MANAGER_GLOBAL_QUOTA', null),

    // Embed proxy configuration
    'embed' => [
        'enabled' => true,
        'route_prefix' => 'e',
        'cache_ttl' => 3600,
    ],

    // Presigned URL configuration
    'presigned' => [
        'default_expiration' => 3600, // seconds
    ],

    // Sync configuration
    'sync' => [
        'queue' => 'default',
        'chunk_size' => 1000,
    ],

    // Bucket configurations
    'buckets' => [
        'default' => [
            'driver' => 's3',
            'key' => env('S3_DEFAULT_KEY'),
            'secret' => env('S3_DEFAULT_SECRET'),
            'region' => env('S3_DEFAULT_REGION', 'us-east-1'),
            'bucket' => env('S3_DEFAULT_BUCKET'),
            'endpoint' => env('S3_DEFAULT_ENDPOINT'),
            'public_base_url' => env('S3_DEFAULT_PUBLIC_URL'),
            'quota' => env('S3_DEFAULT_QUOTA', null), // bytes
            'options' => [
                'use_path_style_endpoint' => false,
            ],
        ],
    ],
];

use Nandung\S3Manager\Facades\S3Manager;

// Upload a file
$fileRecord = S3Manager::upload('default', 'images/photo.jpg', $fileContents);

// Upload with options
$fileRecord = S3Manager::upload('default', 'documents/report.pdf', $contents, [
    'ContentType' => 'application/pdf',
    'Metadata' => ['author' => 'John Doe'],
]);

// Download a file
$stream = S3Manager::download('default', 'images/photo.jpg');
$contents = $stream->getContents();

// Delete a file
S3Manager::delete('default', 'images/photo.jpg');

// Check if file exists
if (S3Manager::exists('default', 'images/photo.jpg')) {
    // File exists
}

// List files
$files = S3Manager::list('default', 'images/', recursive: true);

use Nandung\S3Manager\Facades\S3Manager;

// Get bucket instance for fluent operations
$bucket = S3Manager::bucket('default');

// All operations are now scoped to this bucket
$fileRecord = $bucket->upload('images/photo.jpg', $contents);
$stream = $bucket->download('images/photo.jpg');
$bucket->delete('images/photo.jpg');
$exists = $bucket->exists('images/photo.jpg');
$files = $bucket->list('images/');

use Nandung\S3Manager\Facades\S3Manager;

// Public URL (to.jpg');
// Result: https://your-bucket.s3.amazonaws.com/images/photo.jpg

// Presigned URL (temporary access)
$presignedUrl = S3Manager::presignedUrl('default', 'images/photo.jpg', 3600);
// Result: https://...?X-Amz-Signature=...

// Presigned URL for upload
$uploadUrl = S3Manager::presignedUrl('default', 'uploads/new-file.jpg', 3600, 'PUT');

// Embed URL (proxied through your application)
$embedUrl = S3Manager::embedUrl('default', 'images/photo.jpg');
// Result: /e/default/images/photo.jpg

use Nandung\S3Manager\Facades\S3Manager;

// Get bucket usage
$usage = S3Manager::getUsage('default');
echo "Used: " . $usage->used . " bytes";
echo "Limit: " . $usage->limit . " bytes";
echo "Files: " . $usage->fileCount;
echo "Percent: " . $usage->percentUsed . "%";
echo "Unlimited: " . ($usage->isUnlimited ? 'Yes' : 'No');

// Get global usage (across all buckets)
$globalUsage = S3Manager::getUsage();

use Nandung\S3Manager\Exceptions\QuotaExceededException;
use Nandung\S3Manager\Exceptions\GlobalQuotaExceededException;

try {
    S3Manager::upload('default', 'large-file.zip', $contents);
} catch (QuotaExceededException $e) {
    // Bucket quota exceeded
    echo "Bucket {$e->bucketId} quota exceeded";
    echo "Limit: {$e->limit}, Used: {$e->used}, Attempted: {$e->attempted}";
} catch (GlobalQuotaExceededException $e) {
    // Global quota exceeded
    echo "Global storage quota exceeded";
}

use Nandung\S3Manager\Facades\S3Manager;

// Sync bucket (updates local database with remote state)
$result = S3Manager::sync('default');

echo "Added: " . $result->added;
echo "Updated: " . $result->updated;
echo "Deleted: " . $result->deleted;
echo "Total Files: " . $result->totalFiles;
echo "Total Size: " . $result->totalSize;
echo "Duration: " . $result->duration . " seconds";

if ($result->hasErrors()) {
    foreach ($result->errors as $error) {
        echo "Error: " . $error;
    }
}

use Nandung\S3Manager\Contracts\S3ManagerInterface;

class FileService
{
    public function __construct(
        private S3ManagerInterface $s3Manager
    ) {}

    public function uploadUserAvatar(User $user, $contents): string
    {
        $path = "avatars/{$user->id}.jpg";
        $this->s3Manager->upload('default', $path, $contents);
        return $this->s3Manager->publicUrl('default', $path);
    }
}

'buckets' => [
    'aws' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
        'bucket' => env('AWS_BUCKET'),
        'endpoint' => null, // Use default AWS endpoint
        'public_base_url' => env('AWS_URL'),
        'quota' => null,
        'options' => [],
    ],
],

'buckets' => [
    'r2' => [
        'driver' => 'r2',
        'key' => env('R2_ACCESS_KEY_ID'),
        'secret' => env('R2_SECRET_ACCESS_KEY'),
        'region' => 'auto',
        'bucket' => env('R2_BUCKET'),
        'endpoint' => env('R2_ENDPOINT'), // https://<account_id>.r2.cloudflarestorage.com
        'public_base_url' => env('R2_PUBLIC_URL'),
        'quota' => null,
        'options' => [
            'use_path_style_endpoint' => false,
        ],
    ],
],

'buckets' => [
    'minio' => [
        'driver' => 'minio',
        'key' => env('MINIO_ACCESS_KEY'),
        'secret' => env('MINIO_SECRET_KEY'),
        'region' => 'us-east-1',
        'bucket' => env('MINIO_BUCKET'),
        'endpoint' => env('MINIO_ENDPOINT', 'http://localhost:9000'),
        'public_base_url' => env('MINIO_PUBLIC_URL'),
        'quota' => 1073741824, // 1GB
        'options' => [
            'use_path_style_endpoint' => true,
        ],
    ],
],

'buckets' => [
    'spaces' => [
        'driver' => 'spaces',
        'key' => env('DO_SPACES_KEY'),
        'secret' => env('DO_SPACES_SECRET'),
        'region' => env('DO_SPACES_REGION', 'nyc3'),
        'bucket' => env('DO_SPACES_BUCKET'),
        'endpoint' => env('DO_SPACES_ENDPOINT'), // https://nyc3.digitaloceanspaces.com
        'public_base_url' => env('DO_SPACES_URL'),
        'quota' => null,
        'options' => [],
    ],
],

'embed' => [
    'enabled' => true,
    'route_prefix' => 'e',  // URL prefix
    'cache_ttl' => 3600,    // Cache duration in seconds
],

// Generate embed URL
$embedUrl = S3Manager::embedUrl('default', 'images/photo.jpg');
// Result: /e/default/images/photo.jpg

// Use in views
<img src="{{ S3Manager::embedUrl('default', 'images/photo.jpg') }}" alt="Photo">

use Nandung\S3Manager\Exceptions\BucketNotFoundException;
use Nandung\S3Manager\Exceptions\FileNotFoundException;
use Nandung\S3Manager\Exceptions\QuotaExceededException;
use Nandung\S3Manager\Exceptions\GlobalQuotaExceededException;
use Nandung\S3Manager\Exceptions\PublicUrlNotConfiguredException;
use Nandung\S3Manager\Exceptions\SyncException;

try {
    S3Manager::upload('unknown-bucket', 'file.txt', 'content');
} catch (BucketNotFoundException $e) {
    // Bucket not configured
}

try {
    S3Manager::download('default', 'non-existent.txt');
} catch (FileNotFoundException $e) {
    // File doesn't exist
}

try {
    S3Manager::publicUrl('default', 'file.txt');
} catch (PublicUrlNotConfiguredException $e) {
    // public_base_url not set for bucket
}

$fileRecord = S3Manager::upload('default', 'file.txt', 'content');

$fileRecord->bucket_id;    // string
$fileRecord->path;         // string
$fileRecord->size;         // int (bytes)
$fileRecord->mime_type;    // string
$fileRecord->etag;         // string
$fileRecord->last_modified; // Carbon
$fileRecord->metadata;     // array

$usage = S3Manager::getUsage('default');

$usage->used;        // int (bytes)
$usage->limit;       // int|null (bytes)
$usage->fileCount;   // int
$usage->percentUsed; // float
$usage->isUnlimited; // bool

$result = S3Manager::sync('default');

$result->added;      // int
$result->updated;    // int
$result->deleted;    // int
$result->totalFiles; // int
$result->totalSize;  // int (bytes)
$result->duration;   // float (seconds)
$result->errors;     // array
$result->hasErrors(); // bool
bash
php artisan vendor:publish --tag=s3-manager-config
bash
php artisan migrate
bash
php artisan vendor:publish --tag=s3-manager-migrations
php artisan migrate