+++
title = "Standalone PHP"
weight = 114
aliases = ["/docs/php", "/docs/managed-search/elasticsearch-and-opensearch/using-your-cluster/connecting/php/standalone/", "/docs/using-your-cluster/connecting/php/"]

[extra]
weight = 10
nav_title = "PHP"
+++

Instructions on adding and using the Elasticsearch library with a PHP app.

Getting Elasticsearch up and running with a PHP app is fairly straightforward. We recommend using
the [official PHP client](https://github.com/elastic/elasticsearch-php), as it is being actively developed alongside
Elasticsearch.

## Adding the Elasticsearch library

Like [Heroku](https://www.heroku.com), we recommend [Composer](https://getcomposer.org) for dependency management in PHP
projects, so you'll need to add the Elasticsearch library to
your [composer.json file](https://getcomposer.org/doc/04-schema.md):

```json
{
  "require": {
    "elasticsearch/elasticsearch": "1.0"
  }
}
```

Heroku will automatically add the library when you deploy your code.

## Using the library

The elasticsearch-php library is configured almost entirely by associative arrays. To initialize your client, use the
following code block:

```php
// Initialize the parameters for the cluster
$params = array();
$params['hosts'] = array (
    getenv("BONSAI_URL"),
);
$client = new Elasticsearch\Client($params);
```

Note that the host is pulled from the environment. When you add Bonsai to your app, the cluster will be automatically
created and a `BONSAI_URL` variable will be added to your environment. The initialization process above allows you to
access your cluster without needing to hardcode your authentication credentials.

## Indexing your documents

Bonsai does not support lazy index creation, so you will need
to [create your index](https://www.elastic.co/guide/en/elasticsearch/client/php-api/0.4/_index_operations.html) before
you can send over your
documents. You can specify a number of parameters to configure your new index; the code below is the minimum needed to
get started:

```php
$indexParams = array();
$indexParams['index'] = 'my_index'; //index
$client->indices()->create($indexParams);
```

Once your index has been created, you can add a document by specifying a body (an associative array of fields and data),
target index, type and (optionally) a document ID. If you don't specify an ID, Elasticsearch will create one for you:

```php
$params['body'] = array('testField' => 'abc');
$params['index'] = 'my_index';
$params['type'] = 'my_type';
$params['id'] = 'my_id';
// Document will be indexed to my_index/my_type/my_id
$ret = $client->index($params);
```