influxdb-client-php
This repository contains the reference PHP client for the InfluxDB 2.x.
Note: Use this client library with InfluxDB 2.x and InfluxDB 1.8+ (see details). For connecting to InfluxDB 1.7 or earlier instances, use the influxdb-php client library.
Documentation
This section contains links to the client library documentation.
Installation
The client is not hard coupled to HTTP client library like Guzzle, Buzz or something else.
The client uses general abstractions (PSR-7 - HTTP messages,
PSR-17 - HTTP factories, PSR-18 - HTTP client) which give you
freedom to use your favorite one.
Install the library
The InfluxDB 2 client is bundled and hosted on https://packagist.org/ and can be installed with composer:
composer require influxdata/influxdb-client-php guzzlehttp/guzzle
Usage
Creating a client
Use InfluxDB2\Client to create a client connected to a running InfluxDB 2 instance.
$client = new InfluxDB2\Client([
"url" => "http://localhost:8086",
"token" => "my-token",
"bucket" => "my-bucket",
"org" => "my-org",
"precision" => InfluxDB2\Model\WritePrecision::NS
]);
Client Options
| Option |
Description |
Note |
Type |
Default |
| url |
InfluxDB server API url (e.g. http://localhost:8086) |
required |
String |
none |
| token |
Token to use for the authorization |
required |
String |
none |
| bucket |
Default destination bucket for writes |
|
String |
none |
| org |
Default destination organization for writes |
|
String |
none |
| precision |
Default precision for the unix timestamps within the body line-protocol |
|
String |
none |
| allow_redirects |
Enable HTTP redirects |
|
bool |
true |
| debug |
Enable verbose logging of http requests |
|
bool |
false |
| logFile |
Default output for logs |
|
bool |
php://output |
| httpClient |
Configured HTTP client to use for communication with InfluxDB |
|
Psr\Http\Client\ClientInterface |
none |
| verifySSL |
Turn on/off SSL certificate verification. Set to false to disable certificate verification. |
:warning: required Guzzle HTTP client |
bool |
true |
| timeout |
Describing the number of seconds to wait while trying to connect to a server. Use 0 to wait indefinitely. |
:warning: required Guzzle HTTP client |
int |
10 |
| proxy |
specify an HTTP proxy, or an array to specify different proxies for different protocols. |
:warning: required Guzzle HTTP client |
string |
none |
| udpPort |
Port for the UDP connection |
|
int |
none |
| ipVersion |
You can specify the ip version |
|
int (4 or 6) |
4 |
| udpPort |
Host for the UDP connection, otherwise udpHost will parsed from url option |
|
String |
url host |
| tags |
default tags (e.g "tags" => ['id' => '1234', 'hostname' => '${env.Hostname}'] |
|
array<String, String> |
none |
Custom HTTP client
The following code shows how to use and configure cURL HTTP client:
Install dependencies via composer
composer require influxdata/influxdb-client-php nyholm/psr7 php-http/curl-client
Configure cURL client
$curlOptions = [
CURLOPT_CONNECTTIMEOUT => 30, // The number of seconds to wait while trying to connect.
];
$curlClient = new Http\Client\Curl\Client(
Http\Discovery\Psr17FactoryDiscovery::findRequestFactory(),
Http\Discovery\Psr17FactoryDiscovery::findStreamFactory(),
$curlOptions
);
Initialize InfluxDB client
$client = new Client([
"url" => "http://localhost:8086",
"token" => "my-token",
"bucket" => "my-bucket",
"org" => "my-org",
"httpClient" => $curlClient
]);
Queries
The result retrieved by QueryApi could be formatted as a:
- Raw query response
- Flux data structure: FluxTable, FluxColumn and FluxRecord
- Stream of FluxRecord
Query raw
Synchronously executes the Flux query and return result as unprocessed String
$this->client = new Client([
"url" => "http://localhost:8086",
"token" => "my-token",
"bucket" => "my-bucket",
"precision" => WritePrecision::NS,
"org" => "my-org",
"debug" => false
]);
$this->queryApi = $this->client->createQueryApi();
$result = $this->queryApi->queryRaw(
'from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()');
Synchronous query
Synchronously executes the Flux query and return result as a Array of FluxTables
$this->client = new Client([
"url" => "http://localhost:8086",
"token" => "my-token",
"bucket" => "my-bucket",
"precision" => WritePrecision::NS,
"org" => "my-org",
"debug" => false
]);
$this->queryApi = $this->client->createQueryApi();
$result = $this->queryApi->query(
'from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()');
This can then easily be encoded to JSON with json_encode
header('Content-type:application/json;charset=utf-8');
echo json_encode( $result, JSON_PRETTY_PRINT ) ;
Query stream
Synchronously executes the Flux query and return stream of FluxRecord
$this->client = new Client([
"url" => "http://localhost:8086",
"token" => "my-token",
"bucket" => "my-bucket",
"precision" => WritePrecision::NS,
"org" => "my-org",
"debug" => false
]);
$this->queryApi = $this->client->createQueryApi();
$parser = $this->queryApi->queryStream(
'from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()');
foreach ($parser->each() as $record)
{
...
}
Parameterized queries
InfluxDB Cloud supports Parameterized Queries
that let you dynamically change values in a query using the InfluxDB API. Parameterized queries make Flux queries more
reusable and can also be used to help prevent injection attacks.
InfluxDB Cloud inserts the params object into the Flux query as a Flux record named params. Use dot or bracket
notation to access parameters in the params record in your Flux query. Parameterized Flux queries support only int
, float, and string data types. To convert the supported data types into
other Flux basic data types, use Flux type conversion functions.
Parameterized query example:
:warning: Parameterized Queries are supported only in InfluxDB Cloud, currently there is no support in InfluxDB OSS.
<?php
require __DIR__ . '/../vendor/autoload.php';
use InfluxDB2\Client;
use InfluxDB2\Model\Query;
use InfluxDB2\Point;
use InfluxDB2\WriteType as WriteType;
$url = "https://us-west-2-1.aws.cloud2.influxdata.com";
$organization = 'my-org';
$bucket = 'my-bucket';
$token = 'my-token';
$client = new Client([
"url" => $url,
"token" => $token,
"bucket" => $bucket,
"org" => $organization,
"precision" => InfluxDB2\Model\WritePrecision::NS,
"debug" => false
]);
$writeApi = $client->createWriteApi(["writeType" => WriteType::SYNCHRONOUS]);
$queryApi = $client->createQueryApi();
$today = new DateTime("now");
$yesterday = $today->sub(new DateInterval("P1D"));
$p = new Point("temperature");
$p->addTag("location", "north")->addField("value", 60)->time($yesterday);
$writeApi->write($p);
$writeApi->close();
//
// Query range start parameter using duration
//
$parameterizedQuery = "from(bucket: params.bucketParam) |> range(start: duration(v: params.startParam))";
$query = new Query();
$query->setQuery($parameterizedQuery);
$query->setParams(["bucketParam" => "my-bucket", "startParam" => "-1d"]);
$tables = $queryApi->query($query);
foreach ($tables as $table) {
foreach ($table->records as $record) {
var_export($record->values);
}
}
//
// Query range start parameter using DateTime
//
$parameterizedQuery = "from(bucket: params.bucketParam) |> range(start: time(v: params.startParam))";
$query->setParams(["bucketParam" => "my-bucket", "startParam" => $yesterday]);
$query->setQuery($parameterizedQuery);
$tables = $queryApi->query($query);
foreach ($tables as $table) {
foreach ($table->records as $record) {
var_export($record->values);
}
}
$client->close();
Writing data
The WriteApi supports
synchronous and batching writes into InfluxDB 2.x. In default api uses synchronous write. To enable batching you
can use WriteOption.
$client = new InfluxDB2\Client(["url" => "http://localhost:8086", "token" => "my-token",
"bucket" => "my-bucket",
"org" => "my-org",
"precision" => InfluxDB2\Model\WritePrecision::NS
]);
$write_api = $client->createWriteApi();
$write_api->write('h2o,location=west value=33i 15');
Batching
The writes are processed in batches which are configurable by WriteOptions:
| Property |
Description |
Default Value |
| writeType |
type of write SYNCHRONOUS / BATCHING / |
SYNCHRONOUS |
| batchSize |
the number of data point to collect in batch |
10 |
| retryInterval |
the number of milliseconds to retry unsuccessful write. The retry interval is "exponentially" used when the InfluxDB server does not specify "Retry-After" header. |
5000 |
| jitterInterval |
the number of milliseconds before the data is written increased by a random amount |
0 |
| maxRetries |
the number of max retries when write fails |
5 |
| maxRetryDelay |
maximum delay when retrying write in milliseconds |
125000 |
| maxRetryTime |
maximum total retry timeout in milliseconds |
180000 |