• Documentation
  • Installation
    • Install the library
  • Usage
    • Creating a client
      • Client Options
    • Queries
      • Query raw
      • Synchronous query
      • Query stream
    • Parameterized queries
    • Writing data
      • Batching
      • Time precision
      • Configure destination
      • Data format
      • Default Tags
        • Via API
  • Advanced Usage
    • Check the server status
    • InfluxDB 1.8 API compatibility
    • InfluxDB 2.x management API
    • Writing via UDP
    • Delete data
    • Proxy and redirects
      • 1. Using environment variable
      • 2. Configure client to use proxy via Options
    • Redirects
  • Local tests
  • Contributing
  • License

    influxdb-client-php

    This repository contains the reference PHP client for the InfluxDB 2.x.

    PHP - 图10Note: Use this client library with InfluxDB 2.x and InfluxDB 1.8+ (). For connecting to InfluxDB 1.7 or earlier instances, use the influxdb-php client library.

    This section contains links to the client library documentation.

    Installation

    The InfluxDB 2 client is bundled and hosted on https://packagist.org/.

    The client can be installed with composer.

    PHP - 图15Creating a client

    Use 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 - 图17Queries

    The result retrieved by could be formatted as a:

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

    Query raw

    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

    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

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

    Query stream

    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. }

    InfluxDB Cloud supports 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:

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

    PHP - 图22Writing data

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

    Batching

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

    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

    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

    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

    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

    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
    PHP - 图28Via API

    Advanced Usage

    PHP - 图30Check the server status

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

    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:

    InfluxDB 2.x management API

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

    Writing via UDP

    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();

    The 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 .

    Proxy and redirects

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

    1. Using environment variable

    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

    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 - .

    Redirects

    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 Guzzle docs - allow_redirects

    1. # run unit & integration tests
    2. make test

    Contributing

    Bug reports and pull requests are welcome on GitHub at .