Répertoriez tous les objets d'un bucket à l'aide du SDK Object Storage Service (OSS) pour PHP 2.0.
Notes d'utilisation
L'exemple de code de cette rubrique utilise l'ID de région
cn-hangzhoupour la région Chine (Hangzhou). Par défaut, un endpoint public permet d'accéder aux ressources d'un bucket. Pour accéder aux ressources via d'autres services Alibaba Cloud situés dans la même région, utilisez un endpoint interne. Pour plus d'informations sur les régions et les endpoints OSS, consultez la page Régions et endpoints.Pour répertorier les objets, vous devez disposer de l'autorisation
oss:ListObjects. Pour plus d'informations, consultez la section Accorder une politique personnalisée.
Exemple de code
OSS renvoie jusqu'à 1 000 objets par requête. La classe ListObjectsV2Paginator gère automatiquement la pagination : la boucle foreach externe itère sur les pages, tandis que la boucle interne parcourt les objets de chaque page.
L'exemple suivant utilise ListObjectsV2Paginator pour répertorier tous les objets d'un bucket :
<?php
// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Specify descriptions for command line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];
// Convert the parameter descriptions to a long options list required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Obtain the help information about the parameters.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // If the required parameters are not configured, exit the program.
}
}
// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load access credentials from environment variables.
// EnvironmentVariableCredentialsProvider reads the AccessKey ID and AccessKey secret
// from environment variables, keeping credentials out of your source code.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default SDK configuration.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided.
}
// Create an OSS client.
$client = new Oss\Client($cfg);
// Use ListObjectsV2Paginator to list all objects across pages.
// The outer foreach iterates over pages; the inner foreach iterates over objects on each page.
$paginator = new Oss\Paginator\ListObjectsV2Paginator(client: $client);
$iter = $paginator->iterPage(new Oss\Models\ListObjectsV2Request(bucket: $bucket));
foreach ($iter as $page) {
foreach ($page->contents ?? [] as $object) {
// Print the name, type, and size of each object.
print("Object: $object->key, $object->type, $object->size\n");
// Example output: Object: example/photo.jpg, Normal, 10240
}
}
Scénarios courants
Répertorier tous les objets d'un répertoire
Répertorier les objets dont le nom contient un préfixe spécifique
Limiter le nombre d'objets répertoriés
Démarrer la liste à partir d'une position spécifique
Lister tous les sous-répertoires du répertoire racine
Référence
Pour consulter l'exemple de code complet, rendez-vous sur GitHub.