Firstly CAPTCHA is not a word, its an abbreviation which stands for Completely Automated Public Turing Test to tell Human and Animal Apart..
Introduction
In this article lets see how to implement CAPTCHA in asp.net application which we generally see when we login or signup in different websites.It is used to protect websites from hackers and spammers. Firstly,CAPTCHA is not a word, its an abbreviation which stands for Completely Automated Public Turing Test to tell Computers and Humans Apart,lets start doing...
Implementing Captcha
Add a new website in Visual Studio. In Default.aspx, add image control which is in HTML section of Toolbox, one textbox and one button control in it. Add one another web page in root directory with name
Captcha.aspx and in its code separation page write the following code,
Note:- don't forget to add three namespaces mentioned below:
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Design;public partial class captcha : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//create object of Bitmap Class and set its width and height.
Bitmap bmp = new Bitmap(180,50);
//Create Graphics object and assign bitmap object to graphics' object.
Graphics gp = Graphics.FromImage(bmp);
gp.Clear(Color .OrangeRed);
Font ft = new Font("arial", 30, FontStyle.Regular);
//genetating random 6 digit random number
string str = getcapt();
//take returned value from method into session
Session.Add("str",str);
gp.DrawString(str, ft, Brushes.White, 2, 2);
Response.ContentType = "image/GIF";
bmp.Save(Response.OutputStream, ImageFormat.Gif);
bmp.Dispose();
gp.Dispose();
ft.Dispose();
}
public string getcapt()
{
//u can allowed any characters which u want
string allowedchars = "a,b,c,d,e,f,g,h,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,";
allowedchars += "A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z,";
allowedchars += "2,3,4,5,6,7,8,9";
char[] sep ={ ',' };
string[] arr = allowedchars.Split(sep);
string passwordchars = "";
string temp;
//creates random combination of letters and nos.
Random rmd = new Random();
int i;
for (i = 0; i <= 6; i++)
{
temp = arr[rmd.Next(0, arr.Length)];
passwordchars += temp;
}
return passwordchars ;
}
}
After this in image control of Default.aspx page include
src="Captcha.aspx" then run ur application
Conclusion
This looks simple but used in almost every website which gives preference to security of their websites it protects from machine to login behaving like a human.
njoy coding
ankit saxena
Ankitsrist