aliyuncs/oss-sdk-php
Alibaba Cloud OSS SDK for PHP (V1): connect to Object Storage Service to upload, download, and manage files. Composer install, works on PHP 5.3+ with cURL. Supports common OSS operations for websites and applications with secure, reliable storage.
## Getting Started
### Minimal Setup
1. **Installation**:
```bash
composer require aliyuncs/oss-sdk-php
Add to composer.json:
"require": {
"aliyuncs/oss-sdk-php": "^2.0"
}
Autoload:
require_once __DIR__ . '/vendor/autoload.php';
First Use Case: Initialize the client with credentials:
$client = new \OSS\OssClient('accessKeyId', 'accessKeySecret', 'endpoint');
Quick Operations:
$client->putObject('bucket-name', 'object-key', fopen('local-file', 'r'));
$buckets = $client->listBuckets();
print_r($buckets->getBucketList());
Key Files:
vendor/aliyuncs/oss-sdk-php/src/OSS/OssClient.php (Core class)vendor/aliyuncs/oss-sdk-php/samples/ (Example workflows)File Operations:
$client->putObject('bucket', 'key', fopen('file', 'r'), [
'Content-Type' => 'image/jpeg',
]);
$result = $client->getObject('bucket', 'key');
file_put_contents('local-file', $result->getContent());
$client->putObject('bucket', 'key', fopen('php://input', 'r'));
Bucket Management:
$client->createBucket('bucket-name', \OSS\OssClient::OSS_ACL_TYPE_PUBLIC_READ);
$client->deleteBucket('bucket-name');
$objects = $client->listObjects('bucket-name');
foreach ($objects->getContents() as $object) {
echo $object->getKey() . "\n";
}
Pre-Signed URLs:
$url = $client->signUrl('bucket-name', 'key', 3600); // Expires in 1 hour
Multipart Uploads:
$uploadId = $client->createMultipartUpload('bucket', 'key')->getUploadId();
$client->completeMultipartUpload('bucket', 'key', $uploadId, $parts);
Laravel Service Provider:
use OSS\OssClient;
class OssServiceProvider extends ServiceProvider {
public function register() {
$this->app->singleton('oss', function() {
return new OssClient(
config('oss.accessKeyId'),
config('oss.accessKeySecret'),
config('oss.endpoint')
);
});
}
}
Configure in .env:
OSS_ACCESS_KEY_ID=your_key
OSS_ACCESS_KEY_SECRET=your_secret
OSS_ENDPOINT=oss-cn-hangzhou.aliyuncs.com
Environment Variables:
Use OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_ENDPOINT for dynamic config:
$client = new OssClient(
getenv('OSS_ACCESS_KEY_ID'),
getenv('OSS_ACCESS_KEY_SECRET'),
getenv('OSS_ENDPOINT')
);
Error Handling: Wrap operations in try-catch:
try {
$client->putObject('bucket', 'key', fopen('file', 'r'));
} catch (\OSS\Core\OssException $e) {
\Log::error($e->getMessage());
abort(500, 'Upload failed');
}
Advanced Features:
$client->putBucketCors('bucket-name', [
'CORSRules' => [
[
'AllowedHeaders' => ['*'],
'AllowedMethods' => ['GET', 'POST'],
'AllowedOrigins' => ['*'],
'ExposeHeaders' => ['ETag'],
'MaxAgeSeconds' => 3600,
],
],
]);
$client->putBucketLifecycle('bucket-name', [
'Rules' => [
[
'ID' => 'rule1',
'Status' => 'Enabled',
'Filter' => ['Prefix' => 'logs/'],
'Expiration' => ['Days' => 30],
],
],
]);
Credentials Handling:
.env.Endpoint Validation:
oss-cn-hangzhou.aliyuncs.com).forcePathStyle: true if encountering DNS issues:
$client = new OssClient($accessKeyId, $accessKeySecret, $endpoint, [], [
'forcePathStyle' => true,
]);
Object Naming:
0file.txt) or reserved characters (/, \, ?).strictObjectName: true to enforce validation:
$client = new OssClient(..., ..., ..., [], [
'strictObjectName' => true,
]);
Multipart Uploads:
CORS Issues:
$cors = $client->getBucketCors('bucket-name');
print_r($cors->getCORSRules());
PHP Version Quirks:
~2.4 to avoid PHP 8+ features.oss-sdk-php is updated to ^2.4.2 for compatibility.Enable Debugging:
$client = new OssClient(..., ..., ..., [
'debug' => true,
'logLevel' => \OSS\Core\Logger::LOG_DEBUG,
]);
Logs appear in stderr or Laravel's log channel.
Common Errors:
InvalidAccessKeyId: Verify accessKeyId/accessKeySecret.BucketAlreadyExists: Check bucket naming conventions (3–63 chars, lowercase, no underscores).NoSuchBucket: Confirm the bucket exists and is in the correct region.Network Issues:
proxy: ['host' => 'proxy.example.com', 'port' => 8080] for corporate networks.$client = new OssClient(..., ..., ..., [
'connectTimeout' => 30,
'readTimeout' => 60,
]);
Custom Credentials Provider:
Implement \OSS\Core\Credentials\CredentialsProviderInterface for dynamic credentials:
class MyCredentialsProvider implements CredentialsProviderInterface {
public function getCredentials() {
return [
'AccessKeyId' => 'dynamic-key',
'AccessKeySecret' => 'dynamic-secret',
'SecurityToken' => null,
];
}
}
Usage:
$client = new OssClient(null, null, $endpoint, new MyCredentialsProvider());
Middleware for Requests:
Extend \OSS\Core\Request to add headers or modify requests:
$client->addRequestMiddleware(function($request) {
$request->addHeader('X-My-Custom-Header', 'value');
return $request;
});
Event Listeners:
Subscribe to SDK events (e.g., beforeRequest, afterResponse):
$client->addEventListener('beforeRequest', function($event) {
if ($event->getRequest()->getMethod() === 'PUT') {
$event->getRequest()->addHeader('X-Accel-Buffering', 'no');
}
});
Batch Operations:
Use listObjectsV2 for pagination:
$objects = $client->listObjectsV2('bucket-name', [
'maxKeys' => 1000,
'prefix'
How can I help you explore Laravel packages today?