Skip to content

Configuration

Daniel Carbone edited this page Nov 6, 2026 · 3 revisions

Configuration

DCarbone\PHPConsulAPI\Config mirrors the Go client's api.Config. Every constructor parameter is optional and has a matching getter and setter (getAddress() / setAddress(), and so on). Where behavior differs from Go, it is listed in Differences from Go.

use DCarbone\PHPConsulAPI\Config;
use DCarbone\PHPConsulAPI\Consul;

$consul = new Consul(config: new Config(
    Address: 'consul.example.com:8501',
    Scheme: 'https',
    Datacenter: 'dc1',
    Token: 'my-acl-token',
    CAFile: '/etc/consul/ca.pem',
    WaitTime: '5m',
));

Parameters

Parameter Type Default / Env var Description
Address string CONSUL_HTTP_ADDR, else localhost:8500 host:port, or a http://, https:// or unix:// URL (see below)
Scheme bool|string CONSUL_HTTP_SSL (true → https), else http http/https; true/'1' → https, false/'0' → http
PathPrefix string '' Prefix prepended to every request path (e.g. behind a reverse proxy)
Datacenter string '' (agent's datacenter) Default datacenter, sent as ?dc=
Namespace string CONSUL_NAMESPACE Default namespace, sent as ?ns= (Enterprise)
Partition string CONSUL_PARTITION Default admin partition, sent as ?partition= (Enterprise)
HttpAuth null|string|HttpAuth CONSUL_HTTP_AUTH HTTP basic auth, user:pass or new HttpAuth(username: ..., password: ...)
WaitTime duration none Default max wait for blocking queries
Token string CONSUL_HTTP_TOKEN ACL token, sent as X-Consul-Token
TokenFile string CONSUL_HTTP_TOKEN_FILE File containing the ACL token
CAFile string CONSUL_CACERT CA bundle used to verify the server certificate
CAPath string CONSUL_CAPATH Directory of CA certificates (OpenSSL hash-named, as for c_rehash)
CertFile string CONSUL_CLIENT_CERT Client certificate for mTLS (requires KeyFile)
KeyFile string CONSUL_CLIENT_KEY Client key for mTLS (requires CertFile)
TLSServerName string CONSUL_TLS_SERVER_NAME SNI server name; stored and exported, but not applied (see TLS)
InsecureSkipVerify null|bool CONSUL_HTTP_SSL_VERIFY (false → skip), else false Disable TLS certificate verification
HttpClient GuzzleHttp\ClientInterface new GuzzleHttp\Client() HTTP client used for all requests
JSONEncodeOpts int JSON_UNESCAPED_SLASHES Flags passed to json_encode
JSONDecodeMaxDepth int 512 Max depth passed to json_decode
JSONDecodeOpts int 0 Flags passed to json_decode (JSON_BIGINT_AS_STRING is always added)

"duration" means any value accepted by Time::Duration(): a Go duration string ('30s'), an int of nanoseconds, a \DateInterval, or a DCarbone\Go\Time\Duration. See Durations and Time.

Passing CertFile without KeyFile (or the reverse) throws \InvalidArgumentException.

Environment variables

When a parameter is not given, Config reads the same environment variables as the Consul CLI and Go client:

Variable Parameter
CONSUL_HTTP_ADDR Address
CONSUL_HTTP_TOKEN Token
CONSUL_HTTP_TOKEN_FILE TokenFile
CONSUL_HTTP_AUTH HttpAuth
CONSUL_HTTP_SSL Scheme
CONSUL_HTTP_SSL_VERIFY InsecureSkipVerify (inverted)
CONSUL_CACERT CAFile
CONSUL_CAPATH CAPath
CONSUL_CLIENT_CERT CertFile
CONSUL_CLIENT_KEY KeyFile
CONSUL_TLS_SERVER_NAME TLSServerName
CONSUL_NAMESPACE Namespace
CONSUL_PARTITION Partition

Env var names are also available as constants on Consul (e.g. Consul::HTTPAddrEnvName).

Empty env vars are treated as unset. CONSUL_HTTP_SSL and CONSUL_HTTP_SSL_VERIFY are parsed exactly like Go's strconv.ParseBool: 1, t, T, TRUE, true, True are true; 0, f, F, FALSE, false, False are false. As in Go, an unparseable CONSUL_HTTP_SSL means http, and an unparseable CONSUL_HTTP_SSL_VERIFY disables verification.

$config->generateEnv() returns the CONSUL_*=value list for a config, equivalent to Go's Config.GenerateEnv().

How Consul merges config

new Consul(config: $config) calls Config::merge($config), which is the equivalent of Go's api.NewClient. The config you pass is not modified; a merged copy is used.

  • Empty Address, Scheme, Namespace, Partition, CAFile, CAPath, CertFile, KeyFile and TLSServerName are filled from the default (environment-derived) config. Datacenter, HttpAuth and WaitTime are not.
  • InsecureSkipVerify is OR'd with the default. As with the Go client, passing InsecureSkipVerify: false does not re-enable verification if CONSUL_HTTP_SSL_VERIFY=false is set in the environment.

Address formats

Address Result
consul.local:8500 Used as-is with Scheme
http://consul.local:8500 Scheme prefix stripped; does not downgrade an explicit https Scheme
https://consul.local:8501 Scheme becomes https
unix:///var/run/consul.sock Requests are sent over the unix socket (requires ext-curl)
https://proxy.local/consul Address becomes proxy.local, PathPrefix becomes /consul

Any other scheme throws \InvalidArgumentException.

Token precedence

Matching Go, the ACL token is resolved in this order:

  1. An explicit TokenFile (one that differs from CONSUL_HTTP_TOKEN_FILE).
  2. An explicit Token (one that differs from CONSUL_HTTP_TOKEN).
  3. CONSUL_HTTP_TOKEN_FILE.
  4. CONSUL_HTTP_TOKEN.

Token files are read when the Consul instance is created and trimmed of whitespace; an empty file is ignored. An unreadable file throws \RuntimeException.

Authentication

ACL token

Set Token, or TokenFile to read it from disk. See Token precedence.

The token can be overridden per request with QueryOptions(Token: ...) / WriteOptions(Token: ...).

HTTP basic auth

If Consul is behind a proxy that requires basic auth:

use DCarbone\PHPConsulAPI\HttpAuth;

new Config(HttpAuth: 'user:pass');
new Config(HttpAuth: new HttpAuth(username: 'user', password: 'pass'));

The credentials are sent on every request.

TLS

  • Server certificates are verified by default, using the system CA bundle.
  • CAFile replaces the system bundle with your own CA. If CAFile is empty, CAPath is used instead.
  • InsecureSkipVerify: true (or CONSUL_HTTP_SSL_VERIFY=false) disables verification entirely, even if CAFile is set.
  • CertFile + KeyFile present a client certificate (for verify_incoming agents).
  • TLSServerName is stored and exported by generateEnv(), but is not applied to requests: Guzzle has no SNI override. Use an Address whose host matches the server certificate.
$config = new Config(
    Address: 'consul.service:8501',
    Scheme: 'https',
    CAFile: '/etc/consul/ca.pem',
    CertFile: '/etc/consul/client.pem',
    KeyFile: '/etc/consul/client-key.pem',
);

Before the next release, verification was disabled unless InsecureSkipVerify was true. See Upgrading.

Custom HTTP client

Any GuzzleHttp\ClientInterface can be used. This is how to configure proxies, connection timeouts, retries, logging middleware, and so on:

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;

$stack = HandlerStack::create();
$stack->push(Middleware::log($logger, new \GuzzleHttp\MessageFormatter()));

$config = new Config(HttpClient: new Client([
    'handler'         => $stack,
    'connect_timeout' => 2,
    'proxy'           => 'http://proxy.internal:3128',
]));

The library always sends http_errors => false and decode_content => false, and sets verify, cert, ssl_key, auth, and timeout per request from Config and the request options. Don't rely on setting those on the client.

A per-request timeout is set with QueryOptions(Timeout: '10s') / WriteOptions(Timeout: '10s'). See Query and Write Options.

JSON options

JSONEncodeOpts, JSONDecodeMaxDepth, and JSONDecodeOpts control how request and response bodies are encoded and decoded. Responses are always decoded with JSON_BIGINT_AS_STRING so that uint64 values are not truncated. See Big Integers.

Default wait time

WaitTime sets a default ?wait= on every request. Consul only uses it for blocking queries (requests that also carry a WaitIndex or WaitHash). It can be overridden per request with QueryOptions(WaitTime: ...).

Clone this wiki locally