PHP Examples
PHP integration examples for the CuliUptime API using session-based authentication.
š¦ Installationā
composer require guzzlehttp/guzzle
# Note: Official CuliUptime PHP SDK is planned for future release
š Authentication Approachā
CuliUptime uses OAuth2 social login. For PHP integrations, you can:
- Web Dashboard Integration: Use embedded web views for OAuth2 flow
- Session-based API: Extract session cookies from authenticated browser sessions
- Future SDK: Wait for official PHP SDK with OAuth2 support
š Session-Based PHP Clientā
Basic Client Classā
<?php
require_once 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
class CuliUptimeAPI
{
private string $sessionCookie;
private string $baseURL;
private Client $client;
public function __construct(string $sessionCookie, string $baseURL = 'https://uptime.culiops.net/api/v1')
{
$this->sessionCookie = $sessionCookie;
$this->baseURL = $baseURL;
$this->client = new Client([
'base_uri' => $this->baseURL,
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Cookie' => "session_cookie={$this->sessionCookie}"
],
'timeout' => 30.0
]);
}
private function request(string $method, string $endpoint, array $data = null): array
{
try {
$options = [];
if ($data) {
$options['json'] = $data;
}
$response = $this->client->request($method, $endpoint, $options);
return json_decode($response->getBody(), true);
} catch (RequestException $e) {
if ($e->hasResponse()) {
$statusCode = $e->getResponse()->getStatusCode();
$message = $e->getResponse()->getReasonPhrase();
throw new Exception("API Error: {$statusCode} - {$message}");
}
throw new Exception("Request failed: " . $e->getMessage());
}
}
// Monitor Management
public function getMonitors(array $params = []): array
{
$endpoint = '/monitors';
if (!empty($params)) {
$endpoint .= '?' . http_build_query($params);
}
$response = $this->request('GET', $endpoint);
return $response['data'] ?? [];
}
public function getMonitor(int $monitorId): array
{
$response = $this->request('GET', "/monitors/{$monitorId}");
return $response['data'] ?? [];
}
public function createMonitor(array $monitorData): array
{
$response = $this->request('POST', '/monitors', $monitorData);
return $response['data'] ?? [];
}
public function updateMonitor(int $monitorId, array $updates): array
{
$response = $this->request('PUT', "/monitors/{$monitorId}", $updates);
return $response['data'] ?? [];
}
public function deleteMonitor(int $monitorId): bool
{
$this->request('DELETE', "/monitors/{$monitorId}");
return true;
}
public function enableMonitor(int $monitorId): array
{
return $this->request('POST', "/monitors/{$monitorId}/enable");
}
public function disableMonitor(int $monitorId): array
{
return $this->request('POST', "/monitors/{$monitorId}/disable");
}
public function testMonitor(int $monitorId): array
{
$response = $this->request('POST', "/monitors/{$monitorId}/test");
return $response['data'] ?? [];
}
public function getMonitorResults(int $monitorId, array $params = []): array
{
$endpoint = "/monitors/{$monitorId}/results";
if (!empty($params)) {
$endpoint .= '?' . http_build_query($params);
}
$response = $this->request('GET', $endpoint);
return $response['data'] ?? [];
}
public function getMonitorStats(int $monitorId): array
{
$response = $this->request('GET', "/monitors/{$monitorId}/stats");
return $response['data'] ?? [];
}
// Agent Management
public function getAgents(): array
{
$response = $this->request('GET', '/agents');
return $response['data'] ?? [];
}
public function getAccessibleAgents(): array
{
$response = $this->request('GET', '/agents/accessible');
return $response['data'] ?? [];
}
public function getAgent(int $agentId): array
{
$response = $this->request('GET', "/agents/{$agentId}");
return $response['data'] ?? [];
}
public function assignAgentsToMonitor(int $monitorId, array $agentIds): array
{
return $this->request('POST', "/monitors/{$monitorId}/agents", ['agent_ids' => $agentIds]);
}
// Notifications
public function getActiveNotifications(): array
{
$response = $this->request('GET', '/notifications/active');
return $response['data'] ?? [];
}
public function getRecentNotifications(): array
{
$response = $this->request('GET', '/notifications/recent');
return $response['data'] ?? [];
}
public function getNotifications(array $params = []): array
{
$endpoint = '/notifications';
if (!empty($params)) {
$endpoint .= '?' . http_build_query($params);
}
$response = $this->request('GET', $endpoint);
return $response['data'] ?? [];
}
public function acknowledgeNotification(int $notificationId): array
{
return $this->request('POST', "/notifications/{$notificationId}/acknowledge");
}
// User & Dashboard
public function getCurrentUser(): array
{
$response = $this->request('GET', '/auth/user');
return $response['data'] ?? [];
}
public function getDashboardData(): array
{
$response = $this->request('GET', '/dashboard');
return $response['data'] ?? [];
}
public function getUserPreferences(): array
{
$response = $this->request('GET', '/preferences');
return $response['data'] ?? [];
}
public function updateUserPreferences(array $preferences): array
{
$response = $this->request('PUT', '/preferences', $preferences);
return $response['data'] ?? [];
}
}
š Usage Examplesā
Initialize Clientā
// Initialize with session cookie from browser
$api = new CuliUptimeAPI('your_session_cookie_value');
Monitor Managementā
try {
// Get all monitors
$monitors = $api->getMonitors();
echo "Found " . count($monitors) . " monitors\n";
// Get online monitors only
$onlineMonitors = $api->getMonitors(['status' => 'online']);
// Search monitors
$apiMonitors = $api->getMonitors(['search' => 'api']);
// Create new HTTP monitor
$newMonitor = $api->createMonitor([
'name' => 'My API Endpoint',
'url' => 'https://api.example.com/health',
'method' => 'GET',
'expected_status' => [200, 201],
'timeout' => 30,
'check_interval' => 300
]);
echo "Created monitor with ID: {$newMonitor['id']}\n";
// Update monitor
$updatedMonitor = $api->updateMonitor($newMonitor['id'], [
'check_interval' => 600,
'timeout' => 45
]);
// Test monitor immediately
$testResult = $api->testMonitor($newMonitor['id']);
echo "Monitor status: {$testResult['status']}\n";
// Get monitor statistics
$stats = $api->getMonitorStats($newMonitor['id']);
echo "Uptime: " . ($stats['uptime_24h'] ?? 0) . "%\n";
} catch (Exception $e) {
echo "Monitor management error: " . $e->getMessage() . "\n";
}
Notification Handlingā
try {
// Check for active alerts
$activeNotifications = $api->getActiveNotifications();
if (!empty($activeNotifications)) {
echo "ā ļø " . count($activeNotifications) . " active notifications:\n";
foreach ($activeNotifications as $notification) {
echo " - {$notification['message']}\n";
// Acknowledge notification
$api->acknowledgeNotification($notification['id']);
echo " ā
Acknowledged notification {$notification['id']}\n";
}
}
// Get notification history
$recentNotifications = $api->getRecentNotifications();
echo "Recent notifications: " . count($recentNotifications) . "\n";
} catch (Exception $e) {
echo "Notification handling error: " . $e->getMessage() . "\n";
}
Agent Managementā
try {
// Get available agents
$agents = $api->getAccessibleAgents();
echo "Available agents: " . count($agents) . "\n";
foreach ($agents as $agent) {
echo " - {$agent['name']} ({$agent['location']}) - Status: {$agent['status']}\n";
}
// Assign agents to monitor
$monitors = $api->getMonitors();
if (count($agents) >= 2 && count($monitors) > 0) {
$agentIds = array_slice(array_column($agents, 'id'), 0, 2); // Use first 2 agents
$monitorId = $monitors[0]['id']; // Use first monitor
$api->assignAgentsToMonitor($monitorId, $agentIds);
echo "Assigned " . count($agentIds) . " agents to monitor {$monitorId}\n";
}
} catch (Exception $e) {
echo "Agent management error: " . $e->getMessage() . "\n";
}
Dashboard Integrationā
try {
// Get dashboard overview
$dashboard = $api->getDashboardData();
echo "š Dashboard Overview:\n";
echo " - Total Monitors: " . ($dashboard['total_monitors'] ?? 0) . "\n";
echo " - Online: " . ($dashboard['online_monitors'] ?? 0) . "\n";
echo " - Offline: " . ($dashboard['offline_monitors'] ?? 0) . "\n";
echo " - Average Uptime: " . number_format($dashboard['average_uptime'] ?? 0, 2) . "%\n";
} catch (Exception $e) {
echo "Dashboard error: " . $e->getMessage() . "\n";
}
š Advanced Usageā
Error Handlingā
class CuliUptimeException extends Exception
{
private ?int $statusCode;
public function __construct(string $message, int $statusCode = null, Throwable $previous = null)
{
parent::__construct($message, 0, $previous);
$this->statusCode = $statusCode;
}
public function getStatusCode(): ?int
{
return $this->statusCode;
}
}
// Enhanced client with error handling
class EnhancedCuliUptimeAPI extends CuliUptimeAPI
{
private function request(string $method, string $endpoint, array $data = null): array
{
try {
return parent::request($method, $endpoint, $data);
} catch (RequestException $e) {
if ($e->hasResponse()) {
$statusCode = $e->getResponse()->getStatusCode();
switch ($statusCode) {
case 401:
throw new CuliUptimeException('Authentication failed - session expired', 401);
case 429:
throw new CuliUptimeException('Rate limit exceeded', 429);
case 500:
case 502:
case 503:
throw new CuliUptimeException('Server error occurred', $statusCode);
default:
throw new CuliUptimeException("API error: {$statusCode}", $statusCode);
}
}
throw new CuliUptimeException("Network error: " . $e->getMessage());
}
}
}
// Usage with error handling
try {
$api = new EnhancedCuliUptimeAPI('your_session_cookie');
$monitors = $api->getMonitors();
echo "Successfully retrieved " . count($monitors) . " monitors\n";
} catch (CuliUptimeException $e) {
echo "API Error ({$e->getStatusCode()}): {$e->getMessage()}\n";
} catch (Exception $e) {
echo "Unexpected error: {$e->getMessage()}\n";
}
Batch Operationsā
function batchUpdateMonitors(CuliUptimeAPI $api, array $updates): array
{
$results = [];
foreach ($updates as $update) {
$id = $update['id'];
unset($update['id']);
try {
$result = $api->updateMonitor($id, $update);
$results[] = ['status' => 'success', 'id' => $id, 'result' => $result];
} catch (Exception $e) {
$results[] = ['status' => 'error', 'id' => $id, 'error' => $e->getMessage()];
}
}
return $results;
}
// Example batch update
$updates = [
['id' => 123, 'check_interval' => 300],
['id' => 124, 'timeout' => 45],
['id' => 125, 'check_interval' => 600]
];
$results = batchUpdateMonitors($api, $updates);
foreach ($results as $result) {
echo "Monitor {$result['id']}: {$result['status']}\n";
}
Monitor Health Checkerā
function checkMonitorHealth(CuliUptimeAPI $api, int $monitorId): array
{
try {
$monitor = $api->getMonitor($monitorId);
$stats = $api->getMonitorStats($monitorId);
$recentResults = $api->getMonitorResults($monitorId);
$recentFailures = 0;
foreach (array_slice($recentResults, 0, 10) as $result) {
if ($result['status'] !== 'online') {
$recentFailures++;
}
}
$uptime24h = $stats['uptime_24h'] ?? 0;
$healthScore = $uptime24h > 99 ? 'excellent' : ($uptime24h > 95 ? 'good' : 'poor');
return [
'monitor_id' => $monitorId,
'name' => $monitor['name'],
'url' => $monitor['url'],
'status' => $monitor['status'],
'uptime_24h' => $uptime24h,
'avg_response_time' => $stats['avg_response_time'] ?? 0,
'recent_failures' => $recentFailures,
'health_score' => $healthScore
];
} catch (Exception $e) {
throw new Exception("Health check failed: " . $e->getMessage());
}
}
// Generate health report
$health = checkMonitorHealth($api, 123);
echo "\nš„ Health Report for {$health['name']}:\n";
echo " Status: {$health['status']}\n";
echo " 24h Uptime: " . number_format($health['uptime_24h'], 2) . "%\n";
echo " Avg Response Time: {$health['avg_response_time']}ms\n";
echo " Recent Failures: {$health['recent_failures']}/10\n";
echo " Health Score: {$health['health_score']}\n";
š§ Session Cookie Managementā
Extract Session Cookieā
// Manual cookie extraction (for development)
function getSessionCookieFromInput(): string
{
/*
Instructions for extracting session cookie:
1. Open browser and login to CuliUptime dashboard
2. Open Developer Tools (F12)
3. Go to Application/Storage tab
4. Click on Cookies
5. Find 'session_cookie' and copy its value
6. Use the value to initialize the API client
*/
echo "Enter session cookie from browser: ";
return trim(fgets(STDIN));
}
// Environment variable approach (recommended)
function getSessionCookieFromEnv(): string
{
$cookie = getenv('CULIUPTIME_SESSION_COOKIE');
if (!$cookie) {
throw new Exception('CULIUPTIME_SESSION_COOKIE environment variable not set');
}
return $cookie;
}
Session Validationā
function validateSession(CuliUptimeAPI $api): bool
{
try {
$user = $api->getCurrentUser();
return !empty($user['id']);
} catch (Exception $e) {
return false;
}
}
// Check session validity
if (validateSession($api)) {
echo "ā
Session is valid\n";
} else {
echo "ā Session expired or invalid\n";
}
Note: For production applications, consider implementing a proper OAuth2 flow or wait for the official CuliUptime PHP SDK which will handle authentication securely.