You are here

function image_captcha_image in CAPTCHA 7

Same name and namespace in other branches
  1. 5.3 image_captcha/image_captcha.module \image_captcha_image()
  2. 6.2 image_captcha/image_captcha.user.inc \image_captcha_image()
  3. 6 image_captcha/image_captcha.user.inc \image_captcha_image()

Menu callback function that generates the CAPTCHA image.

1 string reference to 'image_captcha_image'
image_captcha_menu in image_captcha/image_captcha.module
Implements hook_menu().

File

image_captcha/image_captcha.user.inc, line 14
Functions for the generation of the CAPTCHA image.

Code

function image_captcha_image() {

  // If output buffering is on: discard current content and disable further buffering.
  if (ob_get_level()) {
    ob_end_clean();
  }
  if (!isset($_GET['sid']) || is_array($_GET['sid'])) {
    exit;
  }
  $captcha_sid = $_GET['sid'];

  // Get solution (the code to show).
  $code = db_query("SELECT solution FROM {captcha_sessions} WHERE csid = :csid", array(
    ':csid' => $captcha_sid,
  ))
    ->fetchField();

  // Only generate captcha if code exists in the session.
  if ($code !== FALSE) {

    // Seed the random generators used for image CAPTCHA distortion based on session and code
    // to counter attacks that re-request the same challenge and pick the simplest image one or combine info.
    $seed = (int) hexdec(substr(md5($captcha_sid . $code), 0, 8));
    srand($seed);
    mt_srand($seed);

    // Generate the image.
    $image = @_image_captcha_generate_image($code);

    // Check of generation was successful.
    if (!$image) {
      watchdog('CAPTCHA', 'Generation of image CAPTCHA failed. Check your image CAPTCHA configuration and especially the used font.', array(), WATCHDOG_ERROR);
      exit;
    }

    // Send the image resource as an image file to the client.
    $file_format = variable_get('image_captcha_file_format', IMAGE_CAPTCHA_FILE_FORMAT_JPG);
    if ($file_format == IMAGE_CAPTCHA_FILE_FORMAT_JPG) {
      drupal_add_http_header('Content-Type', 'image/jpeg');
      imagejpeg($image);
    }
    else {
      drupal_add_http_header('Content-Type', 'image/png');
      imagepng($image);
    }

    // Clean up the image resource.
    imagedestroy($image);
  }
  exit;
}