Liste todos os objetos em um bucket com o SDK do Object Storage Service (OSS) para PHP 2.0.
Notas de uso
O código de exemplo deste tópico usa o ID da região
cn-hangzhoupara a região china (Hangzhou). Por padrão, usa-se um endpoint público para acessar recursos em um bucket. Para acessar recursos com outros serviços do alibaba cloud na mesma região, use um endpoint interno. Para mais informações sobre as regiões e endpoints do OSS, consulte Regions and endpoints.Para listar objetos, é necessária a permissão
oss:ListObjects. Para mais informações, consulte Grant a custom policy.
Código de exemplo
O OSS retorna até 1.000 objetos por solicitação. O ListObjectsV2Paginator gerencia a paginação automaticamente: o loop foreach externo itera pelas páginas, e o interno, pelos objetos de cada página.
Primeiro, crie um cliente OSS. O exemplo a seguir usa o ListObjectsV2Paginator para listar todos os objetos em um 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
}
}
Cenários comuns
Listar todos os objetos em um diretório
Listar objetos cujos nomes contêm um prefixo específico
Listar uma quantidade específica de objetos
Listar todos os objetos a partir de uma posição específica
Listar todos os subdiretórios no diretório raiz
Referência
Para o código de exemplo completo, consulte GitHub.