influxdb-client-php

PHP - 图1

CircleCI codecov Packagist Version License GitHub issues GitHub pull requests PHP from Packagist Slack Status

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.

PHP - 图10

Documentation

PHP - 图11

This section contains links to the client library documentation.

Installation

PHP - 图12

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

PHP - 图13

The InfluxDB 2 client is bundled and hosted on https://packagist.org/ and can be installed with composer:

  1. composer require influxdata/influxdb-client-php guzzlehttp/guzzle

Usage

PHP - 图14

Creating a client

PHP - 图15

Use InfluxDB2\Client to create a client connected to a running InfluxDB 2 instance.

  1. $client = new InfluxDB2\Client([
  2. "url" => "http://localhost:8086",
  3. "token" => "my-token",
  4. "bucket" => "my-bucket",
  5. "org" => "my-org",
  6. "precision" => InfluxDB2\Model\WritePrecision::NS
  7. ]);

Client Options

PHP - 图16

OptionDescriptionNoteTypeDefault
urlInfluxDB server API url (e.g. http://localhost:8086)requiredStringnone
tokenToken to use for the authorizationrequiredStringnone
bucketDefault destination bucket for writesStringnone
orgDefault destination organization for writesStringnone
precisionDefault precision for the unix timestamps within the body line-protocolStringnone
allow_redirectsEnable HTTP redirectsbooltrue
debugEnable verbose logging of http requestsboolfalse
logFileDefault output for logsboolphp://output
httpClientConfigured HTTP client to use for communication with InfluxDBPsr\Http\Client\ClientInterfacenone
verifySSLTurn on/off SSL certificate verification. Set to false to disable certificate verification.⚠️ required Guzzle HTTP clientbooltrue
timeoutDescribing the number of seconds to wait while trying to connect to a server. Use 0 to wait indefinitely.⚠️ required Guzzle HTTP clientint10
proxyspecify an HTTP proxy, or an array to specify different proxies for different protocols.⚠️ required Guzzle HTTP clientstringnone

Custom HTTP client

PHP - 图17

The following code shows how to use and configure cURL HTTP client:

Install dependencies via composer

PHP - 图18

  1. composer require influxdata/influxdb-client-php nyholm/psr7 php-http/curl-client
Configure cURL client

PHP - 图19

  1. $curlOptions = [
  2. CURLOPT_CONNECTTIMEOUT => 30, // The number of seconds to wait while trying to connect.
  3. ];
  4. $curlClient = new Http\Client\Curl\Client(
  5. Http\Discovery\Psr17FactoryDiscovery::findRequestFactory(),
  6. Http\Discovery\Psr17FactoryDiscovery::findStreamFactory(),
  7. $curlOptions
  8. );
Initialize InfluxDB client

PHP - 图20

  1. $client = new Client([
  2. "url" => "http://localhost:8086",
  3. "token" => "my-token",
  4. "bucket" => "my-bucket",
  5. "org" => "my-org",
  6. "httpClient" => $curlClient
  7. ]);

Queries

PHP - 图21

The result retrieved by QueryApi could be formatted as a:

  1. Raw query response
  2. Flux data structure: FluxTable, FluxColumn and FluxRecord
  3. Stream of FluxRecord

Query raw

PHP - 图22

Synchronously executes the Flux query and return result as unprocessed String

  1. $this->client = new Client([
  2. "url" => "http://localhost:8086",
  3. "token" => "my-token",
  4. "bucket" => "my-bucket",
  5. "precision" => WritePrecision::NS,
  6. "org" => "my-org",
  7. "debug" => false
  8. ]);
  9. $this->queryApi = $this->client->createQueryApi();
  10. $result = $this->queryApi->queryRaw(
  11. 'from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()');

Synchronous query

PHP - 图23

Synchronously executes the Flux query and return result as a Array of FluxTables

  1. $this->client = new Client([
  2. "url" => "http://localhost:8086",
  3. "token" => "my-token",
  4. "bucket" => "my-bucket",
  5. "precision" => WritePrecision::NS,
  6. "org" => "my-org",
  7. "debug" => false
  8. ]);
  9. $this->queryApi = $this->client->createQueryApi();
  10. $result = $this->queryApi->query(
  11. 'from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()');

This can then easily be encoded to JSON with json_encode

  1. header('Content-type:application/json;charset=utf-8');
  2. echo json_encode( $result, JSON_PRETTY_PRINT ) ;

Query stream

PHP - 图24

Synchronously executes the Flux query and return stream of FluxRecord

  1. $this->client = new Client([
  2. "url" => "http://localhost:8086",
  3. "token" => "my-token",
  4. "bucket" => "my-bucket",
  5. "precision" => WritePrecision::NS,
  6. "org" => "my-org",
  7. "debug" => false
  8. ]);
  9. $this->queryApi = $this->client->createQueryApi();
  10. $parser = $this->queryApi->queryStream(
  11. 'from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()');
  12. foreach ($parser->each() as $record)
  13. {
  14. ...
  15. }

Parameterized queries

PHP - 图25

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:

⚠️ Parameterized Queries are supported only in InfluxDB Cloud, currently there is no support in InfluxDB OSS.

  1. <?php
  2. require __DIR__ . '/../vendor/autoload.php';
  3. use InfluxDB2\Client;
  4. use InfluxDB2\Model\Query;
  5. use InfluxDB2\Point;
  6. use InfluxDB2\WriteType as WriteType;
  7. $url = "https://us-west-2-1.aws.cloud2.influxdata.com";
  8. $organization = 'my-org';
  9. $bucket = 'my-bucket';
  10. $token = 'my-token';
  11. $client = new Client([
  12. "url" => $url,
  13. "token" => $token,
  14. "bucket" => $bucket,
  15. "org" => $organization,
  16. "precision" => InfluxDB2\Model\WritePrecision::NS,
  17. "debug" => false
  18. ]);
  19. $writeApi = $client->createWriteApi(["writeType" => WriteType::SYNCHRONOUS]);
  20. $queryApi = $client->createQueryApi();
  21. $today = new DateTime("now");
  22. $yesterday = $today->sub(new DateInterval("P1D"));
  23. $p = new Point("temperature");
  24. $p->addTag("location", "north")->addField("value", 60)->time($yesterday);
  25. $writeApi->write($p);
  26. $writeApi->close();
  27. //
  28. // Query range start parameter using duration
  29. //
  30. $parameterizedQuery = "from(bucket: params.bucketParam) |> range(start: duration(v: params.startParam))";
  31. $query = new Query();
  32. $query->setQuery($parameterizedQuery);
  33. $query->setParams(["bucketParam" => "my-bucket", "startParam" => "-1d"]);
  34. $tables = $queryApi->query($query);
  35. foreach ($tables as $table) {
  36. foreach ($table->records as $record) {
  37. var_export($record->values);
  38. }
  39. }
  40. //
  41. // Query range start parameter using DateTime
  42. //
  43. $parameterizedQuery = "from(bucket: params.bucketParam) |> range(start: time(v: params.startParam))";
  44. $query->setParams(["bucketParam" => "my-bucket", "startParam" => $yesterday]);
  45. $query->setQuery($parameterizedQuery);
  46. $tables = $queryApi->query($query);
  47. foreach ($tables as $table) {
  48. foreach ($table->records as $record) {
  49. var_export($record->values);
  50. }
  51. }
  52. $client->close();

Writing data

PHP - 图26

The WriteApi supports synchronous and batching writes into InfluxDB 2.x. In default api uses synchronous write. To enable batching you can use WriteOption.

  1. $client = new InfluxDB2\Client(["url" => "http://localhost:8086", "token" => "my-token",
  2. "bucket" => "my-bucket",
  3. "org" => "my-org",
  4. "precision" => InfluxDB2\Model\WritePrecision::NS
  5. ]);
  6. $write_api = $client->createWriteApi();
  7. $write_api->write('h2o,location=west value=33i 15');

Batching

PHP - 图27

The writes are processed in batches which are configurable by WriteOptions:

PropertyDescriptionDefault Value
writeTypetype of write SYNCHRONOUS / BATCHING /SYNCHRONOUS
batchSizethe number of data point to collect in batch10
retryIntervalthe number of milliseconds to retry unsuccessful write. The retry interval is “exponentially” used when the InfluxDB server does not specify “Retry-After” header.5000
jitterIntervalthe number of milliseconds before the data is written increased by a random amount0
maxRetriesthe number of max retries when write fails5
maxRetryDelaymaximum delay when retrying write in milliseconds125000
maxRetryTimemaximum total retry timeout in milliseconds180000
exponentialBasethe base for the exponential retry delay, the next delay is computed using random exponential backoff as a random value within the interval retryInterval exponentialBase^(attempts-1) and retryInterval exponentialBase^(attempts). Example for retryInterval=5000, exponentialBase=2, maxRetryDelay=125000, total=5 Retry delays are random distributed values within the ranges of [5000-10000, 10000-20000, 20000-40000, 40000-80000, 80000-125000]2
  1. use InfluxDB2\Client;
  2. use InfluxDB2\WriteType as WriteType;
  3. $client = new Client(["url" => "http://localhost:8086", "token" => "my-token",
  4. "bucket" => "my-bucket",
  5. "org" => "my-org",
  6. "precision" => InfluxDB2\Model\WritePrecision::NS
  7. ]);
  8. $writeApi = $client->createWriteApi(
  9. ["writeType" => WriteType::BATCHING, 'batchSize' => 1000]);
  10. foreach (range(1, 10000) as $number) {
  11. $writeApi->write("mem,host=aws_europe,type=batch value=1i $number");
  12. }
  13. // flush remaining data
  14. $writeApi->close();

Time precision

PHP - 图28

Configure default time precision:

  1. $client = new InfluxDB2\Client(["url" => "http://localhost:8086", "token" => "my-token",
  2. "bucket" => "my-bucket",
  3. "org" => "my-org",
  4. "precision" => \InfluxDB2\Model\WritePrecision::NS
  5. ]);

Configure precision per write:

  1. $client = new InfluxDB2\Client([
  2. "url" => "http://localhost:8086",
  3. "token" => "my-token",
  4. "bucket" => "my-bucket",
  5. "org" => "my-org",
  6. ]);
  7. $writeApi = $client->createWriteApi();
  8. $writeApi->write('h2o,location=west value=33i 15', \InfluxDB2\Model\WritePrecision::MS);

Allowed values for precision are:

  • WritePrecision::NS for nanosecond
  • WritePrecision::US for microsecond
  • WritePrecision::MS for millisecond
  • WritePrecision::S for second

Configure destination

PHP - 图29

Default bucket and organization destination are configured via InfluxDB2\Client:

  1. $client = new InfluxDB2\Client([
  2. "url" => "http://localhost:8086",
  3. "token" => "my-token",
  4. "bucket" => "my-bucket",
  5. ]);

but there is also possibility to override configuration per write:

  1. $client = new InfluxDB2\Client(["url" => "http://localhost:8086", "token" => "my-token"]);
  2. $writeApi = $client->createWriteApi();
  3. $writeApi->write('h2o,location=west value=33i 15', \InfluxDB2\Model\WritePrecision::MS, "production-bucket", "customer-1");

Data format

PHP - 图30

The data could be written as:

  1. string that is formatted as a InfluxDB’s line protocol
  2. array with keys: name, tags, fields and time
  3. Data Point structure
  4. Array of above items
  1. $client = new InfluxDB2\Client([
  2. "url" => "http://localhost:8086",
  3. "token" => "my-token",
  4. "bucket" => "my-bucket",
  5. "org" => "my-org",
  6. "precision" => InfluxDB2\Model\WritePrecision::US
  7. ]);
  8. $writeApi = $client->createWriteApi();
  9. //data in Point structure
  10. $point=InfluxDB2\Point::measurement("h2o")
  11. ->addTag("location", "europe")
  12. ->addField("level",2)
  13. ->time(microtime(true));
  14. $writeApi->write($point);
  15. //data in array structure
  16. $dataArray = ['name' => 'cpu',
  17. 'tags' => ['host' => 'server_nl', 'region' => 'us'],
  18. 'fields' => ['internal' => 5, 'external' => 6],
  19. 'time' => microtime(true)];
  20. $writeApi->write($dataArray);
  21. //write lineprotocol
  22. $writeApi->write('h2o,location=west value=33i 15');

Default Tags

PHP - 图31

Sometimes is useful to store same information in every measurement e.g. hostname, location, customer. The client is able to use static value, app settings or env variable as a tag value.

The expressions:

  • California Miner - static value
  • ${env.hostname} - environment property
Via API

PHP - 图32

  1. $this->client = new Client([
  2. "url" => "http://localhost:8086",
  3. "token" => "my-token",
  4. "bucket" => "my-bucket",
  5. "precision" => WritePrecision::NS,
  6. "org" => "my-org",
  7. "tags" => ['id' => '132-987-655',
  8. 'hostname' => '${env.Hostname}']
  9. ]);
  10. $writeApi = $this->client->createWriteApi(null, ['data_center' => '${env.data_center}']);
  11. $writeApi->pointSettings->addDefaultTag('customer', 'California Miner');
  12. $point = Point::measurement('h2o')
  13. ->addTag('location', 'europe')
  14. ->addField('level', 2);
  15. $this->writeApi->write($point);

Advanced Usage

PHP - 图33

Check the server status

PHP - 图34

Server availability can be checked using the $client->ping(); method. That is equivalent of the influx ping.

InfluxDB 1.8 API compatibility

PHP - 图35

InfluxDB 1.8.0 introduced forward compatibility APIs for InfluxDB 2.x. This allow you to easily move from InfluxDB 1.x to InfluxDB 2.x Cloud or open source.

The following forward compatible APIs are available:

APIEndpointDescription
QueryApi.php/api/v2/queryQuery data in InfluxDB 1.8.0+ using the InfluxDB 2.x API and Flux (endpoint should be enabled by flux-enabled option)
WriteApi.php/api/v2/writeWrite data to InfluxDB 1.8.0+ using the InfluxDB 2.x API
HealthApi.php/healthCheck the health of your InfluxDB instance

For detail info see InfluxDB 1.8 example.

InfluxDB 2.x management API

PHP - 图36

InfluxDB 2.x API client is generated using influxdb-clients-apigen. Sources are in InfluxDB2\Service\ and InfluxDB2\Model\ packages.

The following example shows how to use OrganizationService and BucketService to create a new bucket.

  1. require __DIR__ . '/../vendor/autoload.php';
  2. use InfluxDB2\Client;
  3. use InfluxDB2\Model\BucketRetentionRules;
  4. use InfluxDB2\Model\Organization;
  5. use InfluxDB2\Model\PostBucketRequest;
  6. use InfluxDB2\Service\BucketsService;
  7. use InfluxDB2\Service\OrganizationsService;
  8. $organization = 'my-org';
  9. $bucket = 'my-bucket';
  10. $token = 'my-token';
  11. $client = new Client([
  12. "url" => "http://localhost:8086",
  13. "token" => $token,
  14. "bucket" => $bucket,
  15. "org" => $organization,
  16. "precision" => InfluxDB2\Model\WritePrecision::S
  17. ]);
  18. function findMyOrg($client): ?Organization
  19. {
  20. /** @var OrganizationsService $orgService */
  21. $orgService = $client->createService(OrganizationsService::class);
  22. $orgs = $orgService->getOrgs()->getOrgs();
  23. foreach ($orgs as $org) {
  24. if ($org->getName() == $client->options["org"]) {
  25. return $org;
  26. }
  27. }
  28. return null;
  29. }
  30. $bucketsService = $client->createService(BucketsService::class);
  31. $rule = new BucketRetentionRules();
  32. $rule->setEverySeconds(3600);
  33. $bucketName = "example-bucket-" . microtime();
  34. $bucketRequest = new PostBucketRequest();
  35. $bucketRequest->setName($bucketName)
  36. ->setRetentionRules([$rule])
  37. ->setOrgId(findMyOrg($client)->getId());
  38. //create bucket
  39. $respBucket = $bucketsService->postBuckets($bucketRequest);
  40. print $respBucket;
  41. $client->close();

Writing via UDP

PHP - 图37

Sending via UDP will be useful in cases when the execution time is critical to avoid potential delays (even timeouts) in sending metrics to the InfluxDB while are problems with the database or network connectivity.
As is known, sending via UDP occurs without waiting for a response, unlike TCP (HTTP).

UDP Writer Requirements:

  1. Installed ext-sockets
  2. Since Influxdb 2.0+ does not support UDP protocol natively you need to install and configure Telegraf plugin: https://docs.influxdata.com/telegraf/v1.16/plugins/#socket_listener
  3. Extra config option passed to client: udpPort. Optionally you can specify udpHost, otherwise udpHost will parsed from url option
  4. Extra config option passed to client: ipVersion. Optionally you can specify the ip version, defaults to IPv4
  1. $client = new InfluxDB2\Client(["url" => "http://localhost:8086", "token" => "my-token",
  2. "bucket" => "my-bucket",
  3. "org" => "my-org",
  4. "precision" => InfluxDB2\Model\WritePrecision::NS,
  5. "udpPort" => 8094,
  6. "ipVersion" => 6,
  7. ]);
  8. $writer = $client->createUdpWriter();
  9. $writer->write('h2o,location=west value=33i 15');
  10. $writer->close();

Delete data

PHP - 图38

The DefaultService.php supports deletes points from an InfluxDB bucket.

  1. <?php
  2. /**
  3. * Shows how to delete data from InfluxDB by client
  4. */
  5. use InfluxDB2\Client;
  6. use InfluxDB2\Model\DeletePredicateRequest;
  7. use InfluxDB2\Service\DeleteService;
  8. $url = 'http://localhost:8086';
  9. $token = 'my-token';
  10. $org = 'my-org';
  11. $bucket = 'my-bucket';
  12. $client = new Client([
  13. "url" => $url,
  14. "token" => $token,
  15. "bucket" => $bucket,
  16. "org" => $org,
  17. "precision" => InfluxDB2\Model\WritePrecision::S
  18. ]);
  19. //
  20. // Delete data by measurement and tag value
  21. //
  22. /** @var DeleteService $service */
  23. $service = $client->createService(DeleteService::class);
  24. $predicate = new DeletePredicateRequest();
  25. $predicate->setStart(DateTime::createFromFormat('Y', '2020'));
  26. $predicate->setStop(new DateTime());
  27. $predicate->setPredicate("_measurement=\"mem\" AND host=\"host1\"");
  28. $service->postDelete($predicate, null, $org, $bucket);
  29. $client->close();

For more details see DeleteDataExample.php.

Proxy and redirects

PHP - 图39

You can configure InfluxDB PHP client behind a proxy in two ways:

1. Using environment variable

PHP - 图40

Set environment variable HTTP_PROXY or HTTPS_PROXY based on the scheme of your server url. For more info see Guzzle docs - environment Variables.

2. Configure client to use proxy via Options

PHP - 图41

You can pass a proxy configuration when creating the client:

  1. $client = new InfluxDB2\Client([
  2. "url" => "http://localhost:8086",
  3. "token" => "my-token",
  4. "bucket" => "my-bucket",
  5. "org" => "my-org",
  6. "proxy" => "http://192.168.16.1:10",
  7. ]);

For more info see Guzzle docs - proxy.

Redirects

PHP - 图42

Client automatically follows HTTP redirects. You can configure redirects behaviour by a allow_redirects configuration:

  1. $client = new InfluxDB2\Client([
  2. "url" => "http://localhost:8086",
  3. "token" => "my-token",
  4. "bucket" => "my-bucket",
  5. "org" => "my-org",
  6. "allow_redirects" => false,
  7. ]);

For more info see Redirect Plugin docs - allow_redirects

Local tests

PHP - 图43

Run once to install dependencies:

  1. make deps

Run unit & intergration tests:

  1. make test

Contributing

PHP - 图44

Bug reports and pull requests are welcome on GitHub at https://github.com/influxdata/influxdb-client-php.

License

PHP - 图45

The gem is available as open source under the terms of the MIT License.