Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Zend Framework 101: Zend_Service_Amazon_S3

Create a Bucket

Buckets are created using the createBucket() method. This method accepts the name of the bucket as its first argument. If the bucket is successfully created, this method returns true. If the name of the bucket is not valid, an exception is thrown.

If the bucket cannot be created (likely due to somebody else owning that bucket name), false is returned from createBucket().

It is important to note that if you have already created a bucket then try to create it again, true will still be returned. If you want to ensure that a new bucket is being creating you should first retrieve a list of buckets and check for the name.

The following listing demonstrates creating a bucket.

Listing 4 Creating a new bucket (create-bucket.php)
    $awsKey       = '[your key]';
    $awsSecretKey = '[your secret key]';
    $s3 = new Zend_Service_Amazon_S3($awsKey, $awsSecretKey);
    $bucketName = 'phpriot-test-bucket';
    try {
        $buckets    = $s3->getBuckets();
        if (in_array($bucketName, $buckets)) {
            throw new Exception('You already have this bucket');
        $succ = $s3->createBucket($bucketName);
        if ($succ) {
            echo "Bucket created!";
        else {
            echo "Unable to create bucket!";
    catch (Exception $ex) {
        echo $ex->getMessage();

This code begins by specifying the name of the bucket to create in $bucketName. It then retrieves a list of buckets and checks that you don't already have that bucket. If so, it throws an exception which is then handled at the bottom of the script.

Next it tries to create the bucket. If the name is invalid an exception is thrown. Otherwise, the call to createBucket() returns a boolean.

In This Article

Bonus listings: 2 available