Use o OSS SDK for PHP 2.0 para verificar se um objeto existe em um bucket.
Observações de uso
O código de exemplo neste tópico usa o ID da região
cn-hangzhou, referente à região China (Hangzhou). Por padrão, o acesso aos recursos do bucket ocorre por um endpoint público. Para acessar esses recursos a partir de outros serviços da Alibaba Cloud na mesma região do bucket, use um endpoint interno. Para mais informações sobre as regiões e endpoints compatíveis com o OSS, consulte Regiões e endpoints.Para baixar um objeto, você precisa da permissão
oss:GetObject. Para mais informações, consulte Conceder uma política de acesso personalizada a um usuário RAM.
Código de exemplo
O código abaixo verifica se um objeto específico existe.
<?php
// Import the autoloader file to ensure that dependency libraries are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define the description of command line arguments.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. (Required)
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint. (Optional)
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The name of the bucket. (Required)
"key" => ['help' => 'The name of the object', 'required' => True], // The name of the object. (Required)
];
// Transform the argument descriptions into the long option format required by getopt.
// A colon (:) after each argument indicates that the argument requires a value.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command line arguments.
$options = getopt("", $longopts);
// Authenticate whether the required parameters are specified.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Obtain the help information of the parameter.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // If a required parameter is missing, exit the program.
}
}
// Fetch values from the parsed parameters.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of the object.
// Load the credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credentials provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Check whether the object exists.
$exist = $client->isObjectExist(bucket: $bucket, key: $key);
// Print the check result.
printf(
'object is exist:' . var_export($exist, true) . PHP_EOL // Output the Boolean value that indicates whether the object exists.
);
Referências
Para obter o código de exemplo completo, consulte GitHub.
Para obter detalhes sobre a operação de API, consulte IsObjectExist.