January 19, 2025
+ 12
Installing the Couchbase PHP SDK & a Hello World example program.

The Couchbase PHP SDK allows you to connect to a Couchbase cluster from PHP. It is a native PHP extension and uses the Couchbase++ high-performance C++ library to handle communicating to the cluster over Couchbase binary protocols.

In this guide, you will learn:

Hello Couchbase

We will go through the code sample step by step, but for those in a hurry to see it, here it is:

If you are connecting to Couchbase Capella, be sure to get the correct endpoint as well as the username and password.

<?php

// NOTE: Change the below vendor path to your own.
require_once '../../../vendor/autoload.php';

use Couchbase\ClusterOptions;
use Couchbase\Cluster;

// Update these credentials for your Capella instance!
$connectionString = "couchbases://cb.<your-instance>.cloud.couchbase.com";
$options = new ClusterOptions();

$options->credentials("username", "Password!123");
// Sets a pre-configured profile called "wan_development" to help avoid latency issues
// when accessing Capella from a different Wide Area Network
// or Availability Zone (e.g. your laptop).
$options->applyProfile("wan_development");
$cluster = new Cluster($connectionString, $options);

// get a bucket reference
$bucket = $cluster->bucket("travel-sample");

// get a user-defined collection reference
$scope = $bucket->scope("tenant_agent_00");
$collection = $scope->collection("users");

$upsertResult = $collection->upsert("my-document-key", ["name" => "Ted", "Age" => 31]);

$getResult = $collection->get("my-document-key");

print_r($getResult->content());

$inventoryScope = $bucket->scope("inventory");
$queryResult = $inventoryScope->query("SELECT * FROM airline WHERE id = 10");

// Print result data to the terminal.
foreach ($queryResult->rows() as $row) {
    print_r($row);
}

The Couchbase Capella free tier version comes with the Travel Sample Bucket, and its Query indexes, loaded and ready.

Quick Installation

A more detailed guide in our Installation page covers every supported platform, but this section should be enough to get up and running in most cases.

On Mac and most Linux distributions, simply use pecl to install the Couchbase PHP SDK.

console
$ pecl install couchbase

Make sure to add the extension details to your php.ini. See post-installation instructions for full details:

ini
extension=couchbase

Additionally, if you are using Composer, simply update your composer.json file with the following dependencies:

json
"require": { ... "ext-couchbase": "^4.2", "couchbase/couchbase": "^4.2" }

And run the composer update command. If there are any problems, refer to the full Installation page.

Prerequisites

The following code samples assume:

  • You have signed up to Couchbase Capella.

  • You have created your own bucket, or loaded the Travel Sample dataset. Note, the Travel Sample dataset is installed automatically when deploying a Capella free tier cluster.

  • A user is created with permissions to access the cluster (at least Application Access permissions). See the Capella connection page for more details.

Couchbase Capella uses Roles to control user access to database resources. For the purposes of this guide, you can use the Organization Owner role automatically assigned to your account during installation of the Capella cluster. In a production scenario, we strongly recommend setting up users with more granular access roles as a best practice.

Step-by-step

Start a new project (in VS Code or PhpStorm, etc.) and create a file cb-test.php.

Go to our Platform Introduction if you don’t already have an editor or IDE setup for working with PHP — e.g. you are evaluating the PHP SDK, but it is not your normal platform.

Install the latest 4.x couchbase SDK package — see above.

Firstly, you will need to have a few import statements at the top of your PHP program:

// NOTE: Change the below vendor path to your own.
require_once '../../../vendor/autoload.php';

use Couchbase\ClusterOptions;
use Couchbase\Cluster;

Connect

Connect to your cluster by instantiating a new Cluster object and pass it your connection details. The basic connection details that you’ll need are given below — for more background information, see Managing Connections.

From version 4.0, the PHP SDK includes Capella’s standard certificates by default, so you do not need to additional configuration. You do need to enable TLS, which can be done by simply using couchbases:// in the connection string as in this example.

// Update these credentials for your Capella instance!
$connectionString = "couchbases://cb.<your-instance>.cloud.couchbase.com";
$options = new ClusterOptions();

$options->credentials("username", "Password!123");
// Sets a pre-configured profile called "wan_development" to help avoid latency issues
// when accessing Capella from a different Wide Area Network
// or Availability Zone (e.g. your laptop).
$options->applyProfile("wan_development");
$cluster = new Cluster($connectionString, $options);

When accessing Capella from a different Wide Area Network or Availability Zone, you may experience latency issues with the default connection settings. SDK 4.1 introduces a wan_development Configuration Profile, which provides pre-configured timeout settings suitable for working in high latency environments. Basic usage is shown in the example above, but if you want to learn more see Constrained Network Environments.

The Configuration Profiles feature is currently a Volatile API and may be subject to change.

Following successful authentication, add this code snippet to access your Bucket:

// get a bucket reference
$bucket = $cluster->bucket("travel-sample");

Add and Retrieve Documents

Collections allow Documents to be grouped by purpose or theme, according to specified Scope. Our Travel Sample bucket has separate scopes for inventory (flights, etc.), and for tenants (different travel agents).

Here we refer to the users collection within the tenant_agent_00 scope from the Travel Sample bucket as an example, but you may replace this with your own data.

// get a user-defined collection reference
$scope = $bucket->scope("tenant_agent_00");
$collection = $scope->collection("users");

Data operations, like storing and retrieving documents, can be done using simple methods on the Collection class such as Collection→get() and Collection→upsert().

Add the following code to create a new document and retrieve it:

$upsertResult = $collection->upsert("my-document-key", ["name" => "Ted", "Age" => 31]);

$getResult = $collection->get("my-document-key");

print_r($getResult->content());

SQL++ Lookup

Couchbase SQL++ queries can be performed at the Cluster or Scope level by invoking Cluster→query() or Scope→query().

Cluster level queries require you to specify the fully qualified keyspace each time (e.g. travel-sample.inventory.airline). However, with a Scope level query you only need to specify the Collection name — which in this case is airline:

$inventoryScope = $bucket->scope("inventory");
$queryResult = $inventoryScope->query("SELECT * FROM airline WHERE id = 10");

// Print result data to the terminal.
foreach ($queryResult->rows() as $row) {
    print_r($row);
}

You can learn more about SQL++ queries on the Query page.

Next Steps

Now you’re up and running, try one of the following:

Additional Resources

The API reference is generated for each release and can be found here. Older API references are linked from their respective sections in the Release Notes.

The Migrating to SDK API 3 page highlights the main differences to be aware of when migrating your code.

Couchbase welcomes community contributions to the PHP SDK. The PHP SDK source code is available on GitHub.

Troubleshooting