PHP code example of litesoc / litesoc-php

1. Go to this page and download the library: Download litesoc/litesoc-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

litesoc / litesoc-php example snippets


use LiteSOC\LiteSOC;

// Initialize the SDK
$litesoc = new LiteSOC('your-api-key');

// Track a login failure - LiteSOC auto-enriches with GeoIP & Network Intelligence
$litesoc->track('auth.login_failed', [
    'actor_id' => 'user_123',
    'actor_email' => '[email protected]',
    'user_ip' => '192.168.1.1',  // Required for Security Intelligence
    'metadata' => ['reason' => 'invalid_password']
]);

// Flush remaining events before shutdown
$litesoc->flush();

use LiteSOC\LiteSOC;

$litesoc = new LiteSOC('your-api-key', [
    'endpoint' => 'https://...',      // Custom API endpoint
    'batching' => true,                // Enable event batching (default: true)
    'batch_size' => 10,                // Events before auto-flush (default: 10)
    'flush_interval' => 5.0,           // Seconds between auto-flushes (default: 5.0)
    'debug' => false,                  // Enable debug logging (default: false)
    'silent' => true,                  // Fail silently on errors (default: true)
    'timeout' => 5.0,                  // Request timeout in seconds (default: 5.0)
]);

// Track any event type
$litesoc->track('auth.login_failed', [
    'actor_id' => 'user_123',
    'actor_email' => '[email protected]',
    'user_ip' => '192.168.1.1'
]);

use LiteSOC\LiteSOC;

$litesoc = new LiteSOC('your-api-key');

$accepted = $litesoc->trackBatch([
    [
        'event_name'  => 'auth.login_success',
        'actor_id'    => 'user_123',
        'actor_email' => '[email protected]',
        'user_ip'     => '203.0.113.50',
        'metadata'    => ['method' => 'password'],
    ],
    [
        'event_name' => 'data.export',
        'actor_id'   => 'user_123',
        'user_ip'    => '203.0.113.50',
        'metadata'   => ['table' => 'orders', 'rows' => 500],
    ],
]);

echo "{$accepted} events accepted";

use LiteSOC\EventType;

$litesoc->track(EventType::AUTH_LOGIN_FAILED, [
    'actor_id' => 'user_123',
    'user_ip' => '192.168.1.1'
]);

use LiteSOC\SecurityEvents;

// Use predefined security event types
$litesoc->track(SecurityEvents::AUTH_LOGIN_FAILED, [
    'actor_id' => 'user_123',
    'user_ip' => '192.168.1.1'
]);

// Get all 26 standard events
$allEvents = SecurityEvents::all();

// Validate an event type
if (SecurityEvents::isValid('auth.login_failed')) {
    // Valid standard event
}

use LiteSOC\EventSeverity;

$litesoc->track('security.suspicious_activity', [
    'actor_id' => 'user_123',
    'user_ip' => '192.168.1.1',
    'severity' => EventSeverity::CRITICAL,
    'metadata' => ['reason' => 'impossible travel detected']
]);

$litesoc->track('data.export', [
    'actor_id' => 'user_123',
    'user_ip' => '192.168.1.1',
    'metadata' => [
        'file_type' => 'csv',
        'record_count' => 1000,
        'export_reason' => 'monthly_report'
    ]
]);

// Track login failures
$litesoc->trackLoginFailed('user_123', ['user_ip' => '192.168.1.1']);

// Track login successes
$litesoc->trackLoginSuccess('user_123', ['user_ip' => '192.168.1.1']);

// Track privilege escalation (critical severity)
$litesoc->trackPrivilegeEscalation('admin_user', ['user_ip' => '192.168.1.1']);

// Track sensitive data access (high severity)
$litesoc->trackSensitiveAccess('user_123', 'customer_pii_table', ['user_ip' => '192.168.1.1']);

// Track bulk deletions (high severity)
$litesoc->trackBulkDelete('admin_user', 500, ['user_ip' => '192.168.1.1']);

// Track role changes
$litesoc->trackRoleChanged('user_123', 'viewer', 'admin', ['user_ip' => '192.168.1.1']);

// Track access denied
$litesoc->trackAccessDenied('user_123', '/admin/settings', ['user_ip' => '192.168.1.1']);

use LiteSOC\Laravel\Facades\LiteSOC;

// Track events using the facade
LiteSOC::track('auth.login_failed', [
    'actor_id' => auth()->id(),
    'user_ip' => request()->ip()
]);

// Use convenience methods
LiteSOC::trackLoginSuccess(auth()->id(), [
    'actor_email' => auth()->user()->email,
    'user_ip' => request()->ip()
]);

use LiteSOC\LiteSOC;

class LoginController extends Controller
{
    public function __construct(
        private LiteSOC $litesoc
    ) {}

    public function login(Request $request)
    {
        // Attempt authentication
        if (Auth::attempt($request->only('email', 'password'))) {
            $this->litesoc->trackLoginSuccess(auth()->id(), [
                'actor_email' => auth()->user()->email,
                'user_ip' => $request->ip()
            ]);
            return redirect('/dashboard');
        }

        $this->litesoc->trackLoginFailed($request->email, [
            'user_ip' => $request->ip()
        ]);
        return back()->withErrors(['email' => 'Invalid credentials']);
    }
}

// app/Providers/EventServiceProvider.php
protected $listen = [
    \Illuminate\Auth\Events\Login::class => [
        \App\Listeners\TrackLoginSuccess::class,
    ],
    \Illuminate\Auth\Events\Failed::class => [
        \App\Listeners\TrackLoginFailed::class,
    ],
];

// app/Listeners/TrackLoginSuccess.php
use LiteSOC\Laravel\Facades\LiteSOC;
use Illuminate\Auth\Events\Login;

class TrackLoginSuccess
{
    public function handle(Login $event): void
    {
        LiteSOC::trackLoginSuccess($event->user->id, [
            'actor_email' => $event->user->email,
            'user_ip' => request()->ip()
        ]);
    }
}

// app/Listeners/TrackLoginFailed.php
use LiteSOC\Laravel\Facades\LiteSOC;
use Illuminate\Auth\Events\Failed;

class TrackLoginFailed
{
    public function handle(Failed $event): void
    {
        LiteSOC::trackLoginFailed($event->credentials['email'] ?? 'unknown', [
            'user_ip' => request()->ip()
        ]);
    }
}

// app/Http/Middleware/TrackSecurityEvents.php
namespace App\Http\Middleware;

use Closure;
use LiteSOC\Laravel\Facades\LiteSOC;

class TrackSecurityEvents
{
    public function handle($request, Closure $next)
    {
        return $next($request);
    }

    public function terminate($request, $response)
    {
        // Track access denied (403 responses)
        if ($response->status() === 403) {
            LiteSOC::trackAccessDenied(
                auth()->id() ?? 'anonymous',
                $request->path(),
                ['user_ip' => $request->ip()]
            );
        }
    }
}

// Get current queue size
$queueSize = $litesoc->getQueueSize();

// Manually flush all events
$litesoc->flush();

// Clear queue without sending
$litesoc->clearQueue();

// Graceful shutdown
$litesoc->shutdown();

use LiteSOC\LiteSOC;

$litesoc = new LiteSOC('your-api-key');

// Get all alerts
$result = $litesoc->getAlerts();
// Returns:
// [
//     'success' => true,
//     'data' => [
//         ['id' => 'alert_123', 'alert_type' => 'impossible_travel', 'severity' => 'critical', ...],
//         ['id' => 'alert_456', 'alert_type' => 'brute_force', 'severity' => 'warning', ...],
//     ],
//     'pagination' => ['total' => 42, 'limit' => 20, 'offset' => 0, 'has_more' => true],
//     'meta' => ['plan' => 'business', 'retention_days' => 90]
// ]

// Get alerts with filters
$result = $litesoc->getAlerts([
    'severity' => 'critical',         // 'critical', 'warning', 'info'
    'status' => 'active',             // 'active', 'resolved', 'safe'
    'alert_type' => 'impossible_travel',
    'limit' => 10,
    'offset' => 0,
]);

// Access alerts from the response
foreach ($result['data'] as $alert) {
    echo $alert['id'] . ': ' . $alert['title'];
}

$result = $litesoc->getAlert('alert_abc123');
// Returns:
// [
//     'success' => true,
//     'data' => [
//         'id' => 'alert_abc123',
//         'alert_type' => 'impossible_travel',
//         'severity' => 'critical',
//         'status' => 'active',
//         'title' => 'Impossible Travel Detected',
//         'description' => 'Login from New York, then Tokyo within 30 minutes',
//         'actor_id' => 'user_123',
//         'trigger_event_id' => 'evt_xyz789',
//         'created_at' => '2026-03-02T10:30:00Z',
//         'forensics' => [...],  // Network intelligence & geolocation (Pro/Enterprise)
//     ],
//     'meta' => ['plan' => 'business', 'retention_days' => 90]
// ]

$alert = $result['data'];
echo $alert['title'] . ' - ' . $alert['severity'];

// Mark an alert as resolved with resolution type and notes
$result = $litesoc->resolveAlert(
    'alert_abc123',
    'blocked_ip',                    // Resolution type: 'blocked_ip', 'false_positive', 'investigated', etc.
    'Blocked IP in firewall'         // Internal notes (optional)
);
// Returns:
// [
//     'success' => true,
//     'data' => ['id' => 'alert_abc123', 'status' => 'resolved', 'resolved_at' => '...'],
// ]

// Mark an alert as safe (false positive)
$result = $litesoc->markAlertSafe(
    'alert_abc123',
    'Expected behavior from automated testing'  // Internal notes (optional)
);
// Returns:
// [
//     'success' => true,
//     'data' => ['id' => 'alert_abc123', 'status' => 'safe'],
// ]

// Get recent events (default limit: 20)
$result = $litesoc->getEvents();
// Returns:
// [
//     'success' => true,
//     'data' => [...events],
//     'pagination' => ['total' => 100, 'limit' => 20, 'offset' => 0, 'has_more' => true],
//     'meta' => ['plan' => 'business', 'retention_days' => 90, 'redacted' => false]
// ]

// Get events with filters
$result = $litesoc->getEvents(50, [
    'event_name' => 'auth.login_failed',  // Filter by event type
    'actor_id' => 'user_123',             // Filter by actor
    'severity' => 'critical',             // 'critical', 'warning', or 'info'
    'offset' => 10,                       // Pagination offset
]);

// Access events from the response
foreach ($result['data'] as $event) {
    echo $event['event_name'] . ': ' . $event['actor']['id'];
}

$result = $litesoc->getEvent('event_xyz789');
// Returns:
// [
//     'success' => true,
//     'data' => [...event data],
//     'meta' => ['plan' => 'business', 'retention_days' => 90, 'redacted' => false]
// ]

$event = $result['data'];
echo $event['event_name'];

use LiteSOC\LiteSOC;

$litesoc = new LiteSOC('your-api-key');

// Make an API call first
$alerts = $litesoc->getAlerts();

// Get plan metadata from response headers
$planInfo = $litesoc->getPlanInfo();

if ($planInfo) {
    echo "Plan: " . $planInfo->plan;              // e.g., "business", "enterprise"
    echo "Retention: " . $planInfo->retentionDays . " days";
    echo "Cutoff: " . $planInfo->cutoffDate;       // ISO 8601 timestamp
}

// Check if plan info is available
if ($litesoc->hasPlanInfo()) {
    // Plan data has been populated
}

use LiteSOC\ResponseMetadata;

// Access properties directly (readonly)
$planInfo = $litesoc->getPlanInfo();
$plan = $planInfo->plan;                 // string|null
$days = $planInfo->retentionDays;        // int|null
$cutoff = $planInfo->cutoffDate;         // string|null

// Helper methods
$planInfo->hasPlanInfo();                // bool
$planInfo->hasRetentionInfo();           // bool
$planInfo->toArray();                    // array

use LiteSOC\Exceptions\PlanRestrictedException;

try {
    $alerts = $litesoc->getAlerts();
} catch (PlanRestrictedException $e) {
    echo "Upgrade 

use LiteSOC\LiteSOC;
use LiteSOC\Exceptions\LiteSOCException;
use LiteSOC\Exceptions\AuthenticationException;
use LiteSOC\Exceptions\RateLimitException;
use LiteSOC\Exceptions\PlanRestrictedException;

$litesoc = new LiteSOC('your-api-key', ['silent' => false]);

try {
    $alerts = $litesoc->getAlerts();
} catch (AuthenticationException $e) {
    // Invalid or missing API key (401)
    error_log('Auth failed: ' . $e->getMessage());
} catch (PlanRestrictedException $e) {
    // Feature 

$litesoc = new LiteSOC('your-api-key', ['silent' => false]);

try {
    $litesoc->track('auth.login_failed', ['actor_id' => 'user_123']);
    $litesoc->flush();
} catch (\Exception $e) {
    // Handle error
    error_log("Failed to track event: " . $e->getMessage());
}

$litesoc = new LiteSOC('your-api-key', ['debug' => true]);
// Logs will be printed to stdout

// In a controller or middleware
public function login(Request $request)
{
    // ... authentication logic ...
    
    // Queue the security event (fast, no HTTP call yet)
    $litesoc->track('auth.login_success', [
        'actor_id' => auth()->id(),
        'user_ip' => $request->ip()
    ]);
    
    // Return response to client immediately
    $response = redirect('/dashboard');
    
    // Finish the request - client receives response NOW
    if (function_exists('fastcgi_finish_request')) {
        // Send response headers and body to client
        $response->send();
        
        // Close the connection - client is done waiting
        fastcgi_finish_request();
        
        // This runs AFTER the client has received their response
        $litesoc->flush();
    }
    
    return $response;
}

// app/Http/Middleware/FlushLiteSOCEvents.php
namespace App\Http\Middleware;

use Closure;
use LiteSOC\LiteSOC;

class FlushLiteSOCEvents
{
    public function __construct(private LiteSOC $litesoc) {}

    public function handle($request, Closure $next)
    {
        return $next($request);
    }

    /**
     * Flush events after response is sent to client
     */
    public function terminate($request, $response)
    {
        // In PHP-FPM, this runs after fastcgi_finish_request()
        // The client has already received their response
        $this->litesoc->flush();
    }
}

// Register in app/Http/Kernel.php
protected $middleware = [
    // ... other middleware
    \App\Http\Middleware\FlushLiteSOCEvents::class,
];

// app/Jobs/TrackSecurityEvent.php
namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use LiteSOC\LiteSOC;

class TrackSecurityEvent implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable;

    public function __construct(
        public string $eventType,
        public array $options
    ) {}

    public function handle(LiteSOC $litesoc): void
    {
        $litesoc->track($this->eventType, $this->options);
        $litesoc->flush();
    }
}

// Usage - non-blocking, runs in background queue worker
TrackSecurityEvent::dispatch('auth.login_failed', [
    'actor_id' => 'user_123',
    'user_ip' => request()->ip()
]);
bash
composer 
bash
composer 
bash
php artisan vendor:publish --tag=litesoc-config