PHP SDK
PHP SDK

Introduction

The Botbye PHP SDK provides comprehensive bot protection for PHP applications. Built with modern PHP standards, it offers seamless integration with any PHP project through Composer.

Requirements

  • PHP 8.1 or higher
  • Composer

Installation

Install the SDK via Composer:

1
composer require botbye/botbye-php-sdk

Configuration

Basic Configuration

Initialize the Botbye client with your server-key (available inside your Project):

1
2
3
4
5
6
7
8
9
<?php
use Botbye\Client\BotbyeClient;
use Botbye\Client\BotbyeConfig;

$config = new BotbyeConfig(
    serverKey: '00000000-0000-0000-0000-000000000000' // Use your project server-key
);

$client = new BotbyeClient($config);

Advanced Configuration

For production environments, you can customize timeouts and connection pooling:

1
2
3
4
5
6
7
8
9
10
<?php
use Botbye\Client\BotbyeConfig;


$config = new BotbyeConfig(
    // Use your project server-key
    serverKey: '00000000-0000-0000-0000-000000000000',
    timeout: 1.0,       // the idle timeout (in seconds)
    max_duration: 2.0,  // the maximum execution time (in seconds) for the request+response as a whole
);

Custom HTTP Client

You can provide your own Symfony HttpClient instance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
use Botbye\Client\BotbyeClient;
use Botbye\Client\BotbyeConfig;
use Symfony\Component\HttpClient\HttpClient;

// Use your project server-key
$config = new BotbyeConfig(serverKey: '00000000-0000-0000-0000-000000000000');

$httpClient = HttpClient::create([
    'timeout' => 2,
    'max_redirects' => 0,
]);

$client = new BotbyeClient($config, $httpClient);

PSR-3 Logger Integration

Integrate with any PSR-3 compatible logger (e.g., Monolog):

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
use Botbye\Client\BotbyeClient;
use Botbye\Client\BotbyeConfig;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Use your project server-key";
$config = new BotbyeConfig(serverKey: '00000000-0000-0000-0000-000000000000');

$logger = new Logger('botbye');
$logger->pushHandler(new StreamHandler('/var/log/botbye.log', Logger::WARNING));

$client = new BotbyeClient($config, null, $logger);

Usage

Validate incoming requests to detect bot activity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
use Botbye\Model\ConnectionDetails;
use Botbye\Model\Headers;

// Prepare request data
$connectionDetails = new ConnectionDetails(
    remoteAddr: $_SERVER['REMOTE_ADDR'],
    requestMethod: $_SERVER['REQUEST_METHOD'],
    requestUri: $_SERVER['REQUEST_URI']
);

$headersArray = getallheaders();
$headers = Headers::fromArray($headersArray);

// Get token from header or any place you store it.
// For example in "x-botbye-token" header
$token = $headersArray['x-botbye-token'] ?? null;

// Validate the request
$response = $client->validateRequest(
    token: $token,
    connectionDetails: $connectionDetails,
    headers: $headers,
    customFields: [
        'user_id' => '12345',
        'session_id' => session_id(),
    ]
);

if ($response->result !== null && !$response->result->isAllowed) {
    http_response_code(403);
    echo 'Access denied';
    exit;
}

// Request is allowed, continue processing
echo 'Welcome!';

Methods Reference

BotbyeClient

validateRequest()

Validates an incoming request for bot activity.

Parameters:

  • token (string|null) - The Botbye token from the client
  • connectionDetails (ConnectionDetails) - Request connection information
  • headers (Headers) - Request headers
  • customFields (array) - Optional custom fields for linking the request

Returns: BotbyeResponse - Contains result and error information

ConnectionDetails

Represents HTTP request connection information.

Properties: - remoteAddr (string) - Client IP address - requestMethod (string) - HTTP method (GET, POST, etc.) - requestUri (string) - Request URI - serverPort (int|null) - Server port (optional) - serverName (string|null) - Server name (optional)

Headers

Represents HTTP headers.

Static Methods: - fromArray(array $headers) - Create Headers from an associative array

Error Handling

Error Handling Best Practices:

1. Fail Open - If Botbye service is unavailable, allow requests to proceed

2. Log Errors - Always log errors for monitoring and debugging

3. Graceful Degradation - Handle API errors without breaking user experience

4. Timeout Configuration - Set appropriate timeouts to avoid blocking requests

Best Practices

Production Usage

1. Environment Variables - Store server keys in environment variables:

1
2
3
4
<?php
$config = new BotbyeConfig(
    serverKey: $_ENV['BOTBYE_SERVER_KEY']
);

Performance

1. Connection Pooling - Use default connection pool settings for optimal performance

2. Timeouts - Keep timeouts low (1-2 seconds) to avoid blocking requests

3. Selective Protection - Only validate critical endpoints (login, checkout, etc.)

Security

1. Rate Limiting - Implement rate limiting alongside Botbye protection (can find more about it in Project Overview

2. Custom Fields - Use custom fields to link requests with user sessions for better analysis

Settings

Configuration parameters for BotbyeConfig:

Setting Description Required Default Value
serverKey Your BotBye server-key yes -
botbyeEndpoint Host of the API Server no https://verify.botbye.com
contentType Content type for requests no application/json
timeout idle timeout (in seconds) no 1.0
max_duration Maximum execution time (in seconds) for the request+response as a whole no 2.0

Demo

GitHub Repository - Full SDK source code with examples and tests.

Examples of BotBye API responses

Bot detected:

1
2
3
4
5
6
7
{
  "reqId": "f77b2abd-c5d7-44f0-be4f-174b04876583",
  "result": {
    "isAllowed": false
  },
  "error": "Automation tool used"
}

Bot not detected:

1
2
3
4
5
6
7
{
  "reqId": "f77b2abd-c5d7-44f0-be4f-174b04876583",
  "result": {
    "isAllowed": true
  },
  "error": null
}

Request banned by custom rule:

1
2
3
4
5
6
7
8
9
{
  "reqId": "f77b2abd-c5d7-44f0-be4f-174b04876583",
  "result": {
    "isAllowed": false
  },
  "error": {
    "message": "Banned by rule: MY_CUSTOM_RULE"
  }
}

Invalid server-key:

1
2
3
4
5
6
7
{
  "reqId": "f77b2abd-c5d7-44f0-be4f-174b04876583",
  "result": null,
  "error": {
    "message": "[BotBye] Bad Request: Invalid Server Key"
  }
}