### Install SDK with Composer Source: https://github.com/cleantalk/php-antispam/blob/master/README.md Use Composer to install the cleantalk/php-antispam package. This is the recommended installation method. ```bash composer require cleantalk/php-antispam ``` -------------------------------- ### Quick start snippet Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/README.md Minimal example of using the library: require the entry file or rely on Composer autoload, then create a CleantalkAntispam instance, set contact form fields, and handle the request. If the result is blocked, it dies with a comment. ```php require_once 'cleantalk-antispam.php'; // or rely on Composer PSR-4 autoload use CleanTalk\CleantalkAntispam; $api_key = getenv('CLEANTALK_API_KEY'); $result = (new CleantalkAntispam($api_key)) ->useContactFormCheck() ->setEmail($_POST['email']) ->setNickName($_POST['name']) ->setMessage($_POST['message']) ->setEventTokenEnabled(1) ->handle(); if ($result->allow === 0) { die('Blocked: ' . $result->comment); } ``` -------------------------------- ### GET with presets and custom callback with Response Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Request.md Shows a GET request using presets 'get', 'get_code', and 'dont_follow_redirects', where the result is the HTTP status code due to 'get_code'. Also demonstrates a second request with a custom callback that receives the Response object because $pass_response is true, returning a formatted string. ```php $http = new Request(); $result = $http->setUrl('https://example.com') ->setData(array('q' => 'spam')) // appended to the URL by the 'get' preset ->setPresets(array('get', 'get_code', 'dont_follow_redirects')) ->request(); // $result is the HTTP status code (int) because of the 'get_code' internal callback. $http2 = (new Request()) ->setUrl('https://example.com/check') ->addCallback(function ($response, $url) { // $response is the Response object because $pass_response = true return 'HTTP ' . $response->getResponseCode() . ' for ' . $url; }, array(), 10, true); $result2 = $http2->request(); ``` -------------------------------- ### fromUTF8 usage example Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Helper.md Example call to fromUTF8() converting a response object to ISO-8859-1 encoding. ```php Helper::fromUTF8($response_json_obj, 'ISO-8859-1'); ``` -------------------------------- ### httpGetHeaders method signature and usage example Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Helper.md Retrieves all HTTP_* entries from $_SERVER, reformatting keys from HTTP_X_Y to X-Y style (e.g., HTTP_X_FORWARDED_FOR becomes X-Forwarded-For). Skips empty prefix parts. The usage example checks for the X-Forwarded-For header, which depends on the request. ```php public static function httpGetHeaders() ``` ```php $headers = Helper::httpGetHeaders(); isset($headers['X-Forwarded-For']); // depends on the request ``` -------------------------------- ### Use ipGet to retrieve IP addresses Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Helper.md Shows example calls to Helper::ipGet with different arguments: default real IPv4, allowing IPv6, and Cloudflare-specific header. ```php $ip = Helper::ipGet(); // 'real', IPv4 only $ip6 = Helper::ipGet('real', false); // allow IPv6 $cf = Helper::ipGet('cloud_flare'); // only Cloudflare headers ``` -------------------------------- ### appendParametersToURL usage examples Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Request.md Shows how to call appendParametersToURL with an array or string of parameters. The first example appends '?x=1' to a URL without a query string; the second appends '&x=1' to a URL that already has '?y=2'. ```php Request::appendParametersToURL('http://e.com/a', array('x' => 1)); // http://e.com/a?x=1 Request::appendParametersToURL('http://e.com/a?y=2', 'x=1'); // http://e.com/a?y=2&x=1 ``` -------------------------------- ### getPlatformServerAddr usage example Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Helper.md Example call to getPlatformServerAddr() returning a server IP like '127.0.0.1'. ```php Helper::getPlatformServerAddr(); // e.g. '127.0.0.1' ``` -------------------------------- ### ipValidate usage examples Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Helper.md Shows expected return values for valid IPv4, valid IPv6, and invalid IP inputs. Use to verify the method's behavior with typical inputs. ```php Helper::ipValidate('8.8.8.8'); // 'v4' Helper::ipValidate('2001:db8::1'); // 'v6' Helper::ipValidate('not-an-ip'); // false ``` -------------------------------- ### setPresets method Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Request.md Sets presets for the request. Accepts an array or a space-separated string like 'get_code async get'. Returns the Request instance. ```php public function setPresets($presets) ``` -------------------------------- ### ipMaskMatch usage examples Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Helper.md Shows expected boolean results for matching and non-matching IP/CIDR pairs, including IPv6. Use to verify the method's behavior with typical inputs. ```php Helper::ipMaskMatch('10.1.2.3', '10.0.0.0/8'); // true Helper::ipMaskMatch('11.1.2.3', '10.0.0.0/8'); // false Helper::ipMaskMatch('::1', '0:0:0:0:0:0:0:1/128', 'v6'); // true ``` -------------------------------- ### ipIsPrivateNetwork usage examples Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Helper.md Shows expected boolean results for private and public IPs, including IPv6 loopback. Use to verify the method's behavior with typical inputs. ```php Helper::ipIsPrivateNetwork('192.168.1.5'); // true Helper::ipIsPrivateNetwork('8.8.8.8'); // false Helper::ipIsPrivateNetwork('::1', 'v6'); // true ``` -------------------------------- ### isJson usage examples Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Request.md Demonstrates isJson with a valid JSON string returning true and a plain string returning false. ```php Request::isJson('{"a":1}'); // true Request::isJson('plain'); // false ``` -------------------------------- ### setPresets Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Request.md Sets presets for the request. Accepts an array of presets or a space-separated string. Non-array values are split with `explode(' ', ...)`. Supported presets include `dont_follow_redirects`, `get_code`, `split_to_array`, `async`, `get`, `ssl`, `cache`, `no_cache`, `retry_with_socket`, and `api3.0`. ```APIDOC ## setPresets ### Description Sets presets for the request. Accepts an array of presets or a space-separated string. Non-array values are split with `explode(' ', ...)`. Supported presets include `dont_follow_redirects`, `get_code`, `split_to_array`, `async`, `get`, `ssl`, `cache`, `no_cache`, `retry_with_socket`, and `api3.0`. ### Method N/A (fluent setter) ### Endpoint N/A ### Parameters #### Path Parameters None. #### Query Parameters None. #### Request Body - **$presets** (string[]|string) - Required - Array of presets or a space-separated string. ### Request Example ```php $request->setPresets('get_code async get'); ``` ### Response #### Success Response (200) - **$this** (Request) - Returns the current instance for chaining. #### Response Example ```php $request->setPresets('get_code async get'); ``` ``` -------------------------------- ### Error handling with getArray() and allow property Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/CleantalkVerdict.md Example of error handling with the verdict object. Checks for an error and logs the array, then checks if the submission is blocked and prints the comment. ```php $api_result = $cleantalk_antispam->handle(); if (!empty($api_result->error)) { // Error path: inspect or log the verdict as an array. error_log(print_r($api_result->getArray(), true)); } if ($api_result->allow === 0) { echo 'Blocked: ' . $api_result->comment; } ``` -------------------------------- ### setEventTokenEnabled(1) Source: https://github.com/cleantalk/php-antispam/blob/master/readme_additional.md Enables event-token processing in the PHP request. Must be called when the Bot Detector script is installed on the form. ```APIDOC ## setEventTokenEnabled(1) ### Description Enables event-token processing in the PHP request. Must be called when the Bot Detector script is installed on the form. ### Method setEventTokenEnabled ### Parameters - **enabled** (int) - Required - Set to 1 to enable event-token processing. ### Request Example ```php $cleantalk_antispam->setEventTokenEnabled(1); ``` ``` -------------------------------- ### setData method Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Request.md Sets the POST or GET data. Scalar non-JSON values are converted to an array, JSON strings are passed through, and arrays are used as-is. Returns the Request instance. ```php public function setData($data) ``` -------------------------------- ### Typical call flow diagram Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/README.md ASCII diagram showing the typical call flow of the library: from constructing CleantalkAntispam, through fluent setters, to handle() and its internal steps. ```text new CleantalkAntispam($apiKey, [$email]) │ (reads $_POST, event token, detects IP) ▼ fluent setters: setEmail/setNickName/setMessage/setIP/setEventToken(...) setDoBlockNoJSVisitor/setEventTokenEnabled/use*Check │ ▼ handle() ──► verifyData() ──► Request (POST api2.0) ──► CleantalkResponse ──► CleantalkVerdict │ └──► whatswrong(true) (suggestions + request data + verdict) ``` -------------------------------- ### Response::getResponseCode Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Response.md Gets the HTTP response code from the cURL info. ```APIDOC ## getResponseCode ### Description Returns the HTTP status code from the cURL info array, or null if not available. ### Method Method ### Signature `public function getResponseCode()` ### Parameters None ### Returns - **mixed** - The HTTP status code `(int) $info['http_code']`, or `null` when the info array had no `http_code` key (e.g. for socket-based responses). ``` -------------------------------- ### Log improvement suggestions for troubleshooting Source: https://github.com/cleantalk/php-antispam/blob/master/README.md Log the output of whatsWrong(true) after calling handle() to identify configuration problems. Warning: the diagnostic output may contain personal data; use only while troubleshooting and store in protected logs. ```php // Troubleshooting: log improvement suggestions. error_log($cleantalk_antispam->whatsWrong(true)); ``` -------------------------------- ### Inspect request and verdict with whatsWrong Source: https://github.com/cleantalk/php-antispam/blob/master/readme_additional.md Calls handle() and then whatsWrong(true) to inspect improvement suggestions, the prepared request data, and the verdict. The output is written to the error log. ```php $api_result = $cleantalk_antispam->handle(); error_log($cleantalk_antispam->whatsWrong(true)); ``` -------------------------------- ### getContentProcessed method signature Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Response.md Signature for the getContentProcessed method. Returns the processed content, which starts equal to the raw content and is updated by setProcessed(). ```php public function getContentProcessed() ``` -------------------------------- ### Basic POST request with error handling Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Request.md Creates a Request, sets a URL and data, sends a POST request, and logs an error if the result contains an 'error' key. The error message may be 'CURL_NOT_INSTALLED' or another failure string. ```php use CleanTalk\HTTP\Request; $http = new Request(); $result = $http->setUrl('https://moderate.cleantalk.org/api2.0') ->setData(array('foo' => 'bar')) ->request(); if (isset($result['error'])) { error_log('Request failed: ' . $result['error']); // e.g. CURL_NOT_INSTALLED } ``` -------------------------------- ### useRegistrationCheck() - Select check_newuser method Source: https://github.com/cleantalk/php-antispam/blob/master/readme_additional.md Selects the check_newuser API method. Use for registrations, subscriptions, and forms where there is no user-written message to inspect. If neither method is selected, handle() chooses check_message when a non-empty message is set and check_newuser otherwise. ```php $cleantalk_antispam->useRegistrationCheck(); ``` -------------------------------- ### request Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Request.md Executes the HTTP request(s) and returns the processed content, an error array, or true for async preset. Handles single and multiple URLs, presets, and callbacks. ```APIDOC ## request ### Description Executes the HTTP request(s) and returns the processed content, an error array, or true for async preset. Handles single and multiple URLs, presets, and callbacks. ### Method request ### Signature public function request() ### Parameters None. ### Returns `array|bool` — see below. Possible returns: - **Single URL, success:** the processed content (e.g. `string`, or whatever the callbacks produced) — the first element of the internal responses list via `reset()`. - **Multiple URLs, success (2+ responses):** an array keyed by URL with each processed content. - **Error:** the error array `array('error' => '')` (e.g. `CURL_NOT_INSTALLED`, `URL_IS_NOT_SET`, a `curl_error()` string, or `Response::getError()` content with the `retry_with_socket` preset). - **`async` preset:** request result is coerced to `true` for each URL. ### Request Flow From source: verify cURL exists → verify URL set → `convertOptionsTocURLFormat()` → `appendOptionsObligatory()` → `processPresets()` → `requestSingle()` or `requestMulti()` → optional socket retry → `runCallbacks()`. ### Default cURL Options From `appendOptionsObligatory` (line 426): - `CURLOPT_TIMEOUT = 50` - `CURLOPT_LOW_SPEED_TIME = 25` - `CURLOPT_RETURNTRANSFER = true` - `CURLOPT_CONNECTTIMEOUT = 30` - `CURLOPT_FORBID_REUSE = true` - `CURLOPT_USERAGENT = AGENT` - `CURLOPT_POST = true` - `CURLOPT_SSL_VERIFYPEER = false` - `CURLOPT_SSL_VERIFYHOST = 0` - `CURLOPT_FOLLOWLOCATION = true` - `CURLOPT_MAXREDIRS = 5` - No-cache HTTP headers: `Expect:`, `Expires:` 1971, `Cache-Control: no-store, no-cache, must-revalidate`, `Pragma: no-cache` ### Examples Basic POST and error handling: ```php use CleanTalk\HTTP\Request; $http = new Request(); $result = $http->setUrl('https://moderate.cleantalk.org/api2.0') ->setData(array('foo' => 'bar')) ->request(); if (isset($result['error'])) { error_log('Request failed: ' . $result['error']); // e.g. CURL_NOT_INSTALLED } ``` GET with presets, response code, and a custom callback with the `Response` object: ```php $http = new Request(); $result = $http->setUrl('https://example.com') ->setData(array('q' => 'spam')) // appended to the URL by the 'get' preset ->setPresets(array('get', 'get_code', 'dont_follow_redirects')) ->request(); // $result is the HTTP status code (int) because of the 'get_code' internal callback. $http2 = (new Request()) ->setUrl('https://example.com/check') ->addCallback(function ($response, $url) { // $response is the Response object because $pass_response = true return 'HTTP ' . $response->getResponseCode() . ' for ' . $url; }, array(), 10, true); $result2 = $http2->request(); ``` ``` -------------------------------- ### Add CleanTalk handler to PHP form handler Source: https://github.com/cleantalk/php-antispam/blob/master/README.md Initialize the CleantalkAntispam class with the API key from the environment, set the email from the form, and call handle(). Throws an exception if the API key is not configured. ```php $api_key = getenv('CLEANTALK_API_KEY'); if (empty($api_key)) { throw new RuntimeException('CLEANTALK_API_KEY is not configured'); } $email = $_POST['email']; // Get this value from your form. $cleantalk_antispam = (new CleantalkAntispam($api_key)) ->setEmail($email); // Set additional parameters here. $api_result = $cleantalk_antispam->handle(); ``` -------------------------------- ### setData Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Request.md Sets the POST (or GET) data for the request. Scalar non-JSON values are converted to `array((string)$data => 1)`; JSON strings are passed through; arrays are used as-is. Returns the current instance for chaining. ```APIDOC ## setData ### Description Sets the POST (or GET) data for the request. Scalar non-JSON values are converted to `array((string)$data => 1)`; JSON strings are passed through; arrays are used as-is. ### Method N/A (fluent setter) ### Endpoint N/A ### Parameters #### Path Parameters None. #### Query Parameters None. #### Request Body - **$data** (array|string|scalar) - Required - POST (or GET) data. ### Request Example ```php $request->setData(['key' => 'value']); ``` ### Response #### Success Response (200) - **$this** (Request) - Returns the current instance for chaining. #### Response Example ```php $request->setData(['key' => 'value']); ``` ``` -------------------------------- ### Get decoded request data with getCleanTalkRequestData Source: https://github.com/cleantalk/php-antispam/blob/master/readme_additional.md Retrieves the decoded request data after handle() has prepared a request, for custom diagnostics. The data may contain personal information, so store it only in protected logs and remove temporary logging when done. ```php $request_data = $cleantalk_antispam->getCleanTalkRequestData(); ``` -------------------------------- ### new CleantalkAntispam($accessKey, $email, $user_name_field, $message_field, $type_form) Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/CleantalkAntispam.md Creates a new CleantalkAntispam instance. Initializes internal state, copies POST data, reads event token, and detects sender IP. Access key validation is deferred to the handle() method. ```APIDOC ## new CleantalkAntispam($accessKey, $email, $user_name_field, $message_field, $type_form) ### Description Creates a new CleantalkAntispam instance. Initializes an empty CleantalkVerdict, copies $_POST data into the internal container, reads the event token if present, and detects the sender IP. Access key validation is not performed here but in the handle() method. ### Method Constructor ### Signature ```php public function __construct($accessKey, $email = '', $user_name_field = '', $message_field = '', $type_form = '') ``` ### Parameters #### Parameters - **$accessKey** (string) - Required - CleanTalk API access key from your CleanTalk dashboard. - **$email** (string) - Optional - Sender email. If empty, the constructor scans $_POST for the first value matching EMAIL_ADDRESS_REGEXP. - **$user_name_field** (string) - Optional - Legacy, unused by the current implementation. - **$message_field** (string) - Optional - Legacy, unused by the current implementation. - **$type_form** (string) - Optional - Legacy, unused by the current implementation. ### Request Example ```php $cleantalk_antispam = new CleantalkAntispam($api_key, $email); ``` ### Response #### Success Response No return value. The constructor initializes the object. ### Notes - Throws no exceptions; access-key validation happens in handle(). - Automatically detects sender IP via CleanTalk\HTTP\Helper::ipGet(). ``` -------------------------------- ### Constructor signature Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-CleantalkResponse.md The constructor accepts an optional JSON-decoded response object, failed URLs, and an error string. All parameters are optional and default to null. It does not throw exceptions. ```php public function __construct($obj = null, $failed_urls = null, $error = null) ``` -------------------------------- ### setOptions Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Request.md Sets cURL options for the request. Accepts simple names or raw CURLOPT_* integer keys. Returns the Request instance for chaining. ```APIDOC ## setOptions ### Description Sets cURL options for the request. Accepts simple names or raw CURLOPT_* integer keys. Returns the Request instance for chaining. ### Method setOptions ### Signature public function setOptions($options) ### Parameters - **$options** (array) - Required - Options in simple-name form (`timeout`, `sslverify`, `sslcertificates`, `headers`, `user-agent`) or raw `CURLOPT_*` integer keys; simple names survive `convertOptionsTocURLFormat()` only if their value is truthy ### Returns `Request` (`$this`). Non-integer option keys that are not one of the supported simple names are silently dropped. ``` -------------------------------- ### whatsWrong($return_as_json = false) Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/CleantalkAntispam.md Provides diagnostic information about the last request. When $return_as_json is true, returns a JSON string; otherwise echoes HTML div blocks and returns an empty string. ```APIDOC ## whatsWrong($return_as_json = false) ### Description Returns diagnostic information about the last request. When `$return_as_json` is `true`, returns a JSON string; otherwise echoes three HTML `
` blocks (suggestions, request data, verdict) and returns `''`. ### Method N/A (PHP method) ### Endpoint N/A (PHP method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **$return_as_json** (bool) - Optional - Default: `false` - When `true`, returns a JSON string instead of echoing diagnostics. ### Request Example ```php // JSON diagnostics for structured logging (intended for troubleshooting; contains personal data) $api_result = $cleantalk_antispam->handle(); error_log($cleantalk_antispam->whatsWrong(true)); // Human-readable HTML diagnostics (echoed to the browser) $cleantalk_antispam->whatsWrong(); // echoes
Suggestions
...
... ``` ### Response #### Success Response - When `$return_as_json` is `true`: Returns a JSON string with shape `{"suggestions": ..., "request_data": ..., "verdict": ...}`. If no verdict exists, `verdict` is the string `"Verdict is not processed. Maybe you forgot to call ->getVerdict() method before"`. Suggestion arrays are keyed by level (`critical`, `average`). - When `$return_as_json` is `false`: Echoes three HTML `
` blocks and returns `''`. #### Response Example ```json { "suggestions": { "critical": ["..."], "average": ["..."] }, "request_data": {}, "verdict": "Verdict is not processed. Maybe you forgot to call ->getVerdict() method before" } ``` ### Error Handling No explicit error handling documented. Note: The returned data contains personal data. ``` -------------------------------- ### Echo HTML diagnostics with whatsWrong() Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/CleantalkAntispam.md Call whatsWrong() without arguments to echo human-readable HTML diagnostics to the browser. It outputs three
blocks (suggestions, request data, verdict) and returns an empty string. ```php $cleantalk_antispam->whatsWrong(); // echoes
Suggestions
...
... ``` -------------------------------- ### getPlatformServerAddr method signature Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Helper.md Returns a valid IP address from $_SERVER['SERVER_ADDR'], $_SERVER['LOCAL_ADDR'] (IIS), or $_SERVER['HTTP_HOST'] with port stripped, in that order. Returns null if none are available. ```php public static function getPlatformServerAddr() ``` -------------------------------- ### Retrieve request data with getCleanTalkRequestData() Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/CleantalkAntispam.md Call handle() first to prepare request data, then retrieve it with getCleanTalkRequestData(). The returned data is JSON-decoded and contains personal data (email, message, IP, headers). ```php $cleantalk_antispam->handle(); $request_data = $cleantalk_antispam->getCleanTalkRequestData(); error_log(print_r($request_data, true)); // method_name, auth_key, sender_email, ... ``` -------------------------------- ### Response::__construct Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Response.md Constructor for the Response class, accepting raw result and cURL info. ```APIDOC ## Constructor ### Description Creates a new Response instance wrapping a raw HTTP transaction result and its cURL info array. ### Method Constructor ### Signature `public function __construct($raw, $info)` ### Parameters - **$raw** (string|array) - Required - Raw request result: the response body, or an error array (e.g. `array('error' => curl_error($ch))`; `error` is set to `$raw` when `!empty($raw['error'])`) - **$info** (array) - Required - cURL info array from `curl_getinfo()`; `http_code` is read into `response_code` when present ### Returns None ``` -------------------------------- ### Declare ipGet method signature Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Helper.md Defines the public static ipGet method with parameters for IP type, IPv4-only flag, and pre-fetched headers. Returns string|null. ```php public static function ipGet($ip_type_to_get = 'real', $v4_only = true, $headers = array()) ``` -------------------------------- ### setDoBlockNoJSVisitor() Source: https://github.com/cleantalk/php-antispam/blob/master/readme_additional.md Configures the library to block visitors who do not provide a valid event token, which is useful when the application requires JavaScript. When enabled, handle() returns a blocked verdict without sending an API request if the token is absent or invalid. ```APIDOC ## setDoBlockNoJSVisitor() ### Description Configures the library to block visitors who do not provide a valid event token, which is useful when the application requires JavaScript. When enabled, handle() returns a blocked verdict without sending an API request if the token is absent or invalid. ### Method setDoBlockNoJSVisitor ### Parameters None ### Request Example ```php $cleantalk_antispam->setDoBlockNoJSVisitor(); ``` ``` -------------------------------- ### useRegistrationCheck Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/CleantalkAntispam.md Selects the `check_newuser` CleanTalk API method for registration and subscription forms that do not contain user-written text. ```APIDOC ## useRegistrationCheck ### Description Selects the `check_newuser` CleanTalk API method (registrations, subscriptions — forms without user-written text). ### Method useRegistrationCheck ### Endpoint `public function useRegistrationCheck()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $cleantalk_antispam->useRegistrationCheck(); ``` ### Response #### Success Response (200) - **$this** - Returns the current instance for method chaining. #### Response Example No response body is returned; the method returns the object instance. ``` -------------------------------- ### setUrl method Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Request.md Sets the URL or array of URLs for the request. Returns the Request instance for chaining. ```php public function setUrl($url) ``` -------------------------------- ### handle() Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/CleantalkAntispam.md Executes the spam check flow: validates credentials, sends request to CleanTalk, and returns a verdict. Errors are captured in the verdict object rather than thrown. ```APIDOC ## handle() ### Description Processes a spam check by validating the access key and event token, sending the request to the CleanTalk moderate server, and returning a verdict object. Errors are captured in the verdict's error field instead of being thrown. ### Method handle ### Endpoint lib/CleantalkAntispam.php:490 ### Parameters None ### Returns - **\CleanTalk\CleantalkVerdict** - Always returns a verdict object; errors are captured in `$verdict->error` rather than thrown. ### Processing Order 1. **verifyData()** - Validates the access key and event token. - Access-key failure → `verdict->error = message`, `verdict->allow = 1` (request is allowed). - Event-token failure → if `block_no_js_visitor` is enabled: `allow = 0`, `comment = 'Please, enable JavaScript to process the form.'`; otherwise `allow = 1`. 2. If `verdict->error` is set after verification, returns the verdict without calling the API. 3. Resolves `method_name`: explicit `useRegistrationCheck()`/`useContactFormCheck()` wins; otherwise `check_newuser` (empty message) or `check_message` (non-empty message). 4. Sends the request to `MODERATE_URL`; a transport failure sets `verdict->error = 'CleanTalk moderate server error: ' . `. 5. Copies `allow` and `comment` from the API response and builds `request_link = 'https://cleantalk.org/my/show_requests?request_id=' . ` (only when the response `id` is non-empty). 6. Normalizes `allow` to `(int) (bool)` and computes improvement suggestions. ### Examples Basic contact-form handling and verdict check: ```php $api_result = $cleantalk_antispam->handle(); if ($api_result->allow === 0) { die('Blocked. Spam protection OK. Reason: ' . $api_result->comment); } // allow === 1: legit submission, continue processing ``` Error-tolerant handling — the library never throws from `handle()`, so inspect the verdict fields: ```php $api_result = $cleantalk_antispam->handle(); if (!empty($api_result->error)) { error_log('CleanTalk check failed: ' . $api_result->error); // Decide policy: e.g. fail-open and process, or fail-closed and block. if ($api_result->allow === 0) { // Blocked: no valid event token and setDoBlockNoJSVisitor() is on. } } ``` ``` -------------------------------- ### useRegistrationCheck method and usage Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/CleantalkAntispam.md Selects the check_newuser CleanTalk API method for registrations and subscriptions (forms without user-written text). Returns $this for chaining. ```php public function useRegistrationCheck() ``` ```php $cleantalk_antispam->useRegistrationCheck(); ``` -------------------------------- ### Basic CleantalkAntispam construction Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/CleantalkAntispam.md Basic construction with an explicit email. The constructor copies $_POST into data_container and detects the sender IP via CleanTalk\HTTP\Helper::ipGet(). ```php $cleantalk_antispam = new CleantalkAntispam($api_key, $email); ``` -------------------------------- ### ipV6Reduce method signature Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Helper.md Compresses an IPv6 address by removing zero hextets and collapsing repeated ::. ```php public static function ipV6Reduce($ip) ``` -------------------------------- ### Accessing Response via Request Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Response.md Shows how to access the Response object from a Request instance. The Request object must be kept to reach the raw Response. ```php use CleanTalk\HTTP\Request; $http = (new Request()) ->setUrl('https://example.com/api') ->setData(array('k' => 'v')); // Keep the Request object around so the raw Response stays reachable: $result = $http->request(); // processed content (string) $responses = $http->response; // Response object (single URL) or array if ($responses instanceof Response) { $code = $responses->getResponseCode(); } ``` -------------------------------- ### Basic contact-form handling with handle() Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/CleantalkAntispam.md Basic usage of handle() for a contact form. Checks the verdict's allow property; if 0, blocks the request and prints the reason from comment. If allow is 1, the submission is legitimate and processing continues. ```php $api_result = $cleantalk_antispam->handle(); if ($api_result->allow === 0) { die('Blocked. Spam protection OK. Reason: ' . $api_result->comment); } // allow === 1: legit submission, continue processing ``` -------------------------------- ### Helper::ipGet Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Helper.md Static method to detect the client IP address based on a chosen source strategy and optional IPv4-only filtering. ```APIDOC ## ipGet ### Description Detects the client IP address based on the specified source strategy and optional IPv4-only filtering. Returns the detected IP as a string, or null if no valid IP is found. ### Method Static method call: `Helper::ipGet()` ### Parameters - `$ip_type_to_get` (string) - Optional - Source strategy: `real`, `cloud_flare`, `gtranslate`, `ezoic`, `sucury`, `x_forwarded_by`, `stackpath`, `ico_x_forwarded_for`, `ovh`, `incapsula`, `clientside`, `remote_addr`, `x_forwarded_for`, `x_real_ip`; anything else falls back to `real`. - `$v4_only` (bool) - Optional - When true, IPv6 results are discarded (null). - `$headers` (array) - Optional - Pre-fetched headers; when empty, `httpGetHeaders()` is used. ### Returns - `string|null` - The detected IP address, or null when none of the sources yield a valid (and IPv4, if `$v4_only`) address. ### Example ```php $ip = Helper::ipGet(); // 'real', IPv4 only $ip6 = Helper::ipGet('real', false); // allow IPv6 $cf = Helper::ipGet('cloud_flare'); // only Cloudflare headers ``` ``` -------------------------------- ### Error-tolerant handling with handle() Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/CleantalkAntispam.md Error-tolerant handling of handle(). Since the method never throws, inspect the error property to log failures and decide a policy. If allow is 0, the request is blocked, typically due to a missing event token with setDoBlockNoJSVisitor() enabled. ```php $api_result = $cleantalk_antispam->handle(); if (!empty($api_result->error)) { error_log('CleanTalk check failed: ' . $api_result->error); // Decide policy: e.g. fail-open and process, or fail-closed and block. if ($api_result->allow === 0) { // Blocked: no valid event token and setDoBlockNoJSVisitor() is on. } } ``` -------------------------------- ### Configure Registration Check with CleantalkAntispam Source: https://github.com/cleantalk/php-antispam/blob/master/readme_additional.md Use for sign-up, subscription, or similar forms without a user-written message. It calls the CleanTalk check_newuser API method and expects $email and $name to be already validated by your application. ```php $cleantalk_antispam = (new CleantalkAntispam($api_key)) ->useRegistrationCheck() ->setEmail($email) ->setNickName($name); $api_result = $cleantalk_antispam->handle(); ``` -------------------------------- ### ipV6Normalize method signature Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Helper.md Expands and normalizes an IPv6 address. Maps ::ffff:a.b.c.d to an IPv6 form, expands :: to full hextets, and removes leading zeros. Recursive. ```php public static function ipV6Normalize($ip) ``` -------------------------------- ### Echo frontend HTML code Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/CleantalkAntispam.md Outputs the HTML script tag for the CleanTalk Bot Detector. The comment shows the expected output. ```php echo CleantalkAntispam::getFrontendHTMLCode(); // ``` -------------------------------- ### Improvement suggestions array structure Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/types.md Structure of the suggestions array returned by `whatsWrong(true)` under the `suggestions` key. Each level key ('critical' or 'average') maps to a list of entries with a `stack` (string or null) and a `message`. When no suggestions exist, the array is `array('Everything looks well!')`. ```php array( '' => array( array('stack' => , 'message' => ), // ... ), // level keys: 'critical' | 'average' (ksort(SORT_STRING) applied) ) ``` -------------------------------- ### Using getJSON() to serialize a verdict Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/CleantalkVerdict.md Shows how to obtain the JSON string from a verdict object. The comment shows the expected output for a default verdict. ```php $verdict = $cleantalk_antispam->handle(); $json = $verdict->getJSON(); $json; // {"allow":1,"comment":"","error":"","request_link":null} ``` -------------------------------- ### getInfo method signature Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Response.md Signature for the getInfo method. Returns the cURL info array passed to the constructor. ```php public function getInfo() ``` -------------------------------- ### Constructor signature Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Response.md Signature for the Response constructor. Takes the raw request result (string or error array) and the cURL info array from curl_getinfo(). ```php public function __construct($raw, $info) ``` -------------------------------- ### Set API key in .env file Source: https://github.com/cleantalk/php-antispam/blob/master/README.md Add the CLEANTALK_API_KEY environment variable to your .env file. This requires a dotenv loader in your application. ```dotenv CLEANTALK_API_KEY=your-api-key ``` -------------------------------- ### Response::getContentRaw Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Response.md Retrieves the raw content of the response. ```APIDOC ## getContentRaw ### Description Returns the original raw request result. ### Method Method ### Signature `public function getContentRaw()` ### Parameters None ### Returns - **mixed** - The original raw request result. ``` -------------------------------- ### setIP Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/CleantalkAntispam.md Overrides the auto-detected sender IP address. ```APIDOC ## setIP ### Description Overrides the auto-detected sender IP. Use only when the application already resolved the visitor IP (e.g. behind a trusted proxy). ### Method GET ### Endpoint `CleantalkAntispam::setIP($ip = null)` ### Parameters #### Parameters - **$ip** (string|null) - Optional - Overrides the auto-detected sender IP. If invalid, the current IP is kept and a critical improvement suggestion is recorded. ### Request Example ```php if (filter_var($visitor_ip, FILTER_VALIDATE_IP)) { $cleantalk_antispam->setIP($visitor_ip); } ``` ### Response #### Success Response (200) - **$this** - Returns the current instance for method chaining. #### Response Example ```php $this ``` ``` -------------------------------- ### Block non-JS visitors with setDoBlockNoJSVisitor Source: https://github.com/cleantalk/php-antispam/blob/master/readme_additional.md Call this method to locally block visitors without a valid event token. When enabled, handle() returns a blocked verdict without sending an API request if the token is absent or invalid. ```php $cleantalk_antispam->setDoBlockNoJSVisitor(); ``` -------------------------------- ### fromUTF8 method signature Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Helper.md Converts a value (string, array, or object) to the specified codepage. If $data_codepage is provided and the string is valid UTF-8, it uses mb_convert_encoding() when available, falling back to utf8_decode() on PHP < 8.3. Non-UTF-8 strings are returned unchanged. ```php public static function fromUTF8($obj, $data_codepage = null) ``` -------------------------------- ### Direct construction and usage Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-CleantalkResponse.md Shows how to create a CleantalkResponse from a JSON-decoded response body and check for transport errors or API errors. The comment property contains a formatted error message when errno is non-zero. ```php $body = json_decode($raw_api_response_body); $response = new CleantalkResponse($body); if ($response->error) { // Transport error path. } if ($response->errno !== 0) { echo $response->comment; // '*** Anti-Spam service cleantalk.org ***' } ``` -------------------------------- ### addCallback Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Request.md Adds a callback to be fired for each request result after a successful request, in priority order. Returns the Request instance for chaining. ```APIDOC ## addCallback ### Description Adds a callback to be fired for each request result after a successful request, in priority order. Returns the Request instance for chaining. ### Method addCallback ### Signature public function addCallback($callback, $arguments = array(), $priority = null, $pass_response = false) ### Parameters - **$callback** (callable) - Required - Fired for each request result after a successful request, in priority order - **$arguments** (array) - Optional - Default: `array()` - Extra arguments passed to the callback after the content (or Response) and URL - **$priority** (int|null) - Optional - Default: `null` - Sort key (`100` if not given); colliding priorities are incremented until free - **$pass_response** (bool) - Optional - Default: `false` - When `true`, the `Response` object is passed as the first argument instead of the processed content ### Returns `Request` (`$this`). ``` -------------------------------- ### Include Bot Detector script in HTML Source: https://github.com/cleantalk/php-antispam/blob/master/readme_additional.md Add this script to the HTML page containing the form to enable Bot Detector functionality. It should be loaded with defer. ```html ``` -------------------------------- ### Enable event token processing with setEventTokenEnabled Source: https://github.com/cleantalk/php-antispam/blob/master/readme_additional.md Enable event-token processing in the PHP request. Do not set this flag for forms that do not use Bot Detector. ```php $cleantalk_antispam->setEventTokenEnabled(1); ``` -------------------------------- ### Public property: $response Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Request.md Exposes the Response object or array of Response objects after request() runs. ```APIDOC ## Public property: $response ### Description Holds the Response object (single URL) or array of Response objects keyed by URL (multi request) after request() runs. Exposed for debugging; request() returns the processed content instead. ### Method GET ### Endpoint Request::$response ### Parameters None ### Request Example ```php $request = new Request(); $request->request(); $response = $request->response; ``` ### Response #### Success Response (200) - **$response** (Response|array) - The Response object or array of Response objects. #### Response Example ```php Response object ``` ``` -------------------------------- ### setMessage Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/CleantalkAntispam.md Sets the user-generated content to be checked for spam. ```APIDOC ## setMessage ### Description Sets the user-generated content to check, which is sent to the API as `message`. A non-empty message also influences automatic method-name selection inside `handle()`. ### Method GET ### Endpoint `CleantalkAntispam::setMessage($message)` ### Parameters #### Parameters - **$message** (string) - Required - User-generated content to check; sent to the API as `message`. Non-string values are stored as `null`. ### Request Example ```php $cleantalk_antispam->setMessage($subject . ': ' . $body); ``` ### Response #### Success Response (200) - **$this** - Returns the current instance for method chaining. #### Response Example ```php $this ``` ``` -------------------------------- ### appendParametersToURL method signature Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Request.md Static method that appends query parameters to a URL. Accepts a base URL and parameters as a string or array; arrays are converted using http_build_query(). Returns the URL with '?' or '&' appended, or the original URL if parameters are empty. ```php public static function appendParametersToURL($url, $parameters) ``` -------------------------------- ### setDoBlockNoJSVisitor Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/CleantalkAntispam.md Enables blocking of visitors without JavaScript when the event token is missing or invalid. ```APIDOC ## setDoBlockNoJSVisitor ### Description When enabled, `handle()` returns a blocked verdict (without calling the API) if the event token is missing or invalid. Default behavior without this call: visitors without a token are allowed (`allow = 1`). ### Method GET ### Endpoint `CleantalkAntispam::setDoBlockNoJSVisitor()` ### Parameters None ### Request Example ```php $cleantalk_antispam->setDoBlockNoJSVisitor(); ``` ### Response #### Success Response (200) - **$this** - Returns the current instance for method chaining. #### Response Example ```php $this ``` ``` -------------------------------- ### setUrl Source: https://github.com/cleantalk/php-antispam/blob/master/_autodocs/api-reference/HTTP-Request.md Sets the URL or URLs for the request. Accepts a single URL string or an array of URLs for a multi-request (cURL multi). Returns the current instance for chaining. ```APIDOC ## setUrl ### Description Sets the URL or URLs for the request. Accepts a single URL string or an array of URLs for a multi-request (cURL multi). ### Method N/A (fluent setter) ### Endpoint N/A ### Parameters #### Path Parameters None. #### Query Parameters None. #### Request Body - **$url** (string|string[]) - Required - Single URL or array of URLs. ### Request Example ```php $request->setUrl('https://example.com'); ``` ### Response #### Success Response (200) - **$this** (Request) - Returns the current instance for chaining. #### Response Example ```php $request->setUrl('https://example.com'); ``` ```