PHP code example of mubbi / laravel-flysystem-huawei-obs

1. Go to this page and download the library: Download mubbi/laravel-flysystem-huawei-obs 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/ */

    

mubbi / laravel-flysystem-huawei-obs example snippets


'disks' => [
    'huawei-obs' => [
        'driver' => 'huawei-obs',
        
        // Required Configuration
        'key' => env('HUAWEI_OBS_ACCESS_KEY_ID'),
        'secret' => env('HUAWEI_OBS_SECRET_ACCESS_KEY'),
        'bucket' => env('HUAWEI_OBS_BUCKET'),
        'endpoint' => env('HUAWEI_OBS_ENDPOINT'),
        
        // Optional Configuration
        'prefix' => env('HUAWEI_OBS_PREFIX'),
        'security_token' => env('HUAWEI_OBS_SECURITY_TOKEN'),
        
        // Advanced OBSClient Configuration
        'signature' => env('HUAWEI_OBS_SIGNATURE', 'v4'),
        'path_style' => env('HUAWEI_OBS_PATH_STYLE', false),
        'region' => env('HUAWEI_OBS_REGION'),
        'ssl_verify' => env('HUAWEI_OBS_VERIFY_SSL', true),
        'ssl.certificate_authority' => env('HUAWEI_OBS_SSL_CERTIFICATE_AUTHORITY'),
        'max_retry_count' => env('HUAWEI_OBS_MAX_RETRY_COUNT', 3),
        'timeout' => env('HUAWEI_OBS_TIMEOUT', 120),
        'socket_timeout' => env('HUAWEI_OBS_SOCKET_TIMEOUT', 60),
        'connect_timeout' => env('HUAWEI_OBS_CONNECT_TIMEOUT', 30),
        'chunk_size' => env('HUAWEI_OBS_CHUNK_SIZE', 8192),
        'exception_response_mode' => env('HUAWEI_OBS_EXCEPTION_RESPONSE_MODE', 'exception'),
        'is_cname' => env('HUAWEI_OBS_IS_CNAME', false),
        
        // HTTP Client Configuration
        'http_client' => [
            'timeout' => env('HUAWEI_OBS_TIMEOUT', 120),
            'connect_timeout' => env('HUAWEI_OBS_CONNECT_TIMEOUT', 30),
            'verify' => env('HUAWEI_OBS_VERIFY_SSL', true),
            'proxy' => null,
            'headers' => [],
        ],
        
        // Retry Configuration
        'retry_attempts' => env('HUAWEI_OBS_RETRY_ATTEMPTS', 3),
        'retry_delay' => env('HUAWEI_OBS_RETRY_DELAY', 1),
        
        // Logging Configuration
        'logging_enabled' => env('HUAWEI_OBS_LOGGING_ENABLED', false),
        'log_operations' => env('HUAWEI_OBS_LOG_OPERATIONS', false),
        'log_errors' => env('HUAWEI_OBS_LOG_ERRORS', true),
        
        // Flysystem Configuration
        'visibility' => 'private',
        'throw' => false,
    ],
],

use Illuminate\Support\Facades\Storage;

// Upload a file
Storage::disk('huawei-obs')->put('file.txt', 'Hello World');

// Download a file
$contents = Storage::disk('huawei-obs')->get('file.txt');

// Check if file exists
$exists = Storage::disk('huawei-obs')->exists('file.txt');

// Delete a file
Storage::disk('huawei-obs')->delete('file.txt');

// Get file URL
$url = Storage::disk('huawei-obs')->url('file.txt');

// Get temporary URL
$tempUrl = Storage::disk('huawei-obs')->temporaryUrl('file.txt', now()->addHour());

use LaravelFlysystemHuaweiObs\LaravelHuaweiObsAdapter;
use League\Flysystem\Filesystem;
use League\Flysystem\Config;

$adapter = new LaravelHuaweiObsAdapter(
    env('HUAWEI_OBS_ACCESS_KEY_ID'),
    env('HUAWEI_OBS_SECRET_ACCESS_KEY'),
    env('HUAWEI_OBS_BUCKET'),
    env('HUAWEI_OBS_ENDPOINT'),
    env('HUAWEI_OBS_PREFIX'),
);

$filesystem = new Filesystem($adapter);

$filesystem->write('file.txt', 'Hello World', new Config());
$contents = $filesystem->read('file.txt');

// Get storage statistics with timeout protection
$stats = Storage::disk('huawei-obs')->getStorageStats(10000, 60);
// Returns: ['total_files' => 1234, 'total_directories' => 56, 'total_size_bytes' => 1073741824, ...]

// Get files with limits and timeout
$files = Storage::disk('huawei-obs')->allFilesOptimized(1000, 30);

// Get directories with limits and timeout
$directories = Storage::disk('huawei-obs')->allDirectoriesOptimized(1000, 30);

// List contents with advanced controls
foreach (Storage::disk('huawei-obs')->listContentsOptimized('path', true, 1000, 60) as $item) {
    // Process items with timeout protection
}

// Configure retry behavior
'huawei-obs' => [
    'retry_attempts' => 3,    // Number of retry attempts
    'retry_delay' => 1,       // Base delay in seconds
    // ... other config
],

// Refresh authentication cache manually
$adapter->refreshAuthentication();

// Refresh credentials (clears cache automatically)
$adapter->refreshCredentials('new-key', 'new-secret', 'new-token');

'huawei-obs' => [
    'logging_enabled' => true,
    'log_operations' => true,  // Log successful operations
    'log_errors' => true,      // Log errors
    // ... other config
],

// List files in a directory (non-recursive)
$files = Storage::disk('huawei-obs')->files('uploads');

// List directories in a directory (non-recursive)
$directories = Storage::disk('huawei-obs')->directories('uploads');

// List all files and directories (recursive)
$allFiles = Storage::disk('huawei-obs')->allFiles();
$allDirectories = Storage::disk('huawei-obs')->allDirectories();

// Check if file exists
$exists = Storage::disk('huawei-obs')->exists('file.txt');

// Get file size
$size = Storage::disk('huawei-obs')->size('file.txt');

// Get last modified timestamp
$modified = Storage::disk('huawei-obs')->lastModified('file.txt');

// Get MIME type
$mimeType = Storage::disk('huawei-obs')->mimeType('file.txt');

// Get file visibility
$visibility = Storage::disk('huawei-obs')->visibility('file.txt');

$directory = $request->get('directory', '');
$files = Storage::disk('huawei-obs')->files($directory);
$directories = Storage::disk('huawei-obs')->directories($directory);

$fileDetails = [];
foreach ($files as $file) {
    $fileDetails[] = [
        'name' => $file,
        'size' => Storage::disk('huawei-obs')->size($file),
        'last_modified' => Storage::disk('huawei-obs')->lastModified($file),
        'mime_type' => Storage::disk('huawei-obs')->mimeType($file),
        'url' => Storage::disk('huawei-obs')->url($file),
        'visibility' => Storage::disk('huawei-obs')->visibility($file)
    ];
}

return response()->json([
    'success' => true,
    'files' => $fileDetails,
    'directories' => $directories,
    'total_files' => count($files),
    'total_directories' => count($directories)
]);

// Missing s' => [
    'key' => '', // ❌ Will throw: "Missing 

use LaravelFlysystemHuaweiObs\Exceptions\UnableToCreateSignedUrl;
use LaravelFlysystemHuaweiObs\Exceptions\UnableToSetObjectTags;

try {
    $signedUrl = $adapter->createSignedUrl('file.txt');
} catch (UnableToCreateSignedUrl $e) {
    // Handle signed URL creation errors
}

try {
    $adapter->setObjectTags('file.txt', ['tag' => 'value']);
} catch (UnableToSetObjectTags $e) {
    // Handle object tagging errors
}

try {
    Storage::disk('huawei-obs')->exists('file.txt');
} catch (\RuntimeException $e) {
    // Clear authentication error message
    // "Authentication failed. Please check your Huawei OBS credentials..."
}

// Configure with security token
$adapter = new \LaravelFlysystemHuaweiObs\HuaweiObsAdapter(
    'access_key_id',
    'secret_access_key',
    'bucket_name',
    'endpoint',
    null, // prefix
    null, // http client
    'security_token_here'
);

// Or refresh credentials during runtime
$adapter->refreshCredentials('new_access_key', 'new_secret_key', 'new_security_token');

// For public objects, returns a direct URL
$publicUrl = Storage::disk('huawei-obs')->url('public-file.txt');
// Returns: https://obs.example.com/bucket/public-file.txt

// For private objects, automatically returns a signed URL (1-hour expiration)
$privateUrl = Storage::disk('huawei-obs')->url('private-file.txt');
// Returns: https://obs.example.com/bucket/private-file.txt?signature=...

// Generate a temporary URL that expires in 2 hours
$tempUrl = Storage::disk('huawei-obs')->temporaryUrl(
    'file.txt',
    now()->addHours(2)
);

// Generate a temporary URL for uploads (PUT method)
$uploadUrl = Storage::disk('huawei-obs')->temporaryUploadUrl(
    'file.txt',
    now()->addHour()
);

// Set tags on an object
Storage::disk('huawei-obs')->setObjectTags('file.txt', [
    'category' => 'images',
    'processed' => 'true',
    'user_id' => '123'
]);

// Get tags from an object
$tags = Storage::disk('huawei-obs')->getObjectTags('file.txt');

// Delete tags from an object
Storage::disk('huawei-obs')->deleteObjectTags('file.txt');

// Generate a post signature for direct upload
$signature = Storage::disk('huawei-obs')->createPostSignature('uploads/file.txt', [
    'success_action_status' => '201',
    'x-amz-meta-category' => 'images'
], 3600); // 1 hour expiration

// Use the signature in an HTML form
echo '<form action="' . $signature['url'] . '" method="post" enctype="multipart/form-data">';
foreach ($signature['fields'] as $key => $value) {
    echo '<input type="hidden" name="' . $key . '" value="' . $value . '">';
}
echo '<input type="file" name="file">';
echo '<input type="submit" value="Upload">';
echo '</form>';

// Restore an archived object (default 1 day)
Storage::disk('huawei-obs')->restoreObject('archived-file.txt');

// Restore with custom restoration period (7 days)
Storage::disk('huawei-obs')->restoreObject('archived-file.txt', 7);

use LaravelFlysystemHuaweiObs\HuaweiObsAdapter;

$adapter = new HuaweiObsAdapter(
    'your_access_key_id',
    'your_secret_access_key',
    'your_bucket_name',
    'https://obs.cn-north-1.myhuaweicloud.com'
);

// Test basic operations
$adapter->write('test.txt', 'Hello World', new \League\Flysystem\Config());
$contents = $adapter->read('test.txt');
$adapter->delete('test.txt');

try {
    Storage::disk('huawei-obs')->put('file.txt', 'content');
} catch (\RuntimeException $e) {
    // Authentication errors
    if (str_contains($e->getMessage(), 'Authentication failed')) {
        // Check your credentials
    }
    
    // Bucket errors
    if (str_contains($e->getMessage(), 'NoSuchBucket')) {
        // Check your bucket name
    }
    
    // Permission errors
    if (str_contains($e->getMessage(), 'AccessDenied')) {
        // Check your IAM permissions
    }
}

use LaravelFlysystemHuaweiObs\Exceptions\UnableToCreateSignedUrl;
use LaravelFlysystemHuaweiObs\Exceptions\UnableToSetObjectTags;

try {
    $url = Storage::disk('huawei-obs')->temporaryUrl('file.txt', now()->addHour());
} catch (UnableToCreateSignedUrl $e) {
    // Handle signed URL creation errors
}

try {
    Storage::disk('huawei-obs')->setObjectTags('file.txt', ['tag' => 'value']);
} catch (UnableToSetObjectTags $e) {
    // Handle object tagging errors
}

// Instead of allFiles() which might timeout
$allFiles = Storage::disk('huawei-obs')->allFiles();

// Use optimized method with limits
$files = Storage::disk('huawei-obs')->allFilesOptimized(10000, 60);

// Cache file listings
$files = Cache::remember('huawei-obs-files', 300, function () {
    return Storage::disk('huawei-obs')->files('uploads');
});

// Instead of multiple individual calls
foreach ($files as $file) {
    Storage::disk('huawei-obs')->delete($file);
}

// Consider using background jobs for large batches

'huawei-obs' => [
    'logging_enabled' => true,
    'log_operations' => true,
    'log_errors' => true,
    // ... other config
],
bash
php artisan vendor:publish --provider="LaravelFlysystemHuaweiObs\HuaweiObsServiceProvider" --tag=huawei-obs-config
bash
php artisan huawei-obs:test