• influxdb-client-php
    • 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
  • 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

    PHP - 图1influxdb-client-php

    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.

    PHP - 图10Note: 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 - 图11Documentation

    This section contains links to the client library documentation.

    PHP - 图12Installation

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

    PHP - 图13Install the library

    The client can be installed with composer.

    1. composer require influxdata/influxdb-client-php

    PHP - 图14Usage

    PHP - 图15Creating a client

    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. ]);

    PHP - 图16Client Options

    OptionDescriptionTypeDefault
    bucketDefault destination bucket for writesStringnone
    orgDefault organization bucket for writesStringnone
    precisionDefault precision for the unix timestamps within the body line-protocolStringnone
    verifySSLTurn on/off SSL certificate verification. Set to false to disable certificate verification.booltrue
    timeoutDescribing the number of seconds to wait while trying to connect to a server. Use 0 to wait indefinitelyint10

    PHP - 图17Queries

    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

    PHP - 图18Query 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()');

    PHP - 图19Synchronous 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 json_encode

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

    PHP - 图20Query 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. }

    PHP - 图21Parameterized 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:

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

    PHP - 图22Writing 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.

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

    PHP - 图23Batching

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

    PHP - 图24Time 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

    PHP - 图25Configure 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");

    PHP - 图26Data 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');

    PHP - 图27Default 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
    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);

    PHP - 图29Advanced Usage

    PHP - 图30Check the server status

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

    PHP - 图31InfluxDB 1.8 API compatibility

    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.

    PHP - 图32InfluxDB 2.x management API

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

    PHP - 图33Writing 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();

    PHP - 图34Delete data

    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.

    PHP - 图35Proxy and redirects

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

    PHP - 图361. 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.

    PHP - 图372. 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 - proxy.

    PHP - 图38Redirects

    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

    PHP - 图39Local tests

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

    PHP - 图40Contributing

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

    PHP - 图41License

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