In questo articolo abbiamo cercato di rispondere a tutte le domande principali. Il primo passo per risolvere il problema è capire quale sistema di protezione viene utilizzato. A questo scopo puoi consultare l’elenco dei captcha e dei sistemi di protezione antibot più diffusi, dove trovi esempi visivi e caratteristiche chiave che ti aiutano a identificare rapidamente con cosa hai a che fare.
Se scopri che sul tuo sito viene utilizzato ComplexImage, il passo successivo è analizzarne più nel dettaglio le proprietà e il funzionamento. In questo stesso articolo puoi anche studiare la guida all’integrazione di ComplexImage, per comprendere a fondo come opera sul tuo sito. Questo ti permetterà non solo di capire la protezione attuale, ma anche di pianificarne correttamente la manutenzione.
Lavorare con CapMonster Cloud via API di solito prevede i seguenti passaggi:
type - ComplexImageTask
class - recognition
imagesBase64 - un array di immagini in formato base64. Esempio: [“/9j/4AAQSkZJRgABAQEAAAAAAAD…”];
Task (all'interno dei metadata) - nome del compito (ad esempio, dli).
https://api.capmonster.cloud/createTask{
"clientKey": "API_KEY",
"task": {
"type": "ComplexImageTask",
"class": "recognition",
"imagesBase64": [
"base64"
],
"metadata": {
"Task": "dli" // sostituisci con il task desiderato, l'elenco dei moduli disponibili è reperibile su https://docs.capmonster.cloud/docs/captchas/ComplexImageTask-Recognition/
}
}
}
{
"errorId":0,
"taskId":407533072
}https://api.capmonster.cloud/getTaskResult{
"clientKey":"API_KEY",
"taskId": 407533072
}
{
"solution":
{
"answer": "1",
"metadata": {
"AnswerType": "Text"
}
},
"cost": 0.0003,
"status": "ready",
"errorId": 0,
"errorCode": null,
"errorDescription": null
}
// npm install playwright @zennolab_com/capmonstercloud-client
// npx playwright install chromium
import { chromium } from 'playwright';
import { CapMonsterCloudClientFactory, ClientOptions, ComplexImageTaskRecognitionRequest } from '@zennolab_com/capmonstercloud-client';
const API_KEY = "YOUR_API_KEY";
const TARGET_URL = "https://example.com/captcha-page";
async function solveComplexImageTaskPlaywright() {
const browser = await chromium.launch({ headless: false });
const context = await browser.newContext();
const page = await context.newPage();
await page.goto(TARGET_URL);
// Trova l'immagine del CAPTCHA
const captchaHandle = await page.$('#captcha'); // sostituisci con il selettore reale
const captchaBase64 = await captchaHandle.evaluate(img => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
return canvas.toDataURL('image/png').split(',')[1];
});
console.log("Captcha base64:", captchaBase64.substring(0, 50) + "...");
const cmcClient = CapMonsterCloudClientFactory.Create(
new ClientOptions({ clientKey: API_KEY })
);
// Invia il CAPTCHA per il riconoscimento
const citRecognitionRequest = new ComplexImageTaskRecognitionRequest({
imagesBase64: [captchaBase64],
metaData: { Task: 'oocl_rotate' } // sostituisci con il tuo tipo di CAPTCHA
});
const result = await cmcClient.Solve(citRecognitionRequest);
console.log("Solution received:", result);
// Elaborazione della soluzione
const solution = result.solution;
if (!solution) {
console.error("No solution received");
return;
}
if (solution.metadata?.AnswerType === "Coordinate") {
// CAPTCHA con coordinate
const box = await captchaHandle.boundingBox();
for (const point of solution.answer) {
const clickX = box.x + point.X;
const clickY = box.y + point.Y;
console.log(`Clicking at: (${clickX}, ${clickY})`);
await page.mouse.click(clickX, clickY);
}
} else if (solution.metadata?.AnswerType === "Grid") {
// CAPTCHA Grid (array true/false)
const box = await captchaHandle.boundingBox();
const gridItems = await page.$$('#captcha_grid div'); // sostituisci con i selettori degli elementi della griglia
const answers = solution.answer;
for (let i = 0; i < answers.length; i++) {
if (answers[i] && gridItems[i]) {
const itemBox = await gridItems[i].boundingBox();
const clickX = itemBox.x + itemBox.width / 2;
const clickY = itemBox.y + itemBox.height / 2;
console.log(`Clicking grid item ${i} at: (${clickX}, ${clickY})`);
await page.mouse.click(clickX, clickY);
}
}
} else {
console.warn("Unknown captcha solution type:", solution.metadata?.AnswerType);
}
// Clic sul pulsante di conferma (se presente)
await page.click('#submit_button'); // sostituisci con il selettore reale del pulsante
console.log("Captcha solved.");
}
solveComplexImageTaskPlaywright().catch(console.error);
1. Generazione del CAPTCHA sul server.
2. Trasmissione del CAPTCHA al client
<!--CAPTCHA con griglia di immagini-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Grid CAPTCHA Demo</title>
<style>
#captchaGrid {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-gap: 10px;
margin-bottom: 10px;
}
.grid-item {
width: 100px;
height: 100px;
background-color: #eee;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
border: 2px solid transparent;
}
.grid-item.selected {
border-color: blue;
}
</style>
</head>
<body>
<h1>Grid CAPTCHA Demo</h1>
<div id="captchaGrid"></div>
<button id="submitBtn">Submit</button>
<button id="refreshBtn">Refresh CAPTCHA</button>
<p id="result"></p>
<script>
let captchaId;
let answers = []; // array true/false per i click
async function loadCaptcha() {
const res = await fetch('/captcha'); // Il server restituisce JSON con captchaId e array di immagini base64
const data = await res.json();
captchaId = data.captchaId;
answers = new Array(data.images.length).fill(false);
const grid = document.getElementById('captchaGrid');
grid.innerHTML = '';
data.images.forEach((imgBase64, i) => {
const div = document.createElement('div');
div.className = 'grid-item';
div.style.backgroundImage = `url('data:image/png;base64,${imgBase64}')`;
div.style.backgroundSize = 'cover';
div.addEventListener('click', () => {
answers[i] = !answers[i];
div.classList.toggle('selected', answers[i]);
});
grid.appendChild(div);
});
document.getElementById('result').textContent = '';
}
document.getElementById('refreshBtn').addEventListener('click', loadCaptcha);
document.getElementById('submitBtn').addEventListener('click', async () => {
const res = await fetch('/captcha/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ captchaId, answer: answers })
});
const data = await res.json();
document.getElementById('result').textContent = data.success ? 'Captcha passed!' : 'Captcha failed, try again.';
if (!data.success) loadCaptcha();
});
// Caricamento CAPTCHA all'avvio
loadCaptcha();
</script>
</body>
</html>
3. Inserimento della risposta da parte dell'utente
4. Invio della risposta al server:
5. Verifica sul server
<?php
session_start();
// TTL del CAPTCHA in secondi
define('CAPTCHA_TTL', 300); // 5 minuti
// Generazione immagine casuale
function generateCaptchaImage($text = null) {
$width = 100;
$height = 100;
if (!$text) {
$text = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZ23456789'), 0, 2);
}
$image = imagecreatetruecolor($width, $height);
// sfondo
$bgColor = imagecolorallocate($image, rand(180, 255), rand(180, 255), rand(180, 255));
imagefilledrectangle($image, 0, 0, $width, $height, $bgColor);
// testo
$textColor = imagecolorallocate($image, 0, 0, 0);
$fontSize = 15;
$fontFile = __DIR__ . '/Arial.ttf'; // percorso font TTF
if (file_exists($fontFile)) {
imagettftext($image, $fontSize, rand(-20,20), 10, 50, $textColor, $fontFile, $text);
} else {
imagestring($image, 5, 10, 40, $text, $textColor);
}
ob_start();
imagepng($image);
$imgData = ob_get_clean();
imagedestroy($image);
return base64_encode($imgData);
}
// Creazione CAPTCHA griglia
function generateGridCaptcha() {
$numImages = 9; // 3x3
$images = [];
$solution = [];
for ($i = 0; $i < $numImages; $i++) {
// Risoluzione casuale, immagine corretta o no (esempio)
$isCorrect = rand(0,1) === 1;
$solution[] = $isCorrect;
// Generazione immagine (possono essere aggiunti oggetti per CAPTCHA reali)
$text = $isCorrect ? 'OK' : 'NO';
$images[] = generateCaptchaImage($text);
}
return ['images' => $images, 'solution' => $solution];
}
// Endpoint generazione CAPTCHA
if ($_SERVER['REQUEST_METHOD'] === 'GET' && $_SERVER['REQUEST_URI'] === '/captcha') {
$captchaId = uniqid('captcha_', true);
$gridCaptcha = generateGridCaptcha();
$_SESSION['captchas'][$captchaId] = [
'solution' => $gridCaptcha['solution'],
'timestamp' => time()
];
header('Content-Type: application/json');
echo json_encode([
'captchaId' => $captchaId,
'images' => $gridCaptcha['images']
]);
exit;
}
// Endpoint verifica CAPTCHA
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER['REQUEST_URI'] === '/captcha/verify') {
$data = json_decode(file_get_contents('php://input'), true);
$captchaId = $data['captchaId'] ?? '';
$answer = $data['answer'] ?? [];
if (!isset($_SESSION['captchas'][$captchaId])) {
echo json_encode(['success' => false, 'message' => 'Captcha expired or not found']);
exit;
}
$captcha = $_SESSION['captchas'][$captchaId];
// Controllo TTL
if (time() - $captcha['timestamp'] > CAPTCHA_TTL) {
unset($_SESSION['captchas'][$captchaId]);
echo json_encode(['success' => false, 'message' => 'Captcha expired']);
exit;
}
// Controllo array true/false
$success = $captcha['solution'] === $answer;
// Rimuovere CAPTCHA dopo verifica
unset($_SESSION['captchas'][$captchaId]);
echo json_encode(['success' => $success]);
exit;
}
// 404
http_response_code(404);
echo 'Not found';
6. Passi successivi
Ulteriori consigli
Esegui test di carico (es. con k6 o JMeter) — con molte richieste:
Se ti trovi su un sito con CAPTCHA già installato o un altro sistema di protezione senza accesso al codice — nessun problema! È facile identificare la tecnologia. Per verificarne il funzionamento puoi usare CapMonster Cloud in un ambiente di test isolato per assicurarti che la logica e il processamento dei token siano corretti.
Per i CAPTCHA con immagini, identifica il sistema, studia il comportamento e assicurati che la protezione funzioni. L'articolo mostra come riconoscere il CAPTCHA con immagini ComplexImage e come integrarlo o riconfigurarlo per mantenere la protezione e controllarne il funzionamento.