PHP code example of dkh / captcha-generator

1. Go to this page and download the library: Download dkh/captcha-generator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dkh / captcha-generator example snippets


  // Default size: 3 and default difficulty level: 1
  $expression_captcha = new ExpressionCaptcha();
  $string_captcha = new StringCaptcha();
  
  // Specific size and difficulty level
  $size = 10;
  $level = 2;
  $another_expression_captcha = new ExpressionCaptcha($size, $level);
  

  $_SESSION['captcha'] = $captcha->solve();
  
  // Or in a way that is infrequent,
  // use static method *Captcha::solveString()
  $my_expression = '1+6:3-2*4';
  $_SESSION['my_captcha'] = ExpressionCaptcha::solveString($my_expression);
  

  $user_captcha_input = $_POST['captcha'] ?? '';
  $is_matched = $_SESSION['captcha'] === $user_captcha_input;
  

  $base64_image = $captcha->render();
  echo sprintf('<img src="data:image/png;base64,%s">', $base64_image);
  
  // Or in a way like this:
  $my_string = 'any will do?';
  $image_path = 'captcha.png';
  $base64_image_to_be_saved = Captcha::renderString($my_string);
  file_put_contents(
      $image_path,
      base64_decode($base64_image_to_be_saved)
  );
  echo sprintf('<img src="/%s">', $image_path);
  
  // Image rendered with some options
  $another_base64_image = $captcha->render([
      'height' => 50,
      'fill' => [0, 0, 0, 30],
      // The alpha channel is optional
      'color' => [255, 255, 255]
  ]);
  echo sprintf(
      '<img src="data:image/png;base64,%s">',
      $another_base64_image
  );
  

  

  \ExpressionCaptcha;

  session_start();

  // Verify user's captcha input
  if (isset($_POST['captcha']) && isset($_SESSION['captcha'])) {
      $is_matched = $_POST['captcha'] === $_SESSION['captcha'];
  } else {
      $is_matched = null;
  }
  $message = $is_matched !== null ?
      ($is_matched ? 'Captcha matched' : 'Captcha not matched') :
      'Try solving the captcha';

  // Create a captcha
  $captcha = new ExpressionCaptcha();
  // Store captcha's solved value
  $_SESSION['captcha'] = $captcha->solve();
  // Render the captcha into image
  // The return value is a PNG image string encoded with base64
  $base64_image = $captcha->render();

  echo sprintf(
      '<!DOCTYPE html>' .
      '<html>' .
      '<body>' .
      '<form method="POST">' .
      '<img src="data:image/png;base64,%s"><br>' .
      '<input name="captcha" placeholder="Input captcha">' .
      '<input type="submit" value="Submit"><br>' .
      '</form>' .
      '<div>Message: %s</div>' .
      '</body>' .
      '</html>',
      $base64_image,
      $message
  );