All Products
Search
Document Center

Object Storage Service:Determine whether a bucket exists (PHP SDK V2)

Last Updated:Mar 20, 2026

Call isBucketExist to check whether a bucket exists before performing operations on it. The method returns a boolean: true if the bucket exists, false if it does not.

Prerequisites

Before you begin, ensure that you have:

Check whether a bucket exists

The core call is a single line:

$exist = $client->isBucketExist($bucket);

isBucketExist returns true if the bucket exists, false if it does not.

The following example shows a complete, runnable script that accepts the bucket name and region as command-line arguments, loads credentials from environment variables, and prints the result.

<?php

require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define command-line parameters.
$optsdesc = [
    "region"   => ['help' => 'The region in which the bucket is located.', 'required' => true],
    "endpoint" => ['help' => 'The endpoint for other services to access OSS.', 'required' => false],
    "bucket"   => ['help' => 'The name of the bucket.', 'required' => true],
];

$longopts = array_map(fn($key) => "$key:", array_keys($optsdesc));
$options  = getopt("", $longopts);

foreach ($optsdesc as $key => $value) {
    if ($value['required'] === true && empty($options[$key])) {
        echo "Error: --$key is required. " . $value['help'] . PHP_EOL;
        exit(1);
    }
}

$region = $options["region"];
$bucket = $options["bucket"];

// Load credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Configure and create the OSS client.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);

if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

$client = new Oss\Client($cfg);

// Check whether the bucket exists.
$exist = $client->isBucketExist($bucket);

printf('bucket exists: %s' . PHP_EOL, var_export($exist, true));

Run the script with the required parameters:

php IsBucketExist.php --region <region-id> --bucket <bucket-name>

Replace the following placeholders:

PlaceholderDescriptionExample
<region-id>The region ID of the bucketcn-hangzhou
<bucket-name>The name of the bucketmy-bucket

Usage notes

  • The example uses the region ID cn-hangzhou for the China (Hangzhou) region. By default, a public endpoint is used. If you access OSS from another Alibaba Cloud service in the same region, use an internal endpoint instead. For a full list of regions and endpoints, see Regions and endpoints.

  • The script loads credentials (AccessKey ID and AccessKey secret) from environment variables. Ensure the required environment variables are set before running the script.

References