Search by

iliaal / php_clickhouse

iliaa

Native PHP extension for ClickHouse using the official ClickHouse/clickhouse-c client. Connects over the native TCP protocol with LZ4 / ZSTD compression and optional TLS.

Package info

github.com/iliaal/php_clickhouse

Language:C

Type:php-ext

Ext name:ext-clickhouse

pkg:composer/iliaal/php_clickhouse

Statistics

Installs: 146

Dependents: 0

Suggesters: 0

Stars: 18

0.15.1 2026-11-22 00:59 UTC

README

Tests Version License: PHP-3.01 Follow @iliaa

php_clickhouse: native binary protocol vs HTTP

Native PHP extension for ClickHouse, built in C on the official ClickHouse/clickhouse-c client. Speaks the native binary TCP protocol with LZ4 / ZSTD compression and optional TLS, picking up where SeasX/SeasClick left off in 2020. 1.6–4.1x faster than a pure-PHP HTTP client in the measured workloads below, with modern types (Date32, Time64, Decimal128, LowCardinality, Map, JSON), multi-endpoint failover, and structured exceptions.

📖 Documentation

The full guide lives at iliaal.github.io/php_clickhouse. It covers every supported type (what insert() accepts and what select() returns), fetch_mode flags, CSV/TSV streaming, placeholders, settings, observability, and the complete method list. This README is the quick start.

Why this fork?

SeasX/SeasClick was the standard native PHP ClickHouse extension until it stopped accepting PRs in 2020; several PRs there have been pending for years. This fork:

  • Renames the extension to php_clickhouse (module clickhouse, classes ClickHouse / ClickHouseException)
  • Uses the official ClickHouse/clickhouse-c protocol implementation with C transport, TLS, and PHP bindings
  • Adds Date32 / Time / Time64 / DateTime64 / Int128 / UInt128 / Decimal128 / LowCardinality / Map / JSON column types, multi-endpoint failover, ZSTD compression, query_id propagation, and TLS
  • Ships an updated test suite, CI, PIE-based packaging, and benchmarks

The original SeasClick and SeasClickException class names continue to work as deprecated aliases. Method signatures, return types, and class properties are declared with PHP types via a stub-driven arginfo workflow, so reflection, IDE completion, and static analyzers see the typed surface.

🚀 Install

Via PIE (the PHP Foundation's PECL successor):

pie install iliaal/php_clickhouse

With TLS support:

pie install iliaal/php_clickhouse --enable-clickhouse-openssl

Bare php:X.Y-cli Docker images lack /usr/bin/unzip, which composer needs to extract PIE's prebuilt .so zip. Run apt-get install -y unzip before pie install, otherwise composer falls back to PHP's ZipArchive and PIE fails with ExtensionBinaryNotFound. Host installs that already have unzip are fine.

Building from source:

git clone https://github.com/iliaal/php_clickhouse.git
cd php_clickhouse
phpize
./configure  # default build; no OpenSSL development headers needed
# For TLS, replace the configure command above with:
# ./configure --enable-clickhouse-openssl
# Requires OpenSSL development headers: libssl-dev on Debian/Ubuntu,
# openssl-devel on RHEL/Fedora, or openssl-dev on Alpine.
make && sudo make install

Add extension=clickhouse.so to your php.ini. Source builds need a C11 compiler: GCC or Clang on Unix, or the C11-capable MSVC toolset matching your Windows PHP build. The extension does not require a C++ compiler, Abseil, or a C++ runtime. LZ4 1.11.1 and ZSTD 1.5.7 are vendored under lib/compression/; the C client includes the native protocol's CityHash implementation.

TLS builds link directly to OpenSSL's libssl and libcrypto. You do not need to enable PHP's OpenSSL extension.

The bundled C client is pinned to 084498e63a8e814d8f8ab9a32b923d7d6c3c7d9f, with documented compatibility patches. The PHP adapter retains the previous client's protocol revision gates instead of imposing the C library's default ClickHouse 23.3 minimum. Individual types and SQL features still require a server that supports them.

Platforms

Platform Status Notes
Linux NTS primary PHP 7.4 through 8.6, CI matrix
Linux ZTS supported PHP 7.4 through 8.6, full CI matrix; PIE source builds
Windows (NTS, TS) supported PHP 8.3 through 8.6, x86 / x64 release matrix with offline load tests; pre-built .dll assets
macOS arm64 NTS release build lane PHP 8.4 and 8.5; no ClickHouse runtime test

Per-Client state lives on the zend_object itself (custom create_object / free_obj handlers). Shared ZTS builds also refresh Zend's thread-local TSRM cache during request initialization; object-local state alone is not enough. The Linux PHP 8.4 ZTS lane checks this lifecycle with eight worker-thread requests in the embed SAPI (see the threaded regression).

Test server

For development and integration tests, run the official ClickHouse server image:

docker run -d --name clickhouse-test \
    --ulimit nofile=262144:262144 \
    -p 9000:9000 -p 8123:8123 -p 9440:9440 \
    -e CLICKHOUSE_USER=test \
    -e CLICKHOUSE_PASSWORD=test \
    -e CLICKHOUSE_DB=test \
    clickhouse/clickhouse-server:latest

Stop and clean up: docker rm -f clickhouse-test.

🛠️ Quick example

<?php
$ch = new ClickHouse([
    "host"        => "127.0.0.1",
    "port"        => 9000,
    "database"    => "test",
    "user"        => "test",
    "passwd"      => "test",
    "compression" => "lz4",   // or "zstd" / true / false
]);

$ch->execute("CREATE TABLE IF NOT EXISTS events (
    id UInt32, ts DateTime64(3), tag LowCardinality(String)
) ENGINE = Memory");

$ch->insert("events", ["id", "ts", "tag"], [
    [1, time(), "alpha"],
    [2, time(), "beta"],
]);

foreach ($ch->select("SELECT id, ts, tag FROM events ORDER BY id",
                     [], ClickHouse::DATE_AS_STRINGS) as $row) {
    print_r($row);
}

🧭 API surface

Area Methods
Reading select, selectWithExternalData, selectStream, selectStreamCallback, selectStatement, selectToStream
Writing insert, insertAssoc, insertFromStream, writeStart, write, writeEnd
Result wrapper (ClickHouseStatement) fetchOne, fetchKeyPair, fetchColumn, toArray, statistics (+ Iterator / ArrayAccess / JsonSerializable)
Config & observability setSettings, setSetting, setDatabase, setProgressCallback, setProfileCallback, setVerbose, getStatistics, enableLogQueries, getLogQueries, resetConnection
DDL & introspection execute, ping, isExists, showDatabases, showTables, showCreateTable, getServerVersion, getServerUptime, getServerInfo, getCurrentEndpoint, databaseSize, tablesSize, tableSize, partitions, truncateTable, dropPartition
Flag Value Effect
FETCH_ONE 1 first cell of the first row, as a scalar
FETCH_KEY_PAIR 2 column 0 → column 1 map
DATE_AS_STRINGS 4 dates / datetimes as formatted strings
FETCH_COLUMN 8 flat list of column 0
JSON_AS_ARRAY 16 JSON cells decode to assoc arrays
JSON_AS_OBJECT 32 JSON cells decode to stdClass
UUID_WITH_DASHES 64 hyphenated UUIDs
FIXEDSTRING_BINARY 128 full N-byte FixedString, trailing NULs kept
MAP_AS_PAIRS 256 Map as ordered [key, value] pairs

Shape flags (FETCH_ONE / FETCH_KEY_PAIR / FETCH_COLUMN) are ignored on selectStatement / selectStream / selectStreamCallback; only value flags apply there. See the documentation site for full signatures and streaming formats.

selectStream() receives and buffers the native result before returning its iterator, then converts rows to PHP values as you iterate. Use selectStreamCallback() to process rows without retaining the whole result.

TLS ("ssl" => true, built with --enable-clickhouse-openssl) verifies the server certificate by default. CA files given in ssl_ca_files are added to the system trust store, not used instead of it; set "ssl_use_default_ca" => false as well to trust only your own CA.

The passwd key also accepts the password alias. Returning false from a selectStreamCallback() callback stops the stream cleanly.

📊 Benchmarks

PHP 8.4.22-dev NTS release build / ClickHouse 26.9.13.15 / localhost loopback / Memory table (no disk).

Compared against smi2/phpClickHouse, the most popular pure-PHP HTTP client. Each cell is the median of eight runs and measures one bulk insert plus selectCount queries, in seconds. Setup, reset, and warm-up are untimed; client order rotates between runs.

This is native binary TCP on port 9000 against JSON over HTTP on port 8123, so it measures the protocol as much as the library. HTTP compression is left at the client's default (off) while two of the extension columns are compressed; a gzip-enabled HTTP column is tracked in bench/README.md.

dataCount × selectCount × limit phpClickHouse (HTTP) php_clickhouse (uncompressed) php_clickhouse (LZ4) php_clickhouse (ZSTD)
10000 × 1 × 5000 0.147 0.076 0.090 0.037
10000 × 100 × 5000 4.637 1.313 1.322 1.287
10000 × 100 × 10000 8.344 2.154 2.153 2.057
1000 × 200 × 500 2.270 1.036 1.094 1.153
1000 × 500 × 1000 7.712 3.025 3.219 3.180

The server's default asynchronous inserts add batching delays to short workloads. Recreating tables can change their queue assignment and the observed delay; retain table identities when comparing two extension builds. See bench/ and set BENCH_REPETITIONS=8 to reproduce this sample count.

🔗 Native PHP extensions

Companion native PHP extensions:

  • php_excel: native Excel I/O via LibXL. 7-10× faster than PhpSpreadsheet, full XLS/XLSX with formulas, formatting, and styling.
  • mdparser: native CommonMark + GFM markdown parser via md4c. 15-30× faster than pure-PHP libraries.
  • pdo_duckdb: PDO driver for DuckDB, analytical SQL in your PHP stack.
  • fastjson: drop-in faster ext/json, backed by yyjson. 6× encode, 2.7× decode, 5× validate.
  • phpser: decoder-optimized binary serializer for cache workloads. Faster than igbinary on packed numerics and DTO batches.
  • fast_uuid: high-throughput UUID generation (v1/v4/v7), batched CSPRNG and SIMD hex formatter, ramsey-compatible API.
  • fastchart: native chart-rendering extension. 38 chart types behind one fluent OO API, SVG-canonical with PNG/JPG/WebP and optional PDF output.
  • statgrab: system statistics (CPU, memory, disk, network) via libstatgrab, no parsing /proc by hand.
  • phonetic: native phonetic name matching (Double Metaphone, Beider-Morse, Daitch-Mokotoff, NYSIIS, Match Rating), the encoders PHP core lacks.

📚 Read more

The launch post covers the fork rationale and benchmark methodology: php_clickhouse: A Native ClickHouse Client for PHP, Picking Up Where SeasClick Left Off.

License

The PHP-side wrapper is licensed under PHP-3.01.

The vendored client library at lib/clickhouse-c/ is ClickHouse/clickhouse-c, licensed under the Apache License 2.0.

The vendored LZ4 and ZSTD compression sources retain their BSD license notices. Their versions and source provenance are recorded in lib/compression/UPSTREAM.md.

The C client's CityHash implementation retains the Google MIT license notice.

Credits

php_clickhouse started as a fork of SeasX/SeasClick by SeasX Group (ahhhh.wang@gmail.com). The original PR-4 work to add fetch modes landed in 2019 and the upstream maintainer hasn't accepted external PRs since. Independent re-vendoring, port to clickhouse-cpp v2.6.2, new types, TLS, and packaging are by Ilia Alshanetsky ilia@ilia.ws.

Contributing

See CONTRIBUTING.md. Security issues: SECURITY.md.

Follow @iliaa on X • Blog • If this sped up your stack, ⭐ star it!