Click here to Skip to main content
11,928,078 members (28,151 online)

Saransh Dhingra asked:

Open original thread
Hello everyone this is my first post here so please excuse me if I forget something or don't follow some standard. That being cleared I saw this code for generating captcha somewhere and I modified it to get random color for each character and some other small fixes, here is the code:
header("Content-type: image/png");
function ran_string($length=10){
        $pattern = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        for($i=0; $i<$length; $i++){
            $string .= $pattern[rand(0,61)];
return $string;
function captcha()
$im = imagecreate(100, 50);
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color =array( imagecolorallocate($im, 255, 0, 0),imagecolorallocate($im, 0, 255, 0),imagecolorallocate($im, 0, 0, 255),imagecolorallocate($im, 255, 255, 255));
imagestring($im, 10, $x, 5,  $string[$i], $text_color[rand(0,3)]);
imagestring($im, 10, 10, 5,  $string[0], $text_color[rand(0,3)]);
imagestring($im, 10, 20, 5,  $string[1], $text_color[rand(0,3)]);
imagestring($im, 10, 30, 5,  $string[2], $text_color[rand(0,3)]);
imagestring($im, 10, 40, 5,  $string[3], $text_color[rand(0,3)]);
imagestring($im, 10, 50, 5,  $string[4], $text_color[rand(0,3)]);
imagestring($im, 10, 60, 5,  $string[5], $text_color[rand(0,3)]);*/
But the output for the above is just one character and if I remove the "for loop" and uncomment the commented portion I get the desired result, please can someone help, I am sorry if this is a n00b question!!!
It was quite simple and silly of me, I used count($string) where I should have used strlen() anyways the correct version is this:
        imagechar($im, $font, $x, 5,  $string[$i], $text_color[rand(0,3)]);
Tags: PHP


When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).

Advertise | Privacy | Mobile
Web03 | 2.8.151126.1 | Last Updated 26 Mar 2009
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100