Documentation menu
PHP SDK
The Perfbase PHP SDK wraps the native extension and handles configuration, HTTP transport, and error handling. Use it directly when your framework doesn’t have a first-party integration, or when you need fine-grained control over what gets profiled.
Installation
Install the Perfbase PHP extension first. This is what does the actual profiling:
bash -c "$(curl -fsSL https://cdn.perfbase.com/install.sh)"Then install the SDK via Composer:
composer require perfbase/php-sdkQuick start
use Perfbase\SDK\Perfbase;
use Perfbase\SDK\Config;
$config = Config::fromArray([
'api_key' => 'your_api_key_here',
]);
$perfbase = new Perfbase($config);
$perfbase->startTraceSpan('my-request');
// Your application code runs here; the extension
// profiles every function call automatically.
$perfbase->stopTraceSpan('my-request');
$perfbase->submitTrace();That’s it. The trace appears in your Perfbase dashboard within seconds.
Configuration
Create a configuration with Config::fromArray() or Config::new():
$config = Config::fromArray([
'api_key' => 'sk_live_abc123',
'api_url' => 'https://ingress.perfbase.cloud',
'timeout' => 10,
'proxy' => null,
'flags' => FeatureFlags::DefaultFlags,
]);| Key | Type | Default | Description |
|---|---|---|---|
api_key | string | - | Required. Your project API key. |
api_url | string | https://ingress.perfbase.cloud | Ingestion endpoint. Must be HTTPS. |
timeout | int | 10 | HTTP request timeout in seconds. |
proxy | string|null | null | Proxy URL. Supports http, https, socks5, socks5h. |
flags | int | DefaultFlags | Bitmask controlling which subsystems to profile. See Feature flags. |
Configuration is validated at creation time. Invalid values throw PerfbaseInvalidConfigException.
Profiling spans
A span represents a unit of work you want to profile, typically one HTTP request, queue job, or CLI command.
$perfbase->startTraceSpan('web_request');
// everything between start and stop is profiled
$perfbase->stopTraceSpan('web_request');Span names must match ^[A-Za-z0-9_-]{1,64}$: letters, numbers, hyphens, and underscores, up to 64 characters. Invalid names throw PerfbaseInvalidSpanException.
Multiple concurrent spans are supported. Each span tracks its own timing independently:
$perfbase->startTraceSpan('db-migration');
$perfbase->startTraceSpan('seed-data');
runMigrations();
$perfbase->stopTraceSpan('db-migration');
seedDatabase();
$perfbase->stopTraceSpan('seed-data');
$perfbase->submitTrace();You can also pass initial attributes when starting a span:
$perfbase->startTraceSpan('api-request', [
'endpoint' => '/api/v1/users',
'method' => 'POST',
]);Custom attributes
Add metadata to the current trace with setAttribute(). Attributes are trace-level (not span-scoped) and must be string key-value pairs:
$perfbase->setAttribute('user_id', '12345');
$perfbase->setAttribute('environment', 'production');
$perfbase->setAttribute('app_version', '2.4.1');Attributes appear in the Perfbase dashboard alongside the trace, making it easy to filter and search.
Submitting traces
submitTrace() sends the profiling data to Perfbase and returns a SubmitResult:
$result = $perfbase->submitTrace();
if ($result->isSuccess()) {
// Trace submitted. Profiler state is automatically reset.
}
if ($result->isRetryable()) {
// Network error, 429, or 5xx; safe to retry later.
error_log('Perfbase: ' . $result->getMessage());
}
if ($result->isPermanentFailure()) {
// 4xx auth/validation error; check your API key and config.
error_log('Perfbase: ' . $result->getMessage());
}On success, the SDK automatically resets the profiler. On failure, the trace data is preserved so you can decide whether to retry.
The SDK does not retry automatically. This is intentional, so submissions never block your application longer than the configured timeout.
The request body is the raw Brotli-compressed MessagePack byte string returned by perfbase_get_data(), sent as application/octet-stream. The SDK adds Authorization, X-Perfbase-Version, X-Perfbase-Protocol, and, when available, X-Perfbase-Client-Created-At headers. It does not JSON-wrap or base64-encode the trace payload.
Feature flags
Feature flags control which PHP subsystems the extension profiles. Combine them with the bitwise OR operator:
use Perfbase\SDK\FeatureFlags;
$config = Config::fromArray([
'api_key' => 'sk_live_abc123',
'flags' => FeatureFlags::TrackCpuTime | FeatureFlags::TrackPdo | FeatureFlags::TrackHttp,
]);| Flag | Default | Description |
|---|---|---|
UsePreciseClock | On | Opt in to the high-resolution monotonic clock. |
TrackWallTime | On | Wall-clock time per function call. |
TrackCpuTime | Off | CPU time via getrusage(). |
TrackMemoryAllocation | Off | Heap allocation tracking via Zend Memory Manager. |
TrackArguments | On | Function argument capture. |
TrackExceptions | On | Exception throws. |
TrackFileCompilation | On | Include and require operations. |
TrackFileDefinitions | On | Class and function definitions per file. |
TrackSessions | On | Session operations. |
TrackSerialization | On | Serialization and JSON encoding operations. |
TrackRegex | On | preg_* operations. |
TrackPdo | On | PDO and mysqli queries. |
TrackMongodb | On | MongoDB operations. |
TrackElasticsearch | On | Elasticsearch operations. |
TrackCaches | On | Redis, Memcached, and cache calls. |
TrackHttp | On | cURL and outbound HTTP calls. |
TrackMail | On | Mail and SMTP operations. |
TrackFileOperations | On | File I/O (fopen, fread, fwrite, etc.). |
TrackProc | On | proc_open, exec, and shell_exec. |
TrackProcessList | On | Top running processes at trace end. |
TrackErrors | On | PHP errors, warnings, and notices. |
TrackMagicMethods | On | Magic method calls such as __call, __get, and __set. |
TrackOpcache | On | OPcache hit/miss and memory statistics when OPcache is loaded. |
DefaultFlags is the SDK-curated production default. It excludes CPU-time and memory-allocation tracking by default because those are higher-overhead, specialized signals.
AllFlags is the 0 sentinel understood by the extension. It enables every known feature except the precise clock sentinel behavior handled by the extension.
You can change flags at runtime without creating a new instance:
$perfbase->setFlags(FeatureFlags::AllFlags);Error handling
The SDK uses exceptions for configuration and setup errors, and result objects for submission outcomes.
| Exception | When |
|---|---|
PerfbaseExtensionException | The ext-perfbase extension is not loaded or is missing required functions. |
PerfbaseInvalidConfigException | A configuration value is invalid (missing API key, non-HTTPS URL, etc.). |
PerfbaseInvalidSpanException | A span name doesn’t match the allowed pattern. |
All exceptions extend PerfbaseException, so you can catch them with a single type:
use Perfbase\SDK\Exception\PerfbaseException;
try {
$perfbase = new Perfbase($config);
$perfbase->startTraceSpan('my-span');
} catch (PerfbaseException $e) {
// Extension missing, bad config, or invalid span name
error_log('Perfbase setup failed: ' . $e->getMessage());
}Submission errors are never thrown. They are returned as SubmitResult so your application is never interrupted by a profiling failure.
Checking availability
Before constructing the SDK, you can check whether the extension is loaded:
if (Perfbase::isAvailable()) {
$perfbase = new Perfbase($config);
$perfbase->startTraceSpan('request');
}This is useful for conditional profiling in environments where the extension may not be installed (e.g., local development without Docker).
Framework integrations
If you’re using Laravel, WordPress, or another supported framework, use the framework package first. Those adapters wire the SDK into the relevant framework lifecycle, then delegate transport and extension access back to this package:
The SDK is the right choice when you need manual control, or when your framework doesn’t have a first-party integration yet.