PHP Examples
Ready-to-use PHP code to integrate CaptchaKings API into your application.
š¦ Requirements: PHP 7.0+ with cURL extension (usually enabled by default)
Quick Start (Recommended)
The easiest way to integrate is using our official PHP library. Download CaptchaKings.php
php
<?php
require_once 'CaptchaKings.php';
try {
// Initialize with your API Key
$ck = new CaptchaKings('ck_your_api_key_here');
// Solve CAPTCHA
$result = $ck->solve('/path/to/captcha.jpg');
if ($result['success']) {
echo "Prediction: " . $result['data']['prediction'];
} else {
echo "Error: " . $result['error'];
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
Raw PHP Example
Here's the simplest way to solve a CAPTCHA with PHP:
php
<?php
$apiKey = 'ck_your_api_key_here';
$imagePath = '/path/to/captcha.jpg';
// Initialize cURL
$ch = curl_init('https://captchakings.com/api/process.php');
// Set options
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => [
'captcha' => new CURLFile($imagePath)
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey
]
]);
// Execute
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Parse response
$result = json_decode($response, true);
if ($httpCode === 200 && $result['success']) {
echo "ā
CAPTCHA Solved: " . $result['data']['prediction'] . "\n";
echo "Confidence: " . $result['data']['confidence'] . "\n";
echo "Credits Remaining: " . $result['credits']['credits_remaining'] . "\n";
} else {
echo "ā Error: " . ($result['error'] ?? 'Unknown error') . "\n";
}
?>
Complete Example with Error Handling
Production-ready code with comprehensive error handling:
php
<?php
function solveCaptcha($apiKey, $imagePath) {
$url = 'https://captchakings.com/api/process.php';
// Validate file exists
if (!file_exists($imagePath)) {
return [
'success' => false,
'error' => 'File not found: ' . $imagePath
];
}
// Prepare cURL request
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => [
'captcha' => new CURLFile(
$imagePath,
mime_content_type($imagePath),
'captcha.jpg'
)
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey
],
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => true
]);
// Execute request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
// Handle cURL errors
if ($curlError) {
return [
'success' => false,
'error' => 'Connection error: ' . $curlError
];
}
// Parse JSON response
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return [
'success' => false,
'error' => 'Invalid JSON response: ' . json_last_error_msg()
];
}
// Handle HTTP errors
if ($httpCode !== 200) {
return [
'success' => false,
'error' => $data['error'] ?? 'Unknown error (HTTP ' . $httpCode . ')'
];
}
return $data;
}
// Usage Example
$apiKey = 'ck_your_api_key_here';
$imagePath = '/path/to/captcha.jpg';
$result = solveCaptcha($apiKey, $imagePath);
if ($result['success']) {
echo "ā
CAPTCHA Solved!\n";
echo "āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n";
echo "Prediction: " . $result['data']['prediction'] . "\n";
echo "Confidence: " . $result['data']['confidence'] . "\n";
echo "Process Time: " . $result['data']['process_time'] . "s\n";
echo "āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n";
echo "Credits Deducted: " . $result['credits']['credits_deducted'] . "\n";
echo "Credits Remaining: " . $result['credits']['credits_remaining'] . "\n";
echo "Plan: " . $result['credits']['plan'] . "\n";
} else {
echo "ā Error: " . $result['error'] . "\n";
// Handle specific errors
if (strpos($result['error'], 'Invalid API key') !== false) {
echo "\nš” Tip: Check your API key in the dashboard\n";
echo " URL: https://captchakings.com/dashboard\n";
} elseif (strpos($result['error'], 'Insufficient credits') !== false) {
echo "\nš” Tip: Please top up your credits\n";
echo " URL: https://captchakings.com/dashboard#credits\n";
}
}
?>
Class-Based Implementation
Object-oriented approach for better code organization:
php
<?php
class CaptchaKingsAPI {
private $apiKey;
private $baseUrl = 'https://captchakings.com/api/process.php';
public function __construct($apiKey) {
$this->apiKey = $apiKey;
}
public function solve($imagePath) {
if (!file_exists($imagePath)) {
throw new Exception('Image file not found: ' . $imagePath);
}
$ch = curl_init($this->baseUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => [
'captcha' => new CURLFile($imagePath)
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $this->apiKey
],
CURLOPT_TIMEOUT => 30
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
throw new Exception('cURL error: ' . $error);
}
$data = json_decode($response, true);
if ($httpCode !== 200 || !$data['success']) {
throw new Exception($data['error'] ?? 'API request failed');
}
return $data;
}
public function getCredits() {
// You can implement this to check remaining credits
// without solving a CAPTCHA
}
}
// Usage
try {
$api = new CaptchaKingsAPI('ck_your_api_key_here');
$result = $api->solve('/path/to/captcha.jpg');
echo "Solved: " . $result['data']['prediction'] . "\n";
echo "Credits: " . $result['credits']['credits_remaining'] . "\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
?>
Laravel Integration
If you're using Laravel, here's how to integrate:
1. Create Service Class
php
<?php
// app/Services/CaptchaKingsService.php
namespace App\Services;
use Illuminate\Support\Facades\Http;
class CaptchaKingsService
{
protected $apiKey;
protected $baseUrl = 'https://captchakings.com/api/process.php';
public function __construct()
{
$this->apiKey = config('services.captchakings.api_key');
}
public function solve($imagePath)
{
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $this->apiKey
])->attach(
'captcha',
file_get_contents($imagePath),
'captcha.jpg'
)->post($this->baseUrl);
if (!$response->successful()) {
throw new \Exception('API request failed: ' . $response->json('error'));
}
return $response->json();
}
}
?>
2. Add to config/services.php
php
return [
// ...
'captchakings' => [
'api_key' => env('CAPTCHAKINGS_API_KEY'),
],
];
3. Add to .env
bash
CAPTCHAKINGS_API_KEY=ck_your_api_key_here
4. Use in Controller
php
<?php
namespace App\Http\Controllers;
use App\Services\CaptchaKingsService;
use Illuminate\Http\Request;
class CaptchaController extends Controller
{
protected $captchaService;
public function __construct(CaptchaKingsService $captchaService)
{
$this->captchaService = $captchaService;
}
public function solve(Request $request)
{
$request->validate([
'captcha_image' => 'required|image|max:5120'
]);
try {
$result = $this->captchaService->solve(
$request->file('captcha_image')->path()
);
return response()->json([
'success' => true,
'prediction' => $result['data']['prediction'],
'confidence' => $result['data']['confidence'],
'credits_remaining' => $result['credits']['credits_remaining']
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'error' => $e->getMessage()
], 400);
}
}
}
?>
WordPress Integration
For WordPress plugins or themes:
php
<?php
function solve_captcha_with_captchakings($image_path) {
$api_key = get_option('captchakings_api_key');
$url = 'https://captchakings.com/api/process.php';
$response = wp_remote_post($url, [
'headers' => [
'Authorization' => 'Bearer ' . $api_key
],
'body' => [
'captcha' => new CURLFile($image_path)
],
'timeout' => 30
]);
if (is_wp_error($response)) {
return [
'success' => false,
'error' => $response->get_error_message()
];
}
$data = json_decode(wp_remote_retrieve_body($response), true);
return $data;
}
// Usage
$result = solve_captcha_with_captchakings('/path/to/captcha.jpg');
if ($result['success']) {
echo 'CAPTCHA solved: ' . $result['data']['prediction'];
} else {
echo 'Error: ' . $result['error'];
}
?>
Common Use Cases
Batch Processing
Process multiple CAPTCHAs in sequence:
php
<?php
$apiKey = 'ck_your_api_key_here';
$images = glob('/path/to/captchas/*.jpg');
$results = [];
foreach ($images as $image) {
echo "Processing: " . basename($image) . "...\n";
$result = solveCaptcha($apiKey, $image);
if ($result['success']) {
$results[] = [
'file' => basename($image),
'prediction' => $result['data']['prediction'],
'confidence' => $result['data']['confidence']
];
echo "ā Solved: " . $result['data']['prediction'] . "\n";
} else {
echo "ā Error: " . $result['error'] . "\n";
}
// Be nice to the API - small delay between requests
usleep(500000); // 0.5 second
}
echo "\n" . count($results) . " CAPTCHAs solved successfully!\n";
?>
With Retry Logic
Automatically retry failed requests:
php
<?php
function solveCaptchaWithRetry($apiKey, $imagePath, $maxRetries = 3) {
$attempts = 0;
while ($attempts < $maxRetries) {
$attempts++;
$result = solveCaptcha($apiKey, $imagePath);
if ($result['success']) {
return $result;
}
// Don't retry if it's an authentication or credit error
if (strpos($result['error'], 'Invalid API key') !== false ||
strpos($result['error'], 'Insufficient credits') !== false) {
return $result;
}
echo "Attempt $attempts failed, retrying...\n";
sleep(2); // Wait 2 seconds before retry
}
return $result;
}
$result = solveCaptchaWithRetry('ck_your_api_key_here', '/path/to/captcha.jpg');
?>
Tips & Best Practices
- Store API keys securely - Use environment variables, never hardcode
- Handle errors gracefully - Always check for
successin response - Implement timeout - Set
CURLOPT_TIMEOUTto avoid hanging - Verify SSL - Always use
CURLOPT_SSL_VERIFYPEER => true - Check credits - Monitor
credits_remainingto avoid running out - Respect rate limits - Don't send too many requests at once