- PHP - 图1influxdb-client-php
- 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
- PHP - 图12Installation
- PHP - 图14Usage
- PHP - 图33Advanced Usage
- PHP - 图43Local tests
- PHP - 图44Contributing
- PHP - 图45License
- 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
- Custom HTTP client
- Install dependencies via composer
- Configure cURL client
- Initialize InfluxDB client
- 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
-
- Using environment variable
-
- Configure client to use proxy via Options
-
- Redirects
- Local tests
- Contributing
- License
PHP - 图1influxdb-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+ (see details). For connecting to InfluxDB 1.7 or earlier instances, use the influxdb-php client library.
- Installation
- Install the library
- Usage
- Creating a client
- Querying data
- Writing data
- Default Tags
- Advanced Usage
- Check the server status
- InfluxDB 1.8 API compatibility
- InfluxDB 2.x management API
- Writing via UDP
- Delete data
- Proxy and redirects
- Contributing
- License
PHP - 图11Documentation
This section contains links to the client library documentation.
PHP - 图12Installation
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.
PHP - 图13Install the library
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
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
| 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. |
⚠️ 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. | ⚠️ required Guzzle HTTP client |
int | 10 |
| proxy | specify an HTTP proxy, or an array to specify different proxies for different protocols. | ⚠️ required Guzzle HTTP client |
string | none |
PHP - 图17Custom HTTP client
The following code shows how to use and configure cURL HTTP client:
PHP - 图18Install dependencies via composer
1. composer require influxdata/influxdb-client-php nyholm/psr7 php-http/curl-client
PHP - 图19Configure cURL client
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. );
PHP - 图20Initialize InfluxDB client
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. ]);
PHP - 图21Queries
The result retrieved by QueryApi could be formatted as a:
- Raw query response
- Flux data structure: FluxTable, FluxColumn and FluxRecord
- Stream of FluxRecord
PHP - 图22Query 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. ]);
10. $this->queryApi = $this->client->createQueryApi();
12. $result = $this->queryApi->queryRaw(
13. 'from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()');
PHP - 图23Synchronous 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. ]);
10. $this->queryApi = $this->client->createQueryApi();
12. $result = $this->queryApi->query(
13. '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 - 图24Query 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. ]);
10. $this->queryApi = $this->client->createQueryApi();
12. $parser = $this->queryApi->queryStream(
13. 'from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()');
15. foreach ($parser->each() as $record)
16. {
17. ...
18. }
PHP - 图25Parameterized 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';
4. use InfluxDB2\Client;
5. use InfluxDB2\Model\Query;
6. use InfluxDB2\Point;
7. use InfluxDB2\WriteType as WriteType;
9. $url = "https://us-west-2-1.aws.cloud2.influxdata.com";
10. $organization = 'my-org';
11. $bucket = 'my-bucket';
12. $token = 'my-token';
14. $client = new Client([
15. "url" => $url,
16. "token" => $token,
17. "bucket" => $bucket,
18. "org" => $organization,
19. "precision" => InfluxDB2\Model\WritePrecision::NS,
20. "debug" => false
21. ]);
23. $writeApi = $client->createWriteApi(["writeType" => WriteType::SYNCHRONOUS]);
24. $queryApi = $client->createQueryApi();
26. $today = new DateTime("now");
27. $yesterday = $today->sub(new DateInterval("P1D"));
29. $p = new Point("temperature");
30. $p->addTag("location", "north")->addField("value", 60)->time($yesterday);
31. $writeApi->write($p);
32. $writeApi->close();
34. //
35. // Query range start parameter using duration
36. //
37. $parameterizedQuery = "from(bucket: params.bucketParam) |> range(start: duration(v: params.startParam))";
38. $query = new Query();
39. $query->setQuery($parameterizedQuery);
40. $query->setParams(["bucketParam" => "my-bucket", "startParam" => "-1d"]);
41. $tables = $queryApi->query($query);
43. foreach ($tables as $table) {
44. foreach ($table->records as $record) {
45. var_export($record->values);
46. }
47. }
49. //
50. // Query range start parameter using DateTime
51. //
52. $parameterizedQuery = "from(bucket: params.bucketParam) |> range(start: time(v: params.startParam))";
53. $query->setParams(["bucketParam" => "my-bucket", "startParam" => $yesterday]);
54. $query->setQuery($parameterizedQuery);
55. $tables = $queryApi->query($query);
57. foreach ($tables as $table) {
58. foreach ($table->records as $record) {
59. var_export($record->values);
60. }
61. }
63. $client->close();
PHP - 图26Writing 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 - 图27Batching
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 |
| exponentialBase | the 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;
4. $client = new Client(["url" => "http://localhost:8086", "token" => "my-token",
5. "bucket" => "my-bucket",
6. "org" => "my-org",
7. "precision" => InfluxDB2\Model\WritePrecision::NS
8. ]);
10. $writeApi = $client->createWriteApi(
11. ["writeType" => WriteType::BATCHING, 'batchSize' => 1000]);
13. foreach (range(1, 10000) as $number) {
14. $writeApi->write("mem,host=aws_europe,type=batch value=1i $number");
15. }
17. // flush remaining data
18. $writeApi->close();
PHP - 图28Time 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. ]);
8. $writeApi = $client->createWriteApi();
9. $writeApi->write('h2o,location=west value=33i 15', \InfluxDB2\Model\WritePrecision::MS);
Allowed values for precision are:
WritePrecision::NSfor nanosecondWritePrecision::USfor microsecondWritePrecision::MSfor millisecondWritePrecision::Sfor second
PHP - 图29Configure 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"]);
3. $writeApi = $client->createWriteApi();
4. $writeApi->write('h2o,location=west value=33i 15', \InfluxDB2\Model\WritePrecision::MS, "production-bucket", "customer-1");
PHP - 图30Data format
The data could be written as:
stringthat is formatted as a InfluxDB’s line protocolarraywith keys: name, tags, fields and time- Data Point structure
Arrayof 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. ]);
9. $writeApi = $client->createWriteApi();
11. //data in Point structure
12. $point=InfluxDB2\Point::measurement("h2o")
13. ->addTag("location", "europe")
14. ->addField("level",2)
15. ->time(microtime(true));
17. $writeApi->write($point);
19. //data in array structure
20. $dataArray = ['name' => 'cpu',
21. 'tags' => ['host' => 'server_nl', 'region' => 'us'],
22. 'fields' => ['internal' => 5, 'external' => 6],
23. 'time' => microtime(true)];
25. $writeApi->write($dataArray);
27. //write lineprotocol
28. $writeApi->write('h2o,location=west value=33i 15');
PHP - 图31Default 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 - 图32Via 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. ]);
11. $writeApi = $this->client->createWriteApi(null, ['data_center' => '${env.data_center}']);
13. $writeApi->pointSettings->addDefaultTag('customer', 'California Miner');
15. $point = Point::measurement('h2o')
16. ->addTag('location', 'europe')
17. ->addField('level', 2);
19. $this->writeApi->write($point);
PHP - 图33Advanced Usage
PHP - 图34Check the server status
Server availability can be checked using the $client->ping(); method. That is equivalent of the influx ping.
PHP - 图35InfluxDB 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:
| API | Endpoint | Description |
|---|---|---|
| QueryApi.php | /api/v2/query | Query 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/write | Write data to InfluxDB 1.8.0+ using the InfluxDB 2.x API |
| HealthApi.php | /health | Check the health of your InfluxDB instance |
For detail info see InfluxDB 1.8 example.
PHP - 图36InfluxDB 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';
3. use InfluxDB2\Client;
4. use InfluxDB2\Model\BucketRetentionRules;
5. use InfluxDB2\Model\Organization;
6. use InfluxDB2\Model\PostBucketRequest;
7. use InfluxDB2\Service\BucketsService;
8. use InfluxDB2\Service\OrganizationsService;
10. $organization = 'my-org';
11. $bucket = 'my-bucket';
12. $token = 'my-token';
14. $client = new Client([
15. "url" => "http://localhost:8086",
16. "token" => $token,
17. "bucket" => $bucket,
18. "org" => $organization,
19. "precision" => InfluxDB2\Model\WritePrecision::S
20. ]);
22. function findMyOrg($client): ?Organization
23. {
24. /** @var OrganizationsService $orgService */
25. $orgService = $client->createService(OrganizationsService::class);
26. $orgs = $orgService->getOrgs()->getOrgs();
27. foreach ($orgs as $org) {
28. if ($org->getName() == $client->options["org"]) {
29. return $org;
30. }
31. }
32. return null;
33. }
35. $bucketsService = $client->createService(BucketsService::class);
37. $rule = new BucketRetentionRules();
38. $rule->setEverySeconds(3600);
40. $bucketName = "example-bucket-" . microtime();
41. $bucketRequest = new PostBucketRequest();
42. $bucketRequest->setName($bucketName)
43. ->setRetentionRules([$rule])
44. ->setOrgId(findMyOrg($client)->getId());
46. //create bucket
47. $respBucket = $bucketsService->postBuckets($bucketRequest);
48. print $respBucket;
50. $client->close();
PHP - 图37Writing 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:
- Installed ext-sockets
- 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>
- Extra config option passed to client: udpPort. Optionally you can specify udpHost, otherwise udpHost will parsed from url option
- 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 - 图38Delete 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;
9. $url = 'http://localhost:8086';
10. $token = 'my-token';
11. $org = 'my-org';
12. $bucket = 'my-bucket';
14. $client = new Client([
15. "url" => $url,
16. "token" => $token,
17. "bucket" => $bucket,
18. "org" => $org,
19. "precision" => InfluxDB2\Model\WritePrecision::S
20. ]);
22. //
23. // Delete data by measurement and tag value
24. //
25. /** @var DeleteService $service */
26. $service = $client->createService(DeleteService::class);
28. $predicate = new DeletePredicateRequest();
29. $predicate->setStart(DateTime::createFromFormat('Y', '2020'));
30. $predicate->setStop(new DateTime());
31. $predicate->setPredicate("_measurement=\"mem\" AND host=\"host1\"");
33. $service->postDelete($predicate, null, $org, $bucket);
35. $client->close();
For more details see DeleteDataExample.php.
PHP - 图39Proxy and redirects
You can configure InfluxDB PHP client behind a proxy in two ways:
PHP - 图401. 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 - 图412. 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 - 图42Redirects
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
PHP - 图43Local tests
Run once to install dependencies:
1. make deps
Run unit & intergration tests:
1. make test
PHP - 图44Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/influxdata/influxdb-client-php.
PHP - 图45License
The gem is available as open source under the terms of the MIT License.

