Getting error in captcha code

Sometime back, I wanted to learn how to create a discussion board and did so by taking the help of an online tutorial and placed the discussion board in my personal site. I was soon bombarded with spam messages and I then decided that I should learn how to use a captcha image as well.

Right now, I am going through and trying to understand a php code for a captcha image which is like this.

 
<?php
//Start the session so we can store what the code actually is. 
session_start(); 
//Now lets use md5 to generate a totally random string 
$md5 = md5(microtime() * mktime()); 
/* 
We dont need a 32 character long string so we trim it down to 5 
*/ 
$string = substr($md5,0,5);
?>  
<?php
/* 
Now for the GD stuff, for ease of use lets create 
 the image from a background image. 
*/ 
$captcha = imagecreatefrompng("./captcha.png"); 
/* 
Lets set the colours, the colour $line is used to generate lines. 
 Using a blue misty colours. The colour codes are in RGB 
*/ 
$black = imagecolorallocate($captcha, 0, 0, 0); 
$line = imagecolorallocate($captcha,233,239,239); 
/* 
Now to make it a little bit harder for any bots to break,  
assuming they can break it so far. Lets add some lines 
in (static lines) to attempt to make the bots life a little harder 
*/ 
imageline($captcha,0,0,39,29,$line); 
imageline($captcha,40,0,64,29,$line);
?>  
<?php
/* 
Now for the all important writing of the randomly generated string to 
the image. 
*/ 
imagestring($captcha, 5, 20, 10, $string, $black); 
 
/* 
Encrypt and store the key inside of a session 
*/ 
$_SESSION['key'] = md5($string); 
/* 
Output the image 
*/ 
header("Content-type: image/png"); 
imagepng($captcha);
?>  
<?php
session_start(); 
//Encrypt the posted code field and then compare with the stored key 
if(md5($_POST['code']) != $_SESSION['key']) 
{ 
  die("Error: You must enter the code correctly"); 
}else{ 
  echo 'You entered the code correctly'; 
}
?>  

But when I open my captcha page, I can just see the red cross. I tried using a jpg image and also substituted the png extensions in the file with jpg extensions. But then I get an error message like this.

Fatal error: Call to undefined function imagecreatefromjpg() in C:
\wamp\www\personal site\captcha2.php on line 20

I also checked my phpinfo file and found that both png support and jpeg support are enabled. Why are the errors different with png and jpeg images?

Where am I going wrong? Am I making some simple newbie error?
What I basically want is that when a person wants to start a new discussion or post a reply, he should first need to fill in the captcha code.
Is there any simpler tutorial for a beginner?

Man page : [fphp]imagecreatefromjpeg[/fphp] contains advice:

"If you get the dreaded “Fatal error: Call to undefined function imagecreatefromjpeg()” message, check that your GD library is working properly by to looking at the output of phpinfo().

You need to check explicitly for JPEG support in the output (gd section), otherwise the imagecreatefromjpeg function won’t work."

You need to have the GD library installed.

If you cannot do this there are other Turing Tests you can apply. Come back if you need advice.

Hi Priya,
Can I just check - have you created the background image captcha.png?
The functions create the text and overlay it onto the background image that you have previously created called captcha.png

Thanks for the link, cups. I am reading it and trying to learn. I do have gd installed. I can also see that jpeg support is enabled.

Hi Mike, Thanks a lot. I do have the image created. Actually, the original captcha.png that I have in my folder has been downloaded from the same tutorial that I took the code from. In fact, I tried with 2 different images, captcha.png and captcha.jpeg because I wondered whether it was anything to do with the image support in my gd library. But I can see both png and jpeg enabled in the gd library on my wamp server.

On a second thought, I decided that instead of testing this captcha on wampserver on my PC, it may be better to try it online using my webhost (hostgator) as a file in my personal site itself. After all, it is there that I will utlimately be using this.
I initially found the same error in the file with the jpg image.

Fatal error: Call to undefined function imagecreatefromjpg() in
/home/jppp/public_html/captcha2.php on line 20

I then tried changing my file extension from jpg to jpeg, I got a
different error (all the errors below).
This is what I now get when I try to view the page with the jpeg image

Warning: Cannot modify header information - headers already sent by
(output started at /home/jppp/public_html/captcha2.php:14) in
/home/jppp/public_html/captcha2.php on line 55
ÿØÿàJFIFÿþ>CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), default
quality ÿÛCaaaa    $.’ ",#(7),01444’9=82<.342ÿÛC  2!!
22222222222222222222222222222222222222222222222222ÿÀd"ÿÄ
a ÿĵ}!1AQaa"q2‘¡#B±ÁRÑð$3br‚ %&'()
456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³
´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚáâãäåæçèéêñòóôõö÷øùúÿÄa
ÿĵaw!1AQaaq"2B‘¡±Á #3RðbrÑ $4á%ñ&'()
56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz‚ƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³
´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚâãäåæçèéêòóôõö÷øùúÿÚ ?´—6ú‘ÿO›Ê¸è
—/¿ÿ]ø¯½þ÷«y§ÝXÎ"º·0“Èô#ÔãÞ «v×¾\?g¸‡íVßóÏ?êÿÜÿ8õ
¶¾ŽÎŸÀ|:©ñýågM”Ú“Wò4
]VYÚâÆ.²
ääœaýòqþÏ£¦
°ßÅÐNÑIit.Vâ;svç©Îí¸8=éF¼V짆Ÿci+ÿÄÆ/>1þ›_¿ÿ¦Ÿíÿý÷ÏÍŽNïZ{ ¯.loXȇq>›Xþ¸ëVñ,zmÃI=´ö—0'ÚaI‘(O˜…*H$pH냜TT”M)Â]´gE_‰ëž‹Ä– sý’èé—–×ê-0C üÁ+†H p@ädÏ£øƒûVÚÚæÛJ¿û,ÇoÝ{o÷óúVN¬ÆëR;J>È·ÕøŸef ¢où+J/ž/’²™¬ ñ?ðU˜®6y»áýÝS·}òÿ©ÿWW⸏í^Gü´ûõÍ3²Š}ÁE ÷‘Òxm;ïýÊmô'ʜߎ Õ®´¡„“Ë !n¡ˆÈ7€ãïà‚qν&¡áØu=fgzÒ[ܬ“Åq¶6ºÀ9hPÉä,cÆ 㥠¢¸êac6Ý÷;éâçE8œ͍ûÅ«%•¤†Ñ¡÷qY´!å󔍎ìíê@íÈèjøÒL×·7Z5•ü1I§Î·‚ê6- #0bŠ»¹.X íãÉÍz ¼É«Í½Îáu,ÂçU_ÏA'LƒÝþ÷¨n6Áb°ëk›¼T–©Z~‡§©x~÷OÓµu( é/b,Äc/Ì:•á6c$ã®uö—qý‰<º‡®lo£¾ÝpXO,±m9 .·à€6ô$‚àרE[ZqR^)re%€ë€
SþðÁþ] ¬êP]­<LÛÕ _‰üŸ5ÿå@Ñ›{§°J1Sjµ\ˆ
‰r/ŸÊt«öŸ’Èóy’UXjôJ»÷cæõ®i0.§ÜPŸpQYeŸÿÙ Error: You must enter the
code correctly.

When I try to view the page with the png image, I get this.

Warning: Cannot modify header information - headers already sent by
(output started at /home/jppp/public_html/captcha2Hold.php:14) in
/home/jppp/public_html/captcha2Hold.php on line 55
‰PNG  IHDRdU9,¤7IDAThuY{p]Åyÿ}ßžsï¹I–lY66~@d+4¥15¾,ÚH3Ì@Ò@Z‘–¤ %-
m§M§3íL&dú gH M:¨¥”¡ÂËm’“ˆ’Òˆ8<2ÄÕ~Êò•®®î㜳ûõ=»ç\É9šÑݳg_ßo¿Ço¿
¥³Æ¾é9@Èqe)Tf¯©Êþ¯úÒ×¾Lßù­Ëozô8)¦€I) EÄL‘b("ŤŠ) b"¥(
0““Ä̘¸Ð&ko LLpãû6PÌÌÙ8A6/)3;;““°¢€HÙfD¼ozî…©ñ™©qZƒÔøà_ý·¼ B€Å±ÿ
£}˜¥$õ aDpý#ÇŸ¿ý2²­EÛW.2)ˆü/¹á $”ÍI‚|ýýë&/OþCûgہÄn# ää#òË
°&Áäôܾ鹙©ñ~ñ׬X ÿ×T8i.ÒE€ˆõ¶jk[¥UaíG¸ñÑãÏ|l’‘]ýEg$±ý²ÀR>¯Àn“ˆ:
+Û6ÙdïÔ?Ù¾PŸÌBD²©m-½Œ“Ós3Sã5¿ÿkÕÃ’ ‚‚ ¨¨gÒ×Ћ Ö<ß«œëUbͶ… W'ŽGÛiee‹&‚™¾%Y¨¨ˆ¯“WÈk¨ÐÈMeµ(·+®ˆ‰ãDŒ·»qÝÙ¶·>ô¯?yîŽ+ž½ãŠªJ×b• £APÐ#²4"K -ÎúúË—O@*|!)7’rj·ÇÍøe½ùíßÜIÖ›9ür£ˆ#Yb1¹ ¹á-Ò^½ŒÑ‰îµÅo ¤"’ê8Mcã:ºU¸=!A·×=yòÍåå%c4¬R6°øÝÉçžyñsϼøìWX9ýº²]@™ÉÜž&”vE•téø ¢)mrÜc¢Âþ1’¶Z§êÞ D BT'Íå…Åå…T'nY’©”õvº•·O[X8gŒN>ß\\ìôz"ÆãÅE“i ¥á¡åáC&shy;á_ûç£Ö…&shy; ˆë€2º\\>Á›Oðæ.•É{ý }ŠEÌz$X‘fíõK·>~âñ[·õÅ ²… ¸G- WÒ3lºaÓMÓƱ°}–cãgÞçZ‰róD®ê$˜NÜIÓTÄš×ýì•{/¹d[ Â¥•ÖŽ}{a>IM®a_ž½x ´ÌÜ9ß¿ÏQ°ú[¶‚2³ðO AÔRHEºÚ ŒJ¥»ÓœFaïЖG*è¤ßºýãO½C !‘"Räâ7#”—ÐÕjP1‡fI¥sõÑ:AL–4K›4‹ÔºÕV–‹0’¢RÌJ‘“ÄqçÌ…S£ƒeÖ®
•²•Š(VŒ^Ÿȉ &shy;e© *#7œ;¿¢ñ L>27ùìÜ ·#rÚÑN š€Éô ϵQ«rgÞÞeÞ®IÇÖô¸|bó
‰ps%¯ŽþÿǾõö#·\Ú®™$”,~»Pá”Ê1 )2jP—/‘z]çk–1G¨sT:mïʳF*© „—W¨ñäJM –¶n¬Ö™Èk&¯väEZi€6&Ÿ››¹m<“Ì ñà”+%H «Wa”ÖT§†NˆT˜6µ–¢•´¢‰ûfÌÚuÝ+ €„ˆ<ûØ€3NDT5@P4\\Eà-:ܺ²bNӝñ¡ÂzmRq"*E[F·Ua™ÉÓëB„R(rÔ ±ZØÞ¢i ‰@ºÀbÆ*,qõêÄ0ƒ²2$&shy;š´h Ä¹ƒÖP ‡ )T›5¨×§ÖÉZE„;¾ýÎ\\}YµÃ¤-§ò~Œ¼È× þ-¬PÊÀF„Ãr¶‘VÕ&shy;’¢w–šóiš8ÎÅ•R%T¦ã"ΟÁQa)ˆKp?>«™9ÐrzÎBæÕ©.
ýÖúø¸ygØ4 F ¬ Z½Ê!Úqˆw®Pem DNår&£Ä|â©7¿yÓ¥D"Aa‹aÓ
%“áÇÒc³Bf’QN#²ÀÉê¶È„¬Êõ‘ú¦]ÕÚvãu»»ÜhÎÇIÏÒ‰UDR\V‹<aóÑR<)Í{UEߘ“ýD? Û>Î<»FóRRk¢¦×l‰[H1CʤC½sw?yøë7oÀ¢KºÆ‹µÆ\\¹}–D³Äaz>LνSdºùhù0Ī¤ ¢‘4cöÄj°6²yãÎJ¹f´tVZ:M&NpÇ–rfƒŒ¨ÙŸF¨@Ÿ}7ÿÉUz¼®›>r¸´ƒDw—Ë:- àNàȽ×ñ™Ø?+"¾÷êþÁ/|ãU[8p×^øÀØð0€;ÿåÅÁî)IÒrçüŸù(Ö<rà&shy;— pÈubËEâNv™àâ ,‡efôÚËçÞ=²atëȆM(F ÕÉüÂy&Ú´aTQ‚5VØ·ËUƒòšüÇ;È Óo\\? ýÆ÷¦v7¹¶Ô &shy;‰©‰'^žxâåÝ_›pøÞkVé힇¾ÿß~à¥O¾Ÿ$×êG>}£-üÍÍ? kËëv¯EêþçÿÏg êPY¨!h¦ÝŒ²KF?ý¢&shy;y—ü“W^{㕅ņ«ËO(,«z:7Z¤v5b©”{›éü %fá†é7fn¯4º;N$M†ñí!˜Ø?;ñà,–M¡ûgѯkW>x‚¨c>üØw¼ð©=´r±²
£UÝÖØækî~úè=OÏøÒMïé[¢ãѽx¹Ù<“¤=÷•ÄqרZß¼í½#£ÄÔŸåz­¶uËŽm[¶ÔüÁFœO
à¬TŠÌ§ O ‰¤S¨¡Jåd¬r¡„¤× !Ö$¯ež,Š7±ß±\Ã¿»Ú‹ÛòÊïï]³MpóôëÏM] lxøl £qߝqο÷Ôч>¼ËwùÛ^ögÿy¼oÅ€€r=µ! ×Q,â¨6À0ݤ%fåiW©T¾| û¸b”ƒ0‹LÙF=îÁµœ&shy;¾"ÝæÔ:i2LÇc qÎc$¦ÐÊàl£á8| ï5D²ÂêÇAòúg÷îùêÁ«:h_'¿ñJHÚ–-Röeþòõ›üë?ܲëÓO¹ýÀ¡ÂˆcŠ§X!ær800¸)£Bb
¢h’ÒMº’çß]j7ňˆ¤ib´aâR–‚¯5U†ç¯žW( ÔAª¸”@Ð2ÕCØqÊlh£,BŽ
‰ý³“ßœ›™/Αû®°{ÿìÄþÙÝEÝ®|ð €—ïþyû:óÉ=CªeËš~Ín{ôǯ¿ûõ
¯O=yØnøÎëmtK’Ëb´ˆ6:¶¡XAI´Ž»-dɆ‚oñ,X@wO½{¼µÒ4¶%¹ó|–ÌâvUÔçR@@ é ¥èPô_S¨Á,¡^ÀÏAŒÝWØ·ÍG.ª\\®Ñ+÷ìpí×~ôƒÏ\\E
öC•;®Mª>ñ?'²÷¤Í\Nzƒ¦ä†I
%^2Q%­“¸×䁍JUˆ1qs¡»xš·¼§Re"!rîFH¢0Ú2º% ÊÄÔm¯œ|ç8 TëPʦÅ‘ ‰@AAj’c
š€µ)òq ‘›þV¹—¼%›:ˆÌLï›ž³ŸvIw‡9à‰ûoa§­¯v/€½г­ž³]
(šTß/þèU÷<ùj”žyà#7:<CŽF«Ptâ;÷…rwˆP–$抪
"jCë&Þwu½ZSA€¼GþØt6yÛÉ9+V?
©ªThSHM;µúÃ/}å55~#öõl£a}€÷íiXšÿ}ßaíë{ÿéa‡~çZ[ÞóÕƒŠé‡w_àW¾þªbúÞ]?
·frÜþØ! $€~àW·úaíóÇaŽ.#„ I”f¶7 ¢‘öÊQM)†Ñ+íF­R­GJeWeÙu†„ ˜Ý- 
±bØOöjƒŠŽF\δÕ!WUéÎê2€7WÚÆa/!óÆ| (Àîý³ÌL¯ ÀÄ/—{¯ÝõËkpÝ?¾öÓÀ 8»ûùâueý°÷?ÌÞÖ0Q@i›¥Ò@ E¤È'^Óòòü©sÇëë¶oº¼RŽ²[œ (&R (FµTaDœß09°2Ò0Œ6ƒêµ, 3Æ,&¥T83{ô%d.ª˜3Sã“Ós9) ±.iM$oVeçÕF(aˆ3û¬–bV „lc³šloí]Ö&7~þûçÙ iÓU eÝ;Ç@¥¾) "E(ÀÄö²K'ó‹'a«ëÖm(çWgÙÈÌœ¦ñ酳̴} t¬E6&shy;¦ÜýgG'€eÖ×ËC£ ¶¾—eIYKvÝ€~¤P@ªq²³‘÷qcYª‡ÕŽs4’‚B“ŒêùŠt ÇZrw*^ñÌƻۿzqþ/iƒKˆ%ç¤Ja´±TÙÈ\\Bᬓ™Š°mÚ°}xp=óšôµûÉoœr®ÌT8Ϯά{!
ÒöŽ©äV ›ó[Ë
f¦ÆmK ^¤zBG¥çÒ¦ê˺.chÍð>ÿýóñ‹ëý -#ªÌA”UºKÈG & ƒ
±õé’IзßR­eÆ.]?•Êâ…Ÿÿ( Ò¥<³žëMÁÐV¡Ÿí¾\ük%¹ôΝãTì(Òâêñpç…p½Ë D
©›bkø£¿õ_xiáÏ?0R@×AìU±1àôËè/ûc§€ˆ¢°•J.ñ@ÅVìA&Àµ¨²B³ú:²Zÿb¼ÿꔇÒ?
ÅôŽÝP^Vƒ •òÕµ­l‡šxÿY¸ì?Æü!Yà/¦ü‡üèÇšá È.– èôÉI~öý=d}m½6¯¡<¾
´V¡~@ûñÊ # üÓúx”‡¡ _üß…?½vÄ-Îk6åk¥ÜÒì…Nžä³I¡}®Õ/šm.R4¾àÿ{
[ôký»ãx¼VÃ*°oznrz}y~á—éeÑša~¤ÈÕÂúj’¼ð׳þèša¯~áâ32Ö´í
Ópž,¿ÓöQdµUvðÿ¦q™ Ö‹CIEND®B`‚ Error: You must enter the code
correctly.

What is happening?

It’s down to a typo, the function name is
imagecreatefromjpeg() not imagecreatefromjpg()

SpacePhoenix, I had made this typo error initially, but when I uploaded the script to the server, I had changed jpg to jpeg and the error I mentioned in my last thread is after I made the correction.

I am giving below all the files that I created for the purpose of learning captcha. I hope someone can help me.

They are called captcha.png, captcha.php, form.html and write.php. I have created the image called captcha.png and written the code for captcha.php and write.php as follows.

captcha.php

 
<?php
//Start the session so we can store what the code actually is. 
session_start(); 
//Now lets use md5 to generate a totally random string 
$md5 = md5(microtime() * mktime()); 
/* 
We dont need a 32 character long string so we trim it down to 5 
*/ 
$string = substr($md5,0,5);
?>  
<?php
/* 
Now for the GD stuff, for ease of use lets create 
 the image from a background image. 
*/ 
$captcha = imagecreatefrompng("captcha.png");   // Line 20
/* 
Lets set the colours, the colour $line is used to generate lines. 
 Using a blue misty colours. The colour codes are in RGB 
*/ 
$black = imagecolorallocate($captcha, 0, 0, 0); 
$line = imagecolorallocate($captcha,233,239,239); 
/* 
Now to make it a little bit harder for any bots to break,  
assuming they can break it so far. Lets add some lines 
in (static lines) to attempt to make the bots life a little harder 
*/ 
imageline($captcha,0,0,39,29,$line); 
imageline($captcha,40,0,64,29,$line);
?>  
<?php
/* 
Now for the all important writing of the randomly generated string to the image. 
*/ 
imagestring($captcha, 5, 20, 10, $string, $black); 
 
/* 
Encrypt and store the key inside of a session 
*/ 
$_SESSION['key'] = md5($string); 
/* 
Output the image 
*/ 
header("Content-type: image/png"); 
imagepng($captcha);
?>  
 

write.php

 
<?php
session_start(); 
//Encrypt the posted code field and then compare with the stored key 
if(md5($_POST['code']) != $_SESSION['key']) 
{ 
  die("Error: You must enter the code correctly"); 
}else{ 
  echo 'You entered the code correctly'; 
}
?>  

form.html

 
<html>
<head>
 <title>html form with php captcha</title>
</head>
<body>
 <form method="post" action="write.php">
  <input class="input" type="text" name="norobot" />
  <img src="captcha.php" />
  <input type="submit" value="Submit" />
 </form>
</body>
</html>
 

When I go to the file form.html, I can just see a red cross sign after the text image and the submit button. When I type anything random in the button (I obviously cannot see the captcha image), I get the message, Error, you must enter the code correctly.

Hi Priya,

I had prepared a Captcha script 3 years back. You can download and see the code and examples out there.

http://www.devraju.com/download/?d=captcha

Thanks, Raju. Unfortunately, due to some reason, I am not able to download the script. The dialog box seems to go on transferring the files endlessly but I cannot see anything saved.
Meanwhile, I tried to work on the above code again. I tried reading matter relating to the error which I got and found that it is related to some white space. I removed the “whitespace” after the closing ?> at the end of the file. since I read that there should not be anything (not even blanks or empty lines) after those two characters. I now have the opening and closing tags only in the beginning and ending of the file.

After doing that, I stopped getting the errors. I found that when I go to the file containing the captcha image, the captcha is getting created but now I have a different problem. Each time, a new text gets created, but whenever I type the correct letters in the textbox, I get a message saying that the code is incorrect even though it is correct.
My new captcha.php file is as follows:

 
<?php
//Start the session so we can store what the code actually is. 
session_start(); 
//Now lets use md5 to generate a totally random string 
$md5 = md5(microtime() * mktime()); 
/* We dont need a 32 character long string so we trim it down to 5 */ 
$string = substr($md5,0,5);
/* Now for the GD stuff, for ease of use lets create the image from a background image. */ 
$captcha = imagecreatefrompng("captcha.png");  
/* Lets set the colours, the colour $line is used to generate lines. Using a blue misty colours. The colour codes are in RGB */ 
$black = imagecolorallocate($captcha, 0, 0, 0); 
$line = imagecolorallocate($captcha,233,239,239); 
/* Now to make it a little bit harder for any bots to break,assuming they can break it so far. Lets add some lines in (static lines) to attempt to make the bots life a little harder */ 
imageline($captcha,0,0,39,29,$line); 
imageline($captcha,40,0,64,29,$line);
/* Now for the all important writing of the randomly generated string to the image. */
 imagestring($captcha, 5, 20, 10, $string, $black); 
/* Encrypt and store the key inside of a session */ 
$_SESSION['key'] = md5($string); 
/* Output the image */ 
header("Content-type:image/png"); 
imagepng($captcha);
session_start(); 
//Encrypt the posted code field and then compare with the stored key 
if(md5($_POST['code']) != $_SESSION['key']) 
{ 
  die("Error: You must enter the code correctly"); 
}else{ 
  echo 'You entered the code correctly'; 
}
?>  

Why do I get the message about the incorrect code even though I type the correct letters? You can see it in action here.

Though I haven’t tested your code but in quick look that first of all, you should not md5ed the string while storing the string in session. So change this line :

$_SESSION['key'] = md5($string);

to

$_SESSION['key'] = $string;

Secondly, submit the form to some other file so remove the following lines from captcha.php file:


session_start(); 
//Encrypt the posted code field and then compare with the stored key 
if(md5($_POST['code']) != $_SESSION['key']) 
{ 
  die("Error: You must enter the code correctly"); 
}else{ 
  echo 'You entered the code correctly'; 
}

Hope in this way it will work.

Good luck!

I just ran your captcha successfully in my computer. So here it is:
captcha.php


//Start the session so we can store what the code actually is. 
session_start(); 
//Now lets use md5 to generate a totally random string 
$md5 = md5(microtime() * mktime()); 
/* We dont need a 32 character long string so we trim it down to 5 */ 
$string = substr($md5,0,5);
/* Now for the GD stuff, for ease of use lets create the image from a background image. */ 
$captcha = imagecreatefrompng("captcha.png");  
/* Lets set the colours, the colour $line is used to generate lines. Using a blue misty colours. The colour codes are in RGB */ 
$black = imagecolorallocate($captcha, 0, 0, 0); 
$line = imagecolorallocate($captcha,233,239,239); 
/* Now to make it a little bit harder for any bots to break,assuming they can break it so far. Lets add some lines in (static lines) to attempt to make the bots life a little harder */ 
imageline($captcha,0,0,39,29,$line); 
imageline($captcha,40,0,64,29,$line);
/* Now for the all important writing of the randomly generated string to the image. */
 imagestring($captcha, 5, 20, 10, $string, $black); 
/* Encrypt and store the key inside of a session */ 
$_SESSION['key'] = $string; 
/* Output the image */ 
header("Content-type:image/png"); 
imagepng($captcha);
# Destroys the image
imagedestroy($captcha);

index.php (which calls the captcha)


<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
	$vResult = '';
	if(strtolower($_SESSION['key']) != strtolower($_POST['security_code'])){
		$vResult = 'Security Code is invalid!';
	}
	else{
		echo 'Hoorray!!!';
		die('<a href="./">Back</a>');
	}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
	<meta name="author" content="">
	<title>Captcha Test</title>
</head>
<body>
<form name="frmCaptcha" id="frmCaptcha" action="" method="post">
<div style="width:300px;border:1px solid #cccccc;font-size:11px;font-family:Verdana;padding:0px 0px 5px 0px;">
	<?php echo isset($vResult) ? $vResult . '<br />' : '';?>
	<img src="captcha.php?rand=<?php echo rand(1000, 9999);?>" /><br />
	Enter text appeared on the image above:<br />
	<input autocomplete="off" type="text" name="security_code" id="security_code" value="" />
	<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
</div>
</form>
</body>
</html>

Thank you so much, Raju. I was not able to get back earlier as I was having some issues with my FTP account and was trying to sort out the same.

The captcha code works very well and I have incorporated the same into the discussion form on my site. Ir is a big relief as I was flooded with spam and was even considering removing the discussion form till I learnt how to incorporate a captcha into my site.

I am not very quick in picking up the nuances of programming and am trying to learn and incorporate whatever I can. But with the help of my sitepoint friends, I am surely surging ahead.

Thanks once again.