Adding more number values to CAPTCHA

时间:2015-10-30 21:21:01

标签: php captcha

I wrote this a few months ago and the other day I realized that I made a mistake. This CAPTCHA only displays lowercase characters a-z (97-122). How do I add uppercase A-Z (65-90) and 0-9 (48-57)? I have the area in need of repair separated from the rest.

I first tried doing:

 for ($i = 0; $i < CAPTCHACharas; $i++) {
  $PassPhrase .= chr (rand (48, 57));
  $PassPhrase .= chr (rand (65, 90));
  $PassPhrase .= chr (rand (97, 122));
 }

But it only made things twice as long with only "a-z". I then tried:

 for ($i = 0; $i < CAPTCHACharas; $i++) {
  $PassPhrase .= chr (rand (48, 57), (65, 90), (97, 122));
 }

With no success. I also replaced the ), ( with ) + ( and it didn't work. Thanks for any help.

PHP CAPTCHA:

<?php
 session_start ();
 // Sets some important definitions
 define ("CAPTCHACharas", 7); // the number of characters in the pass-phrase
 define ("CAPTCHAWidth", 100); // the width of the image
 define ("CAPTCHAHeight", 40); // the height of the image
 // Generates the random pass-phrase
 $PassPhrase = "";


 // The characters used
 for ($i = 0; $i < CAPTCHACharas; $i++) {
  // "48" - "57" = "0" - "9"
  // "65" - "90" = "A" - "Z"
  // "97" - "122" = "a" - "z"
  $PassPhrase .= chr (rand (97, 122));
 }


 // Store the encrypted pass-phrase in a session variable
 // Connects to the form.
 $_SESSION ["PassPhrase"] = SHA1 ($PassPhrase);
 // Creates the image
 $img = imagecreatetruecolor (CAPTCHAWidth, CAPTCHAHeight);
 // Set the background, text and line\dots colors
 $BackgroundColor = imagecolorallocate ($img, 255, 255, 255); // current color: white
 $TextColor = imagecolorallocate ($img, 0, 0, 0); // current color: black
 $BorderColor = imagecolorallocate ($img, 64, 64, 64); // current color: dark gray
 // Fills the background
 imagefilledrectangle ($img, 0, 0, CAPTCHAWidth, CAPTCHAHeight, $BackgroundColor);
 // Formats everything
 imagettftext ($img, 18, 0, 5, CAPTCHAHeight - 5, $TextColor, "captcha-1.ttf", $PassPhrase);
 // Draws some random lines here and there.
 for ($i = 0; $i < 5; $i++) {imageline ($img, 0, rand () % CAPTCHAHeight, CAPTCHAWidth, rand () % CAPTCHAHeight, $BorderColor);}
 // Puts in some random dots here and there.
 for ($i = 0; $i < 50; $i++) {imagesetpixel ($img, rand () % CAPTCHAWidth, rand () % CAPTCHAHeight, $BorderColor);}
 // Output the image as a ".png" file using a header
 header ("content-type: image/png");
 imagepng ($img);
 imagedestroy ($img);
?>

1 个答案:

答案 0 :(得分:0)

How about generating your captcha like this:

define( 'CAPTCHACharas', 7 );
// Allowed characters 
$letters    = 'ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789';
$letters_no = strlen( $letters );
$PassPhrase = '';

// Generate CAPCHA
for ( $i=0; $i<CAPTCHACharas; $i++ ) {
    $PassPhrase .= $letters{rand( 0, $letters_no )};
}

// Use it like you used it before
echo $PassPhrase;