PHP Integration

Integrate error tracking into your PHP applications

Laravel Integration

1. Create Error Logger Class

<?php
// app/Services/ErrorLogService.php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class ErrorLogService
{
    private $apiKey;
    private $securityKey;
    private $webhookUrl;

    public function __construct()
    {
        $this->apiKey = env('ERROR_LOG_API_KEY', 'YOUR_API_KEY');
        $this->securityKey = env('ERROR_LOG_SECURITY_KEY', 'YOUR_SECURITY_KEY');
        $this->webhookUrl = "https://your-domain.com/api/ingest/{$this->apiKey}";
    }

    public function logError(\Throwable $exception, array $context = [])
    {
        try {
            Http::withHeaders([
                'X-Security-Key' => $this->securityKey,
            ])->post($this->webhookUrl, [
                'message' => $exception->getMessage(),
                'stackTrace' => $exception->getTraceAsString(),
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
                'context' => $context,
            ]);
        } catch (\Exception $e) {
            // Silently fail
            \Log::error('Failed to log error: ' . $e->getMessage());
        }
    }
}

2. Register in Handler

<?php
// app/Exceptions/Handler.php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use App\Services\ErrorLogService;
use Throwable;

class Handler extends ExceptionHandler
{
    public function report(Throwable $exception)
    {
        if ($this->shouldReport($exception)) {
            $errorLogger = app(ErrorLogService::class);
            $errorLogger->logError($exception, [
                'url' => request()->fullUrl(),
                'method' => request()->method(),
                'ip' => request()->ip(),
            ]);
        }

        parent::report($exception);
    }
}

3. Add to .env

ERROR_LOG_API_KEY=your_api_key_here
ERROR_LOG_SECURITY_KEY=your_security_key_here

Pure PHP Integration

<?php
// error_logger.php

function logError($exception, $context = []) {
    $apiKey = getenv('ERROR_LOG_API_KEY') ?: 'YOUR_API_KEY';
    $securityKey = getenv('ERROR_LOG_SECURITY_KEY') ?: 'YOUR_SECURITY_KEY';
    $webhookUrl = "https://your-domain.com/api/ingest/$apiKey";

    $payload = json_encode([
        'message' => $exception->getMessage(),
        'stackTrace' => $exception->getTraceAsString(),
        'file' => $exception->getFile(),
        'line' => $exception->getLine(),
        'context' => $context,
    ]);

    $ch = curl_init($webhookUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        "X-Security-Key: $securityKey",
    ]);
    
    curl_exec($ch);
    curl_close($ch);
}

// Set global error handler
set_exception_handler(function($exception) {
    logError($exception, [
        'url' => $_SERVER['REQUEST_URI'] ?? '',
        'method' => $_SERVER['REQUEST_METHOD'] ?? '',
    ]);
    
    // Display user-friendly error
    http_response_code(500);
    echo "An error occurred. Please try again later.";
});

// Usage in your code:
try {
    // Your code
} catch (Exception $e) {
    logError($e, ['action' => 'user_registration']);
    // Handle error
}

WordPress Integration

<?php
// wp-content/mu-plugins/error-logger.php

add_action('wp_loaded', function() {
    set_exception_handler(function($exception) {
        $apiKey = get_option('error_log_api_key');
        $securityKey = get_option('error_log_security_key');
        
        if (!$apiKey || !$securityKey) {
            return;
        }

        wp_remote_post("https://your-domain.com/api/ingest/$apiKey", [
            'headers' => [
                'X-Security-Key' => $securityKey,
            ],
            'body' => json_encode([
                'message' => $exception->getMessage(),
                'stackTrace' => $exception->getTraceAsString(),
            ]),
        ]);
    });
});

Tip

Laravel makes integration easiest with built-in HTTP client and exception handling!