### Install Castle PHP SDK using Git Source: https://github.com/castle/castle-php/blob/develop/README.md Clones the Castle PHP SDK repository from GitHub to your local machine. This command fetches the master branch, which contains the latest stable code. ```bash git clone --single-branch --branch master https://github.com/castle/castle-php ``` -------------------------------- ### Start and Stop Impersonation with Castle PHP Source: https://context7.com/castle/castle-php/llms.txt Demonstrates how to initiate and terminate an impersonation session using the Castle::impersonate() method. This is useful for admin users acting on behalf of other users, ensuring their actions are tracked distinctly. It requires the Castle SDK to be included and an API key to be set. ```php 'admin_user_1', 'properties' => [ 'impersonated_user_id' => 'target_user_12345', 'reason' => 'customer_support_request', 'ticket_id' => 'SUPPORT-5678' ] ]); echo "Impersonation started - admin actions will be tracked separately"; // ... perform admin operations on behalf of user ... // End impersonation session Castle::impersonate([ 'user_id' => 'admin_user_1', 'reset' => true ]); echo "Impersonation ended"; } catch (Castle_ForbiddenError $e) { echo "Impersonation not allowed: " . $e->getMessage(); } catch (Castle_UnauthorizedError $e) { echo "Unauthorized: " . $e->getMessage(); } ``` -------------------------------- ### Handle Castle API Errors in PHP Source: https://context7.com/castle/castle-php/llms.txt Provides comprehensive error handling for Castle API interactions using specific PHP exception classes. This example demonstrates how to catch various error types, including configuration issues, unauthorized access, bad requests, forbidden actions, not found resources, invalid tokens, invalid parameters, network errors, and generic API errors. Each catch block shows how to access error messages and relevant details like HTTP status codes. ```php '$login.succeeded', 'user_id' => 'user_12345' ]); echo "Authentication result: " . $auth->status; } catch (Castle_ConfigurationError $e) { // API key not set echo "Configuration error: Please set your Castle API key"; } catch (Castle_UnauthorizedError $e) { // HTTP 401 - Invalid API key echo "Unauthorized: " . $e->getMessage(); echo "HTTP Status: " . $e->httpStatus; // 401 } catch (Castle_BadRequest $e) { // HTTP 400 - Invalid request format echo "Bad request: " . $e->getMessage(); } catch (Castle_ForbiddenError $e) { // HTTP 403 - Action not allowed echo "Forbidden: " . $e->getMessage(); } catch (Castle_NotFoundError $e) { // HTTP 404 - Resource not found echo "Not found: " . $e->getMessage(); } catch (Castle_InvalidRequestTokenError $e) { // HTTP 422 - Invalid or missing request token echo "Invalid request token: " . $e->getMessage(); } catch (Castle_InvalidParametersError $e) { // HTTP 422 - Invalid parameters echo "Invalid parameters: " . $e->getMessage(); echo "Error type: " . $e->type; } catch (Castle_RequestError $e) { // Network/connection error echo "Network error: " . $e->getMessage(); } catch (Castle_ApiError $e) { // Generic API error echo "API error: " . $e->getMessage(); echo "HTTP Status: " . $e->httpStatus; echo "Error type: " . $e->type; } catch (Castle_CurlOptionError $e) { // Invalid cURL options provided echo "Invalid cURL options: " . $e->getMessage(); } ``` -------------------------------- ### Configure Castle PHP SDK Source: https://context7.com/castle/castle-php/llms.txt Initializes the Castle SDK with your API secret key and optional settings for timeouts and header allowlisting. The SDK must be configured before making any API calls. Dependencies include the Castle library itself. ```php 5, // Connection timeout in seconds CURLOPT_TIMEOUT => 10, // Request timeout in seconds CURLOPT_CONNECTTIMEOUT_MS => 5000, // Connection timeout in milliseconds CURLOPT_TIMEOUT_MS => 10000 // Request timeout in milliseconds ]); // Configure header allowlist (optional, not recommended unless necessary) Castle::setUseAllowlist(['User-Agent', 'Accept-Language', 'X-Custom-Header']); // Verify configuration echo Castle::getApiKey(); // Output: YOUR_API_SECRET echo Castle::VERSION; // Output: 3.2.0 echo Castle::getApiVersion(); // Output: v1 ``` -------------------------------- ### Authenticate User Actions with Castle PHP SDK Source: https://context7.com/castle/castle-php/llms.txt Authenticates a user action and returns a recommendation (approve, challenge, or deny) based on Castle's risk assessment. Requires `user_id` and `event` parameters. Handles potential authentication errors like unauthorized keys or invalid parameters. ```php '$login.succeeded', 'user_id' => 'user_12345', 'user_traits' => [ 'email' => 'user@example.com', 'created_at' => '2022-01-15T10:30:00Z' ], 'properties' => [ 'attempted_username' => 'johndoe' ] ]); // Handle the authentication response switch ($auth->status) { case 'approve': // Allow the action - user behavior is normal echo "Login approved"; break; case 'challenge': // Request additional verification (MFA, CAPTCHA, etc.) echo "Challenge required - verify with MFA"; break; case 'deny': // Block the action - high risk detected echo "Login denied - suspicious activity"; break; } // Access additional response properties echo $auth->risk; // Risk score (0.0 - 1.0) echo $auth->device_token; // Device identifier for future requests } catch (Castle_UnauthorizedError $e) { echo "Invalid API key: " . $e->getMessage(); } catch (Castle_InvalidParametersError $e) { echo "Invalid parameters: " . $e->getMessage(); } ``` -------------------------------- ### Include Castle SDK in PHP Script Source: https://github.com/castle/castle-php/blob/develop/README.md Includes the main Castle PHP library file into your script. This makes the Castle SDK functionalities available for use. ```php require_once("/path/to/castle-php/lib/Castle.php"); ``` -------------------------------- ### Extract Request Context with Castle PHP Source: https://context7.com/castle/castle-php/llms.txt Shows how to extract request context information using Castle_RequestContext in PHP. This is valuable for tracking events from background workers or environments where PHP globals are not readily available. It covers extracting the full context, JSON representation, and individual components like IP address, user agent, headers, and client ID. Manual context creation for API calls is also demonstrated. ```php 'cid_abc123...', 'ip' => '192.168.1.100', 'headers' => ['User-Agent' => 'Mozilla/5.0...', ...], 'user_agent' => 'Mozilla/5.0...', 'library' => ['name' => 'castle-php', 'version' => '3.2.0'] ] */ // Get context as JSON string $contextJson = Castle_RequestContext::extractJSON(); // Extract individual context components $clientIp = Castle_RequestContext::extractIp(); // Checks X-Forwarded-For, X-Real-IP, REMOTE_ADDR $userAgent = Castle_RequestContext::extractUserAgent(); $headers = Castle_RequestContext::extractHeaders(); $clientId = Castle_RequestContext::extractClientId(); // From X-Castle-Client-Id header or __cid cookie // Manual context for background worker processing $manualContext = [ 'ip' => '203.0.113.50', 'user_agent' => 'Custom-Agent/1.0', 'headers' => [ 'Accept-Language' => 'en-US,en;q=0.9' ], 'client_id' => 'stored_client_id_from_session', 'library' => [ 'name' => 'castle-php', 'version' => Castle::VERSION ] ]; // Use manual context in API calls Castle::track([ 'event' => '$password_reset.succeeded', 'user_id' => 'user_12345', 'context' => $manualContext ]); ``` -------------------------------- ### Set Allowlist for Request Headers in PHP Source: https://github.com/castle/castle-php/blob/develop/README.md Specifies a list of request headers to be included with event context. This is an optional configuration and generally not recommended. ```php Castle::setUseAllowlist($headers); ``` -------------------------------- ### Log Security Events with Castle::log() in PHP Source: https://context7.com/castle/castle-php/llms.txt Log security events asynchronously with status information. Use this method to record the outcome of actions after they complete. It requires the Castle SDK to be included and the API key to be set. ```php '7e51335b-f4bc-4bc7-875d-b713fb61eb23-bf021a3022a1a302', 'event' => '$login', 'status' => '$succeeded', 'user' => [ 'id' => 'user_12345', 'email' => 'user@example.com' ] ]); // Log a failed login attempt Castle::log([ 'request_token' => '7e51335b-f4bc-4bc7-875d-b713fb61eb23-bf021a3022a1a302', 'event' => '$login', 'status' => '$failed', 'user' => [ 'id' => 'user_12345', 'email' => 'user@example.com' ], 'properties' => [ 'failure_reason' => 'invalid_credentials' ] ]); // Log a challenge completed Castle::log([ 'request_token' => '7e51335b-f4bc-4bc7-875d-b713fb61eb23-bf021a3022a1a302', 'event' => '$challenge', 'status' => '$succeeded', 'user' => [ 'id' => 'user_12345' ], 'properties' => [ 'challenge_type' => 'sms_otp' ] ]); echo "Events logged successfully"; } catch (Castle_ApiError $e) { echo "Logging error: " . $e->getMessage(); } ?> ``` -------------------------------- ### Manually Set Origin IP Address in PHP Source: https://github.com/castle/castle-php/blob/develop/README.md Manually sets the client IP address for the request context when automatic extraction from global variables is not possible. This is useful for tracking events from background workers. ```php Castle_RequestContext['ip'] = '1.1.1.1'; $context = Castle_RequestContext::extractJson(); ``` -------------------------------- ### Configure Castle API Key in PHP Source: https://github.com/castle/castle-php/blob/develop/README.md Sets the Castle API secret key for the SDK. This is a mandatory step to authenticate your application with the Castle API. ```php Castle::setApiKey('YOUR_API_SECRET'); ``` -------------------------------- ### Assess Risk with Castle::risk() in PHP Source: https://context7.com/castle/castle-php/llms.txt Assess the risk of an action in real-time with full user context. This method returns detailed risk signals and a risk score for making security decisions. It requires the Castle SDK to be included and the API key to be set. ```php '7e51335b-f4bc-4bc7-875d-b713fb61eb23-bf021a3022a1a302', 'event' => '$login', 'status' => '$succeeded', 'user' => [ 'id' => 'user_12345', 'email' => 'user@example.com', 'name' => 'John Doe' ], 'context' => Castle_RequestContext::extract(), 'properties' => [ 'login_method' => 'password', 'remember_me' => true ] ]); // Access risk assessment details $riskScore = $riskResult->risk; // 0.0 (safe) to 1.0 (high risk) $signals = $riskResult->signals; // Array of risk signals detected $device = $riskResult->device; // Device information // Make security decision based on risk score if ($riskScore > 0.8) { // High risk - require step-up authentication echo "High risk detected. Please verify your identity."; } elseif ($riskScore > 0.5) { // Medium risk - monitor closely echo "Login successful. We noticed unusual activity."; } else { // Low risk - proceed normally echo "Login successful."; } } catch (Castle_BadRequest $e) { echo "Bad request: " . $e->getMessage(); } ?> ``` -------------------------------- ### Castle::risk() - Assess Risk Source: https://context7.com/castle/castle-php/llms.txt Assesses the risk of an action in real-time with full user context. Returns detailed risk signals and a risk score for making security decisions. ```APIDOC ## POST /risk ### Description Assesses the risk of an action in real-time with full user context. Returns detailed risk signals and a risk score for making security decisions. ### Method POST ### Endpoint Castle::risk() ### Parameters #### Request Body - **request_token** (string) - Required - A unique token representing the request. - **event** (string) - Required - The type of event occurring (e.g., "$login"). - **status** (string) - Required - The status of the event (e.g., "$succeeded", "$failed"). - **user** (object) - Required - Information about the user. - **id** (string) - The unique identifier for the user. - **email** (string) - The email address of the user. - **name** (string) - The name of the user. - **context** (object) - Optional - Contextual information about the request (can be extracted using `Castle_RequestContext::extract()`). - **properties** (object) - Optional - Additional properties related to the event. - **login_method** (string) - The method used for login. - **remember_me** (boolean) - Whether the 'remember me' option was selected. ### Request Example ```json { "request_token": "7e51335b-f4bc-4bc7-875d-b713fb61eb23-bf021a3022a1a302", "event": "$login", "status": "$succeeded", "user": { "id": "user_12345", "email": "user@example.com", "name": "John Doe" }, "context": { "ip": "192.168.1.1", "headers": {}, "user_agent": "Mozilla/5.0" }, "properties": { "login_method": "password", "remember_me": true } } ``` ### Response #### Success Response (200) - **risk** (float) - The risk score (0.0 - 1.0). - **signals** (array) - An array of risk signals detected. - **device** (object) - Information about the device used. #### Response Example ```json { "risk": 0.6, "signals": ["high_velocity_login"], "device": { "id": "device_abc", "model": "iPhone", "os": "iOS" } } ``` #### Error Handling - **Castle_BadRequest**: Thrown for bad requests. ``` -------------------------------- ### Filter Incoming Requests with Castle::filter() in PHP Source: https://context7.com/castle/castle-php/llms.txt Filter incoming requests to detect and block malicious activity before it reaches your application. This method returns a risk assessment with signals and policy actions without requiring user identification. It requires the Castle SDK to be included and the API key to be set. ```php '7e51335b-f4bc-4bc7-875d-b713fb61eb23-bf021a3022a1a302', 'event' => '$registration', 'context' => [ 'ip' => $_SERVER['REMOTE_ADDR'], 'headers' => getallheaders(), 'user_agent' => $_SERVER['HTTP_USER_AGENT'] ], 'user' => [ 'id' => 'new_user_abc', 'email' => 'newuser@example.com' ], 'properties' => [ 'registration_method' => 'email', 'referral_source' => 'organic' ] ]); // Check the policy action $action = $result->policy->action; // 'allow', 'challenge', or 'deny' $riskScore = $result->risk; // Risk score (0.0 - 1.0) if ($action === 'deny') { // Block the registration http_response_code(403); echo "Registration blocked due to suspicious activity"; } elseif ($action === 'challenge') { // Require additional verification echo "Please complete CAPTCHA verification"; } else { // Allow registration to proceed echo "Registration allowed"; } } catch (Castle_InvalidRequestTokenError $e) { echo "Invalid request token: " . $e->getMessage(); } catch (Castle_ApiError $e) { echo "API error: " . $e->getMessage(); } ?> ``` -------------------------------- ### Castle::log() - Log Events Source: https://context7.com/castle/castle-php/llms.txt Logs security events asynchronously with status information. Use this method to record the outcome of actions after they complete. ```APIDOC ## POST /log ### Description Logs security events asynchronously with status information. Use this method to record the outcome of actions after they complete. ### Method POST ### Endpoint Castle::log() ### Parameters #### Request Body - **request_token** (string) - Required - A unique token representing the request. - **event** (string) - Required - The type of event occurring (e.g., "$login", "$challenge"). - **status** (string) - Required - The status of the event (e.g., "$succeeded", "$failed"). - **user** (object) - Optional - Information about the user. - **id** (string) - The unique identifier for the user. - **email** (string) - The email address of the user. - **properties** (object) - Optional - Additional properties related to the event. - **failure_reason** (string) - The reason for a failed event. - **challenge_type** (string) - The type of challenge performed. ### Request Example ```json { "request_token": "7e51335b-f4bc-4bc7-875d-b713fb61eb23-bf021a3022a1a302", "event": "$login", "status": "$succeeded", "user": { "id": "user_12345", "email": "user@example.com" } } ``` ### Response #### Success Response (200) Indicates the event was successfully logged. #### Response Example (No specific response body is detailed for success, typically an empty 200 OK) #### Error Handling - **Castle_ApiError**: Thrown for general API errors during logging. ``` -------------------------------- ### Track Security Events with Castle PHP SDK Source: https://context7.com/castle/castle-php/llms.txt Tracks security events for logging purposes without receiving a real-time verdict. Suitable for events like password changes, profile updates, or session activities. Handles potential network or configuration errors. ```php '$login.failed', 'user_id' => 'user_12345', 'user_traits' => [ 'email' => 'user@example.com' ], 'properties' => [ 'attempted_username' => 'johndoe', 'error_reason' => 'invalid_password' ] ]); // Track a password reset request Castle::track([ 'event' => '$password_reset.requested', 'user_id' => 'user_12345', 'properties' => [ 'method' => 'email' ] ]); // Track a profile update Castle::track([ 'event' => '$profile.updated', 'user_id' => 'user_12345', 'properties' => [ 'updated_fields' => ['email', 'phone'] ] ]); echo "Events tracked successfully"; } catch (Castle_RequestError $e) { echo "Network error: " . $e->getMessage(); } catch (Castle_ConfigurationError $e) { echo "API key not configured"; } ``` -------------------------------- ### Castle::filter() - Filter Requests Source: https://context7.com/castle/castle-php/llms.txt Filters incoming requests to detect and block malicious activity before it reaches your application. It returns a risk assessment with signals and policy actions without requiring user identification. ```APIDOC ## POST /filter ### Description Filters incoming requests to detect and block malicious activity before it reaches your application. Returns a risk assessment with signals and policy actions without requiring user identification. ### Method POST ### Endpoint Castle::filter() ### Parameters #### Request Body - **request_token** (string) - Required - A unique token representing the request. - **event** (string) - Required - The type of event occurring (e.g., "$registration"). - **context** (object) - Optional - Contextual information about the request. - **ip** (string) - The IP address of the client. - **headers** (object) - Key-value pairs of request headers. - **user_agent** (string) - The User-Agent string of the client. - **user** (object) - Optional - Information about the user. - **id** (string) - The unique identifier for the user. - **email** (string) - The email address of the user. - **properties** (object) - Optional - Additional properties related to the event. ### Request Example ```json { "request_token": "7e51335b-f4bc-4bc7-875d-b713fb61eb23-bf021a3022a1a302", "event": "$registration", "context": { "ip": "192.168.1.1", "headers": { "User-Agent": "Mozilla/5.0", "Accept-Language": "en-US" }, "user_agent": "Mozilla/5.0" }, "user": { "id": "new_user_abc", "email": "newuser@example.com" }, "properties": { "registration_method": "email", "referral_source": "organic" } } ``` ### Response #### Success Response (200) - **policy** (object) - The policy decision. - **action** (string) - The action to take ('allow', 'challenge', or 'deny'). - **risk** (float) - The risk score (0.0 - 1.0). #### Response Example ```json { "policy": { "action": "allow" }, "risk": 0.1 } ``` #### Error Handling - **Castle_InvalidRequestTokenError**: Thrown if the request token is invalid. - **Castle_ApiError**: Thrown for general API errors. ``` -------------------------------- ### Set cURL Timeouts in PHP Source: https://github.com/castle/castle-php/blob/develop/README.md Configures connection and request timeouts for cURL requests made by the Castle SDK. This allows you to control how long the SDK waits for a response from the Castle API. ```php Castle::setCurlOpts($curlOpts); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.