要测试OSS PHP的功能,您需要首先确保已经安装了PHP和相关的依赖库。然后,您可以按照以下步骤进行测试:
require_once 'vendor/autoload.php';
use OSS\OssClient;
use OSS\Core\OssException;
$accessKeyId = 'your_access_key_id';
$accessKeySecret = 'your_access_key_secret';
$endpoint = 'your_oss_endpoint'; // 例如:https://oss-cn-shanghai.aliyuncs.com
$client = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$bucketName = 'your_bucket_name';
$filePath = 'path/to/your/local/file';
$objectKey = 'path/to/your/oss/object';
try {
$result = $client->putObject($bucketName, $objectKey, $filePath);
echo "Upload success: " . $result['ObjectURL'] . PHP_EOL;
} catch (OssException $e) {
echo "Upload failed: " . $e->getMessage() . PHP_EOL;
}
try {
$result = $client->getObject($bucketName, $objectKey);
file_put_contents('downloaded_file', $result['Body']->getContents());
echo "Download success: downloaded_file" . PHP_EOL;
} catch (OssException $e) {
echo "Download failed: " . $e->getMessage() . PHP_EOL;
}
$delimiter = '';
$prefix = 'path/to/your/oss/directory/';
try {
$result = $client->listObjects($bucketName, $delimiter, $prefix);
foreach ($result['Contents'] as $file) {
echo "File: " . $file['Key'] . PHP_EOL;
}
} catch (OssException $e) {
echo "List objects failed: " . $e->getMessage() . PHP_EOL;
}
$objectKey = 'path/to/your/oss/object';
try {
$result = $client->deleteObject($bucketName, $objectKey);
echo "Delete success" . PHP_EOL;
} catch (OssException $e) {
echo "Delete failed: " . $e->getMessage() . PHP_EOL;
}
$objectKey = 'path/to/your/oss/object';
try {
$result = $client->headObject($bucketName, $objectKey);
echo "File exists" . PHP_EOL;
} catch (OssException $e) {
if ($e->getErrorCode() == '404') {
echo "File not exists" . PHP_EOL;
} else {
echo "Error: " . $e->getMessage() . PHP_EOL;
}
}
$objectKey = 'path/to/your/oss/object';
try {
$result = $client->getObjectMetadata($bucketName, $objectKey);
print_r($result);
} catch (OssException $e) {
echo "Get object metadata failed: " . $e->getMessage() . PHP_EOL;
}
通过以上示例代码,您可以测试OSS PHP库的基本功能。如果需要更多信息,请参阅官方文档:https://help.aliyun.com/document_detail/31818.html