Tous les produits
Search
Centre de documentation

Object Storage Service:Get started with OSS SDK for PHP V1

Dernière mise à jour :Aug 18, 2026

Utilisez le kit SDK OSS pour PHP pour créer des buckets, charger des objets et les télécharger.

Création d'un bucket

Un bucket est un espace de noms globalement unique dans OSS qui stocke des objets.

Remarque

Endpoints : Régions et endpoints. Conventions de nommage des buckets : Concepts de base.

Le code suivant crée un bucket.

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
$provider = new EnvironmentVariableCredentialsProvider();
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket.
$bucket= "examplebucket";
try {
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);
    // Set the storage class of the bucket to Infrequent Access (IA). The default storage class is Standard.
    $options = array(
        OssClient::OSS_STORAGE => OssClient::OSS_STORAGE_IA
    );
    // Set the ACL of the bucket to public-read. The default bucket ACL is private.
    $ossClient->createBucket($bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ, $options);
} catch (OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");        

Chargement d'un objet

Le code suivant charge un objet vers OSS par flux continu.

<?phpif (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;

// Obtain access credentials from environment variables.$provider = new EnvironmentVariableCredentialsProvider();
// Specify the endpoint of the region. For example, https://oss-cn-hangzhou.aliyuncs.com.$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name.$bucket= "examplebucket";
// Specify the object key. Do not include the bucket name.$object = "exampledir/exampleobject.txt";
// Specify the content to upload.$content = "Hello OSS";

// Optional: set the object ACL to private and add custom metadata.$options = array(
    OssClient::OSS_HEADERS => array(
        'x-oss-object-acl' => 'private',
        'x-oss-meta-info' => 'yourinfo'
    ),
);

try {
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region" => "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

    $ossClient->putObject($bucket, $object, $content, $options);
} catch (OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");

La méthode putObject charge le contenu vers la clé d'objet spécifiée. Utilisez l'option OssClient::OSS_HEADERS pour définir la liste de contrôle d'accès (ACL) de l'objet ou ajouter des métadonnées personnalisées.

Téléchargement d'un objet

Le code suivant télécharge un objet.

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;

// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// Specify the Endpoint for the region where the bucket is located. For example, for the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object. Do not include the bucket name. Example: testfolder/exampleobject.txt.
$object = "testfolder/exampleobject.txt";
// Download the object to a local file named examplefile.txt and save it to the specified local path (D:\\localpath). If the local file exists, it is overwritten. If it does not exist, it is created.
// If you do not specify a local path, the downloaded file is saved to the local path of the project where the sample program resides.
$localfile = "D:\\localpath\\examplefile.txt";
$options = array(
        OssClient::OSS_FILE_DOWNLOAD => $localfile
    );

// Use a try-catch block to catch exceptions. If an exception is caught, the download failed. If no exception is caught, the download is successful.
try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

    $ossClient->getObject($bucket, $object, $options);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK, please check localfile: 'examplefile.txt'" . "\n");
        

Répertoriation des objets

Le code suivant répertorie les objets contenus dans un bucket. Par défaut, jusqu'à 100 objets sont renvoyés.

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;

try {
    // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
    $provider = new EnvironmentVariableCredentialsProvider();
    // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint.
    $endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    // Specify the bucket name. Example: examplebucket.
    $bucket= "examplebucket";
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint, 
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"       
    );
    $ossClient = new OssClient($config);
    $listObjectInfo = $ossClient->listObjects($bucket);
    printf("Bucket Name: %s". "\n",$listObjectInfo->getBucketName());
    printf("Prefix: %s". "\n",$listObjectInfo->getPrefix());
    printf("Marker: %s". "\n",$listObjectInfo->getMarker());
    printf("Next Marker: %s". "\n",$listObjectInfo->getNextMarker());
    printf("Max Keys: %s". "\n",$listObjectInfo->getMaxKeys());
    printf("Delimiter: %s". "\n",$listObjectInfo->getDelimiter());
    printf("Is Truncated: %s". "\n",$listObjectInfo->getIsTruncated());
    $objectList = $listObjectInfo->getObjectList();
    $prefixList = $listObjectInfo->getPrefixList();
    if (!empty($objectList)) {
        print("objectList:\n");
        foreach ($objectList as $objectInfo) {
            printf("Object Name: %s". "\n",$objectInfo->getKey());
            printf("Object Size: %s". "\n",$objectInfo->getSize());
            printf("Object Type: %s". "\n",$objectInfo->getType());
            printf("Object ETag: %s". "\n",$objectInfo->getETag());
            printf("Object Last Modified: %s". "\n",$objectInfo->getLastModified());
            printf("Object Storage Class: %s". "\n",$objectInfo->getStorageClass());

            if ($objectInfo->getRestoreInfo()){
                printf("Restore Info: %s". "\n",$objectInfo->getRestoreInfo() );
            }

            if($objectInfo->getOwner()){
                printf("Owner Id:".$objectInfo->getOwner()->getId() . "\n");
                printf("Owner Name:".$objectInfo->getOwner()->getDisplayName() . "\n");
            }
        }
    }
    if (!empty($prefixList)) {
        print("prefixList: \n");
        foreach ($prefixList as $prefixInfo) {
            printf("Common Prefix:%s\n",$prefixInfo->getPrefix());
        }
    }
} catch (OssException $e) {
    printf($e->getMessage() . "\n");
    return;
}

Suppression d'un objet

Le code suivant supprime un objet spécifié.

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
$provider = new EnvironmentVariableCredentialsProvider();
// Set endpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "yourEndpoint";
// Specify the bucket name. Example: examplebucket.
$bucket = "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path cannot contain the bucket name.
$object = "exampledir/exampleobject.txt";

try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

    $ossClient->deleteObject($bucket, $object);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . "OK" . "\n");          

Références

  • Exemple de code complet : Exemple GitHub.

  • Pour plus d'informations sur l'opération API de création d'un bucket, consultez PutBucket.

  • Pour plus d'informations sur l'opération API de chargement d'un objet, consultez PutObject.

  • Pour plus d'informations sur l'opération API de téléchargement d'un objet, consultez GetObject.

  • Pour plus d'informations sur l'opération API de répertoriation des objets, consultez GetBucket (ListObjects).

  • Pour plus d'informations sur l'opération API de suppression d'un objet, consultez DeleteObject.