Use the doesObjectExist method to check whether a specified object exists in a bucket.
Prerequisites
Before you begin, make sure that you have:
The
oss:GetObjectpermission on the target object. For details, see Attach a custom policy to a RAM userThe
OSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETenvironment variables configured with valid credentials
Usage notes
The example uses the public endpoint for the China (Hangzhou) region. To access OSS from another Alibaba Cloud service in the same region, replace the endpoint with the corresponding internal endpoint. For a full list of endpoints, see Regions and endpoints.
The example creates an OSSClient instance using an OSS endpoint. To create an instance using a custom domain name or Security Token Service (STS), see Create an OSSClient instance.
Sample code
<?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;
// Load credentials from environment variables.
// Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET before running this example.
$provider = new EnvironmentVariableCredentialsProvider();
// Replace with your actual endpoint. This example uses the China (Hangzhou) public endpoint.
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
$bucket = "examplebucket";
$object = "exampledir/exampleobject.txt";
try {
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region" => "cn-hangzhou"
);
$ossClient = new OssClient($config);
$exist = $ossClient->doesObjectExist($bucket, $object);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
var_dump($exist);Replace the following placeholders:
| Placeholder | Description |
|---|---|
examplebucket | Name of the bucket that contains the object |
exampledir/exampleobject.txt | Full path of the object to check |