PHP Freelancer Developer from India
Using Zend Captcha
Recently on a project I was developing using the Zend Framework, I needed to validate a form using a CAPTCHA image.
CAPTCHA
For those who don’t know, CAPTCHA stands for Completely Automated Public Turing test to tell Computers and Humans Apart.
Here’s a list of what we need to do to get our instance of Zend_Captcha_Image up and running.
- Make sure we have GD installed.
- Make a new folder in our web directory with 777 permissions. This will store the generated CAPTCHA images.
- Write generateCaptcha() function
- Write validateCaptcha() function
- Show a quick example, bask in Zend Framework aided CAPTCHA awesomeness, and stop fearing robots until the Matrix comes true
1.) Make sure we have GD installed.
2.) Make CAPTCHA images folder
Create a folder in public/ directory to store image with write pwrmission I of course mean whatever folder your server is pointing to. This is so the captcha images can be accessible by HTTP request, for example through the folder http://www.your-site.com/public/images/captcha/
I hope you’re deep enough in the game for that to make sense. After you’ve made that folder, take note of it, for you’ll use it in step 3.
3.) Write generateCaptcha() function
- //generates an instance of Zend_Captcha
- //returns ID of captcha session
- function generateCaptcha() {
- $captcha = new Zend_Captcha_Image();
- $captcha->setTimeout(’300′)
- ->setWordLen(’6′)
- ->setHeight(’80′)
- ->setFont(‘/path/to/your/fontFile.ttf’)
- ->setImgDir(‘/path/to/your/image/captchaDirectory’);
- $captcha->generate(); //command to generate session + create image
- return $captcha->getId(); //returns the ID given to session & image
- } //end function generateCaptcha
So, let’s go over this function. First we instantiated a new Object of class Zend_Captcha_Image. Then we used it’s functions to feed it some basic information. $captcha->setTimeout(’300′) sets the time the session will stay active, in seconds. So, upon loading the form, the user has 5 minutes to respond. ->setWordLen(’6′), pretty obviously sets how many characters are used in the CAPTCHA image. 6 is pretty decent, as shown in the example above. ->setHeight(’80′) sets the heigh of the image. The default may be good for you; I only chose it because my font file was a bit big.
->setFont(‘/path/to/your/fontFile.ttf’) points to which font you want to use for the image. I’d recommend a san serif font, as others may be too hard for humans to read. Do a quick google search for .ttf files, you should find one online without too much trouble. Contact me if you want one that I used though!
Finally, ->setImgDir(‘/path/to/your/image/captchaDirectory’) should point to the directory you created in step 2.
Let’s talk abit about what the Zend Framework is doing for us with the generate(); command. Basically, it makes a random string of numbers and lower case letters and makes an image out of this using your font and some GD trickery/artistry to make it look funny, and more importantly – (even more) non robot readable. Then, it stores all the information in a session called up by…
4.) Write validateCaptcha() function
- //validates captcha response
- function validateCaptcha($captcha) {
- $captchaId = $captcha[‘id’];
- $captchaInput = $captcha[‘input’];
- $captchaSession = new Zend_Session_Namespace(‘Zend_Form_Captcha_’ . $captchaId);
- $captchaIterator = $captchaSession->getIterator();
- $captchaWord = $captchaIterator[‘word’];
- if( $catchaWord ) {
- if( $captchaInput != $captchaWord ){
- return false;
- } else {
- return true;
- }
- } else {
- return false;
- }
- }
vaidateCaptcha() is pretty simple as well. First, you get data sent by the form through the function in $captcha, an array you set up in the controller later on. It contains 2 pieces of information, – the CAPTCHA session’s id, and what the user (hopefully human!) entered into the form. Using the id, it accesses the session, and gets the correct word. The word is compared to what the input entered, and the function returns appropriately.
5.) This is where you make it clap
Here’s a quick example of what the code would look like in the backend + frontend. I’ll write the code using Zend’s MVC standards if someone requests, but I think you guys can figure this out.
- //setup CAPTCHA
- $captchaId = generateCaptcha(); //generates CAPTCHA image and session, returns session’s ID
- if( isset($_POST[‘captcha’]) ) { //if a post value is sent, process form
- $captcha = $_POST[‘captcha’]; //get array sent in $_POST form
- if( validateCaptcha($captcha) ) {
- //if a true value is sent, process form
- } else {
- //captcha invalid, text doesn’t match
- }
- }
And now the frontend.
- <!–?=$_SERVER[‘PHP_SELF’] ?–><form action=”<?=$_SERVER['PHP_SELF'] ?>” method=”POST”>
- <img src=”/your/captchaDirectory/<!–?=$captchaId ?–><?=$captchaId ?>.png” alt=”"/><br />
- What‘s the word above say? <input />
- <input value=”<!–?=$captchaId ?–><?=$captchaId ?>”/>
- <input value=”test me”/>
</form>
| Print article | This entry was posted by Khem Raj on October 13, 2010 at 1:24 pm, and is filed under Zend Framework. Follow any responses to this post through RSS 2.0. Both comments and pings are currently closed. |
Comments are closed.
about 2 years ago
Why have you removed my post? It was very beneficial information and i guarantee atleast one person found it helpful unlike the rest of the comments on this website. I’ll post it again. Fed up with obtaining low amounts of useless traffic for your website? Well i want to let you know about a new underground tactic which makes myself $900 every day on 100% AUTOPILOT. I could be here all day and going into detail but why dont you just check their website out? There is a great video that explains everything. So if your seriously interested in producing simple money this is the website for you. Auto Traffic Avalanche
about 2 years ago
Hello I thought i had seen this site before… This guy made a exact copy of your site. Or maybe this is also your site? http://www.autotraffic-avalanche.org
about 2 years ago
Hi, No need to worry if anyone copy content of my site as i am web developer and i post the codes/tricks which may help anyone and also this way i collecting my code library at my site.
about 2 years ago
Thanks for an idea, you sparked at thought from a angle I hadn’t given thoguht to yet. Now lets see if I can do something with it.
about 2 years ago
I have built a website and I was thinking of changing the template.Yours looks pretty decent! Feel free to visit my blog and suggest things!
about 2 years ago
Superb blog post, I have book marked this internet site so ideally I’ll see much more on this subject in the foreseeable future!
about 2 years ago
Would you be keen on exchanging hyperlinks?
about 2 years ago
I’d need to examine with you here. Which isn’t one thing I usually do! I get pleasure from reading a submit that can make individuals think. Additionally, thanks for permitting me to remark!
about 2 years ago
Can I just say what a reduction to search out somebody who really knows what theyre speaking about on the internet. You definitely know the way to deliver a difficulty to light and make it important. More folks must learn this and understand this facet of the story. I cant imagine youre no more common since you undoubtedly have the gift.
about 2 years ago
very good publish, i certainly love this web site, keep on it
about 2 years ago
Spot on with this write-up, I actually assume this web site needs much more consideration. I’ll most likely be once more to learn far more, thanks for that info.
about 2 years ago
I discovered your weblog site on google and test just a few of your early posts. Proceed to keep up the very good operate. I simply further up your RSS feed to my MSN Information Reader. In search of ahead to reading extra from you afterward!…
about 2 years ago
Would you be excited about exchanging links?
about 2 years ago
It’s laborious to find knowledgeable individuals on this topic, but you sound like you understand what you’re speaking about! Thanks
about 2 years ago
I’d must examine with you here. Which is not one thing I often do! I take pleasure in reading a post that may make people think. Also, thanks for allowing me to remark!
about 2 years ago
There are some attention-grabbing cut-off dates in this article but I don’t know if I see all of them center to heart. There may be some validity but I’ll take hold opinion until I look into it further. Good article , thanks and we wish extra! Added to FeedBurner as well
about 2 years ago
Spot on with this write-up, I actually think this website wants far more consideration. I’ll most likely be once more to learn far more, thanks for that info.
about 2 years ago
+1 ))
about 2 years ago
There are some attention-grabbing points in time in this article but I don’t know if I see all of them center to heart. There’s some validity but I will take hold opinion till I look into it further. Good article , thanks and we want more! Added to FeedBurner as nicely
about 2 years ago
Hi, i just needed to come here to let you know about a seriously cheap service that posts comments similar to this on millions of WordPress blogs. Why you might ask, well you might want to sell a product and target webmasters or simply just increase the amount of backlinks your web site has which will improve your Google rankins which will then bring your website more traffic and money. Take a quick take a look at this web site for more info. http://hellomotow.net/backlinks
about 2 years ago
We just couldnt leave your website before stating
about 2 years ago
I discovered your weblog web site on google and check just a few of your early posts. Proceed to keep up the very good operate. I simply further up your RSS feed to my MSN News Reader. Looking for forward to studying more from you in a while!…
about 2 years ago
Hi,
i needed render number code captcha.
String + Numbers = not ok.
Please help me its.
Thanks,