error-explorer / php-sdk
PHP SDK for Error Explorer - Capture and report errors automatically
Installs: 0
Dependents: 0
Suggesters: 0
Security: 0
Stars: 1
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/error-explorer/php-sdk
Requires
- php: >=7.4
- ext-curl: *
- ext-json: *
Requires (Dev)
- phpmd/phpmd: ^2.13
- phpstan/phpstan: ^1.0
- phpunit/phpunit: ^9.0|^10.0|^11.0
- squizlabs/php_codesniffer: ^3.7
- symfony/var-dumper: ^5.0|^6.0|^7.0
README
PHP SDK for Error Explorer - Enterprise-grade error monitoring and reporting for your PHP applications.
Installation
composer require error-explorer/php-sdk
Quick Start
Basic Setup
<?php require_once 'vendor/autoload.php'; use function ErrorExplorer\init; use function ErrorExplorer\captureException; use function ErrorExplorer\captureMessage; // Initialize Error Explorer init([ 'webhookUrl' => 'https://error-explorer.com/webhook/project-token', 'projectName' => 'my-php-app', 'environment' => 'production', ]); // Capture exceptions try { riskyOperation(); } catch (Exception $e) { captureException($e); } // Capture messages captureMessage('Something happened', 'info');
Advanced Configuration
use ErrorExplorer\ErrorExplorer; $client = ErrorExplorer::init([ // Required 'webhookUrl' => 'https://error-explorer.com/webhook/project-token', 'projectName' => 'my-php-app', // Basic config 'environment' => 'production', 'enabled' => true, 'maxBreadcrumbs' => 50, 'timeout' => 5, 'retries' => 3, 'debug' => false, 'beforeSend' => function($data) { return $data; }, // User context 'userId' => 'user123', 'userEmail' => 'user@example.com', // Rate limiting 'enableRateLimiting' => true, 'maxRequestsPerMinute' => 60, 'duplicateWindowSeconds' => 300, 'enableDeduplication' => true, // Security 'enforceHttps' => true, 'maxPayloadSizeMb' => 10.0, 'enableXssProtection' => true, 'sensitiveFields' => ['password', 'token', 'secret', 'key'], 'blockLocalUrls' => true, // Quota management 'enableQuotaManagement' => true, 'dailyLimit' => 1000, 'monthlyLimit' => 30000, 'burstLimit' => 100, // Offline queue 'enableOfflineQueue' => true, 'maxQueueSize' => 1000, 'maxItemAgeHours' => 24, 'queueBatchSize' => 10, // SDK monitoring 'enableSdkMonitoring' => true, 'enablePerformanceTracking' => true, 'slowRequestThresholdSeconds' => 5.0, 'healthCheckIntervalSeconds' => 300, // Retry management 'enableJitter' => true, 'exponentialBase' => 2.0, 'maxDelaySeconds' => 60, ]);
Core Features
Exception Handling
try { $result = performDatabaseOperation(); } catch (Exception $e) { captureException($e, [ 'operation' => 'database_query', 'user_id' => 123, 'table' => 'users' ]); throw $e; // Re-throw if needed }
Message Logging
captureMessage('User login successful', 'info', [ 'user_id' => 123, 'ip_address' => $_SERVER['REMOTE_ADDR'] ]); captureMessage('Cache miss detected', 'warning', [ 'cache_key' => 'user_profile_123', 'fallback_used' => true ]);
Breadcrumbs
use function ErrorExplorer\addBreadcrumb; // Add breadcrumbs for debugging context addBreadcrumb('User started checkout', 'user_action', 'info', [ 'cart_items' => 3, 'total_amount' => 99.99 ]); addBreadcrumb('Payment method selected', 'user_action', 'info', [ 'method' => 'credit_card' ]); addBreadcrumb('Database query executed', 'database', 'debug', [ 'query' => 'SELECT * FROM orders WHERE user_id = ?', 'duration_ms' => 45 ]);
User Context
use function ErrorExplorer\setUser; setUser([ 'id' => 123, 'email' => 'user@example.com', 'username' => 'john_doe', 'role' => 'premium', 'subscription_plan' => 'pro' ]);
Enterprise Features
Rate Limiting
Prevents spam and duplicate error reporting:
init([ 'enableRateLimiting' => true, 'maxRequestsPerMinute' => 60, // Max 60 errors per minute 'duplicateWindowSeconds' => 300, // Deduplicate within 5 minutes 'enableDeduplication' => true // Filter duplicate errors ]);
Security Validation
Protects against malicious data and ensures secure transmission:
init([ 'enforceHttps' => true, // Require HTTPS URLs 'maxPayloadSizeMb' => 10.0, // Limit payload size 'enableXssProtection' => true, // Sanitize XSS attempts 'blockLocalUrls' => true, // Block local/private URLs 'sensitiveFields' => [ // Fields to filter 'password', 'token', 'secret', 'api_key', 'auth' ] ]);
Quota Management
Manages usage limits across different time periods:
init([ 'enableQuotaManagement' => true, 'dailyLimit' => 1000, // 1000 errors per day 'monthlyLimit' => 30000, // 30k errors per month 'burstLimit' => 100 // 100 errors per minute ]);
Offline Queue
Queues errors when the service is unavailable:
init([ 'enableOfflineQueue' => true, 'maxQueueSize' => 1000, // Max items in queue 'maxItemAgeHours' => 24, // Expire items after 24h 'queueBatchSize' => 10 // Process 10 items at once ]); // Process queued errors manually use function ErrorExplorer\processOfflineQueue; $result = processOfflineQueue(); echo "Processed: {$result['processed']}, Failed: {$result['failed']}";
Performance Monitoring
Tracks SDK performance and health:
init([ 'enableSdkMonitoring' => true, 'enablePerformanceTracking' => true, 'slowRequestThresholdSeconds' => 5.0, // Flag slow requests 'healthCheckIntervalSeconds' => 300 // Health check frequency ]);
Advanced Retry Logic
Intelligent retry with exponential backoff and jitter:
init([ 'retries' => 3, // Max retry attempts 'enableJitter' => true, // Add randomization 'exponentialBase' => 2.0, // Backoff multiplier 'maxDelaySeconds' => 60 // Max delay between retries ]);
Diagnostic APIs
Health Status
use function ErrorExplorer\getHealthStatus; $health = getHealthStatus(); echo "SDK Status: " . $health['status']; echo "Success Rate: " . $health['success_rate'] . "%"; echo "Memory Usage: " . $health['memory_usage_mb'] . "MB";
Connection Test
use function ErrorExplorer\testConnection; $test = testConnection(); if ($test['success']) { echo "Connection OK ({$test['duration_ms']}ms)"; } else { echo "Connection failed: " . $test['error']; }
Security Report
use function ErrorExplorer\getSecurityReport; $report = getSecurityReport(); echo "URL Valid: " . ($report['validations']['url']['valid'] ? 'Yes' : 'No'); echo "Payload Size: " . $report['validations']['payload_size']['size_mb'] . "MB";
Advanced Usage Examples
Custom Error Context
class DatabaseManager { public function executeQuery($sql, $params = []) { $startTime = microtime(true); addBreadcrumb("Executing query: " . substr($sql, 0, 50) . "...", 'database'); try { $result = $this->pdo->prepare($sql); $result->execute($params); $duration = microtime(true) - $startTime; addBreadcrumb( "Query completed in " . round($duration * 1000, 2) . "ms", 'database', 'info', ['duration_ms' => round($duration * 1000, 2), 'rows' => $result->rowCount()] ); return $result->fetchAll(); } catch (PDOException $e) { captureException($e, [ 'query' => $sql, 'params' => $params, 'duration_ms' => round((microtime(true) - $startTime) * 1000, 2), 'database' => 'main' ]); throw $e; } } }
Before Send Hook
init([ 'beforeSend' => function($errorData) { // Filter out errors from development if ($errorData['environment'] === 'development') { return null; // Don't send } // Add additional context $errorData['context']['server_load'] = sys_getloadavg()[0]; $errorData['context']['memory_usage'] = memory_get_usage(true); // Filter sensitive data if (isset($errorData['context']['password'])) { $errorData['context']['password'] = '[FILTERED]'; } return $errorData; } ]);
Web Request Auto-Capture
// In your error handler or exception handler set_exception_handler(function($exception) { // Auto-captures $_SERVER, $_GET, $_POST data captureException($exception); }); // Manual request data captureException($exception, null, [ 'url' => $_SERVER['REQUEST_URI'], 'method' => $_SERVER['REQUEST_METHOD'], 'headers' => getallheaders(), 'body' => file_get_contents('php://input') ]);
Performance Considerations
- Asynchronous Processing: All errors are sent asynchronously
- Memory Efficient: Configurable breadcrumb limits and payload sizes
- Rate Limiting: Built-in protection against spam
- Offline Queue: Handles network outages gracefully
- Intelligent Retries: Exponential backoff with jitter
Error Handling
The SDK is designed to never interfere with your application:
init([ 'debug' => true // Enable to see SDK errors in logs ]); // The SDK will: // - Never throw exceptions from error reporting // - Log issues to error_log() when debug=true // - Gracefully degrade when services are unavailable // - Queue errors offline when needed
Environment Variables
You can configure using environment variables:
ERROR_EXPLORER_WEBHOOK_URL=https://error-explorer.com/webhook/project-token ERROR_EXPLORER_PROJECT_NAME=my-php-app ERROR_EXPLORER_ENVIRONMENT=production ERROR_EXPLORER_DEBUG=false
init([ 'webhookUrl' => $_ENV['ERROR_EXPLORER_WEBHOOK_URL'], 'projectName' => $_ENV['ERROR_EXPLORER_PROJECT_NAME'], 'environment' => $_ENV['ERROR_EXPLORER_ENVIRONMENT'] ?? 'production', 'debug' => filter_var($_ENV['ERROR_EXPLORER_DEBUG'] ?? false, FILTER_VALIDATE_BOOLEAN) ]);
Requirements
- PHP 7.4+
- ext-json
- ext-curl
- Optional: ext-pdo for database examples
Framework Integration
While this is the native PHP SDK, we also provide specialized packages:
- Laravel:
error-explorer/laravel- Service provider and middleware - Symfony:
error-explorer/symfony-bundle- Full bundle integration - WordPress:
error-explorer/wordpress- Plugin integration
License
MIT License