Ever,logged,onto,Yahoo,here,Planet,Source,Cod
Quick Search for:  in language:    
Ever,logged,onto,Yahoo,here,Planet,Source,Cod
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
PHP Stats

 Code: 74,754 lines
 Jobs: 12 postings

 
Sponsored by:

 

You are in:

 
Login



Latest Code Ticker for PHP.
Smart Image Navigator
By Brian Di Croce on 10/27


Click here to see a screenshot of this code!Form security verification
By Christian Mallette on 10/26

(Screen Shot)

Click here to see a screenshot of this code!Guestbook
By Nightmare on 10/25

(Screen Shot)

Shout! Box
By Nightmare on 10/23


SERVER-TO-SERVE R site (or single dir) transfer
By Raffaele Marranzini on 10/22


Site IP Logger - Watch who comes to your site!
By KRaZY-DeSiGN on 10/21


IP Banner - Block unwanted people from your site!
By KRaZY-DeSiGN on 10/20


PWGen
By Flinn Mueller on 10/19


URHere
By Flinn Mueller on 10/19


Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!





Affiliate Sites



 
 
   

^ An Image Verification Tutorial

Print
Email
 

Submitted on: 9/10/2002 9:35:29 PM
By: Darryl Porter 
Level: Beginner
User Rating: By 21 Users
Compatibility:PHP 4.0

Users have accessed this article 1288 times.
 

(About the author)
 
     Ever logged onto Yahoo! or here on Planet Source Code and have run across the verification image containing numbers and leters that you must plug into a form for verification? Learn to do it.

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.



Image Verification Tutorial

I'm sure many of you have logged on to Yahoo!, eBay or even here on Planet Source Code and have run across the verification image containing numbers and letters that you must plug into an input box for verification. And maybe you thought, "What the heck is this for?" or "I wish I knew how to do that."
You wanna know--then I will show you how.

A script like this is usually used for further security of the user's information--or, like on Planet Source Code, so that "unscrupulous people" cannot use "HTTP Post code in their submissions to trick people into unknowingly voting for them."

Okay, enough talk--let's get started.

First, I assume that you have PHP 4 with the GD library already installed. Also, we will use session functions in this code to pass a varaible from one page to the next.

To create our image, we need to send a header telling the connection that we are about to send an image, we do that with the header function:
--------------------------------------------

 /*Send header*/
Header("Content-Type: image/png");

--------------------------------------------
We are going to be working with png images in this tutorial. But if you want to use "jpeg", just plug it in where "png" is in the header. (You can also call a "gif" image, but because of all the money stuff, most servers don't support it.)

I know your dying to get started building images, but first, we need to get a little more prep work out the way. So, let's put those session functions to work.
---------------------------------------------

/* initialize a session. */
session_start();

/*We'll set this variable later.*/
$new_string;

/*register the session variable. */
session_register('new_string');

-------------------------------------------------
All we did above was start a new session with the session start function. We will call this session on a different page that we will create later. Second, we created a variable called new_string that we will give a value to later. Lastly, we called the session register function: this function takes the variable we created as an argument minus the "$" sign, also, you must put it inside single quotes only. (An argument refers to the single or comma separated information inside the parenthesis of a function.)

With that out the way, we can now begin to create our image. We start this process by calling the create image function, which does exactly what it says: Creates an image.
---------------------------------------------

/* set up image*/
/*The first number is the width and the second is the height*/

$im = ImageCreate(200, 40);  

----------------------------------------------
I set the image Create() function to the variable $im. The variable $im will be our pointer to the image we just created for the rest of the tutorial. The image Create function take only two arguments and the arguments can only be integers (numbers). The first argument is the width of the image in pixels, the second, you guessed it, is the height.

Let's give our image some color.
----------------------------------------------

/*creates two variable to store color*/
$white = ImageColorAllocate($im, 255, 255, 255);
$black = ImageColorAllocate($im, 0, 0, 0);

----------------------------------------------
I called the Image Color Allocate function twice. The first time is to set the color for white, the second to set the color for black. The function take 4 arguments: The image pointer variable $im, and the RGB (red, green, blue) components that are separated by commas.
(255, 255, 255, is the code for white, while 0, 0, 0, is the code for black. You can play with the numbers to produce any color you want.)
At this point we have a png image and two colors. Now we will create a random string generator to place as the verification code inside the image. I won't discuss how the random generator code works, but will only lay out the code with comments.
------------------------------------------------

/*random string generator.*/
/*The seed for the random number*/

srand((double)microtime()*1000000);

/*Runs the string through the md5 function--which is a function that encrypts a string, changing it into a 32 character string composed of numbers and lowercase letters*/

$string = md5(rand(0,9999));

/*Creates the new string. The first number is the point in the 32 character string where we will pull our string from. In other words, PHP will count (beginning at 0) 17 characters into the string. The 18th character in will be our beginning point (remember, PHP starts counting from 0). From there, PHP counts 5 characters from that point, and thus, we get our five character string. The second number is the length of our string--changing this number will give us different string lengths.*/
$new_string = substr($string, 17, 5);
-------------------------------------------------

Moving on--Now let's fill the image with color.
-------------------------------------------------

 /*fill image with black*/
ImageFill($im, 0, 0, $black);

---------------------------------------------------
The Image Fill function is called first. It takes 4 arguments: Again we add the image pointer variable $im, the second and third are x, y coordinates in our image, 0, 0, being at the top left corner. Our image size is 200x40, therefore, the bottom right corner would be 200, 40. The fourth argument tell us with what color to fill the image with: In our case it is black.

Now, let's add the string we just created to our image.
----------------------------------------------------

 /*write string at coordinates (70,10) in the color white. (70, 10) puts the string almost in the middle of the image.*/
ImageString($im, 4, 70, 10, $new_string, $white);

-----------------------------------------------------
We have yet another function: Image String, and yes, it adds a string to our image. It takes six arguments. The first is the image pointer variable, the second argument can be any number from 1 to 5,(which calls for one of the built in fonts). The next two arguments are the coordinates, first the x (width) then the y (height). This is for the placement of our string. The next argument calls for the string variable. In our case it is $new_string. The last argument is the variable containing the color, which is $white.

We end the image build by outputting our image using the code below:
-----------------------------------------------------

 /*output to browser*/
ImagePNG($im, "verify.png");
ImageDestroy($im);

------------------------------------------------------
We have the imagePNG function with two arguments: again, like always the image pointer, the second argument names the image "verify.png" and saves the image in the current directory. If you want the image in a different directory, proceed "verify.png" with the path to the directory.

Hey, we're through building the image.

Finally, input the Image Destroy function, it has one argument: the pointer variable. Destroying the image frees up server memory. Your server administrator will like you for this. Your code should look like this:
-----------------------------------------------------

<?php
 /*header*/
Header("Content-Type: image/png");

/* initialize a session. */

session_start();

/*We'll set this variable later.*/
$new_string;

/*register the session variable. */
session_register('new_string');

/*You will need these two lines below.*/
echo "<html><head><title>Verification</title></head>";
echo "<body>";

/* set up image, the first number is the width and the second is the height*/
$im = ImageCreate(200, 40);

/*creates two variables to store color*/
$white = ImageColorAllocate($im, 255, 255, 255);
$black = ImageColorAllocate($im, 0, 0, 0);

/*random string generator.*/
/*The seed for the random number*/

srand((double)microtime()*1000000);

/*Runs the string through the md5 function*/
$string = md5(rand(0,9999));

/*creates the new string. */
$new_string = substr($string, 17, 5);

 /*fill image with black*/
ImageFill($im, 0, 0, $black);

 /*writes string */
ImageString($im, 4, 96, 19, $new_string, $white);

/* output to browser*/
ImagePNG($im, "verify.png");
ImageDestroy($im);
?>
---------------------------------------------------
Now place a form input box below our image (see the code below), and ask the user to input the string they see in the image in the text box. Append this code to the bottom of the code above, before the "?>."
---------------------------------------------------

/*I plugged our image in like I would any other image.*/
echo "<img src=\"verify.png\">";
echo "<br><br>";
echo "Type the code you see in the image in the box below. (case sensitive)";
echo " <form action=\"formhandler.php\" method=post>";
echo "<input name=\"random\" type=\"text\" value=\"\">";
echo "<input type=\"submit\">";
echo "</form>";
echo "</body>";
echo "</html>";

---------------------------------------------------
With that done, we must now create a new file and name it formhandler.php. We will put the code below into it.
---------------------------------------------------

<?php
/*This starts the session that we created on the last page*/
session_start();

/*This trims the random variable of any white space that the user may have unknowingly put in.*/
$random = trim($random);

/*Below is a conditional statement: In English it reads, if the string that the user put into the text box is equal to what is in the image then print to the screen, "You are verified."  If they are not equal it tells the user to go back and try again.*/

/*We can use the variable $new_string because we registered it into our session on the last page, it retains its value that it had on the first page.*/
if ($new_string == $random){
echo "You are verified";
}
else{
echo "Please go back and get verified.";
}
?>

There you are. Try it out. IF you have any trouble send me an e-mail. And that's that.

Thanks to comments left below, this article has been updated by the Author.
Please Rate this Tutorial!!!

 


Other 2 submission(s) by this author

 

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
Your Vote!

What do you think of this article(in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor See Voting Log
 
Other User Comments
9/11/2002 2:19:51 AM:Mehdi Hanbali
Bravo, EXCELLENT code. I haven't seen something this useful in a long time. Good work, totally worth a perfect score.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
9/11/2002 10:51:06 AM:
I really liked the code. Very impressive. I do mention one thing though that will improve the code a little bit. If I understand the code correctly, you are passing the verification code back to the form as a form element, a hidden one, but a form element no less. This would allow the user to write a program which looks at the HTML code and type in the verification code. This would defeat the purpose. To make it even stronger, it would be best to remove this from the code and put it in a session, or a hash that you load each time, but something that would keep it invisible from the user. Thanks for sharing the code. It was really good.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
9/11/2002 11:34:41 AM:
Very nice indeed.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
9/15/2002 7:26:17 PM:
This is horrible... absolutely worthless! just kidding, couldn't complain if I had to. Nice code!
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
9/15/2002 10:32:16 PM:Darryl Porter
I had to pick my lip off the floor before I could continue to read--Thanks for the feedback--
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
9/18/2002 5:04:33 AM:david.emmo
very nice! thanks! not sure i'd use it in the way you've described but very useful all the same!
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
9/18/2002 5:08:48 AM:david.emmo
oooh...and when i rated it, guess what i had to do...? :)
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
10/6/2002 2:55:45 PM:Alex Graf
Hi. I looked through your code again. Well, true, it only differs from mine in this minor detail: You use one font for writing the Text. I use 5 different ones instead. So, one could use an OCR program to read the string. But since this is quite unlikely, well.... um. I wrote in mail that i´m sorry, if it looked like i was stealing your code. I didn´t intend to. I think we only had the same idea. Please forgive me. :( Alex
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | PHP Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.