Simple Way to Create Captcha in CakePHP 1.2,CakePHP 1.3, CakePHP 2.0 and CakePHP 2.1

You can download the Facebook SDK for PHP from GitHub.

CakePHP 2.1 :Put the “captcha” folder on path-to-cakephp-2.0/vendors/ – on root vendors folder. Use following

App::import('Vendor', 'captcha/captcha');

Since CakePHP 2.1 the Pages Controller is no longer part of the core but ships in the app folder. So my advice would be create UsersController and put the captcha_image() on that controller and and use $this->Html->url(‘/users/captcha_image’);.

CakePHP 2.0 :Put the “captcha” folder on path-to-cakephp-2.0/app/vendors/ – on App’s vendors folder. Use following

App::import('Vendor', 'captcha/captcha');

CakePHP 1.3 :Put the “captcha” folder on path-to-cakephp-1.3/vendors/ – on the root vendors folder.

App::import('Vendor', 'captcha/captcha');

CakePHP 1.2 :This post and code is for CakePHP 1.2 and CakePHP 1.3. For CakePHP 1.3 put the “captcha” folder on path-to-cakephp-1.3/vendors/ – on the root vendors folder.

Update:Google doc link was not working. Thanks miguel for lettimg me know. Here is zip file to download Download Code

When I start developing site using CakePHP, I was at wits end about how to implement captcha. I found couple ways using google but all of them seemed hard to implement. Now I am going to show you can do it in an easy simple way.There are many ways to add captcha to your CakePHP site. I am going to show a easy way to do it. First Let’s create a folder named “captcha” in vendor folder. Now we develop the vendor code.

class captcha {
	public function show_captcha() {
		if (session_id() == "") {
			session_name("CAKEPHP");
			session_start();
		}

		$path= VENDORS.'captcha';
		$imgname = 'noise.jpg';
		$imgpath  = $path.'/images/'.$imgname;

		$captchatext = md5(time());
		$captchatext = substr($captchatext, 0, 5);
		$_SESSION['captcha']=$captchatext;

		if (file_exists($imgpath) ){
			$im = imagecreatefromjpeg($imgpath);
			$grey = imagecolorallocate($im, 128, 128, 128);
			$font = $path.'/fonts/'.'BIRTH_OF_A_HERO.ttf';

			imagettftext($im, 20, 0, 10, 25, $grey, $font, $captchatext) ;

			header('Content-Type: image/jpeg');
			header("Cache-control: private, no-cache");
			header ("Last-Modified: " . gmdate ("D, d M Y H:i:s") . " GMT");
			header("Pragma: no-cache");
			imagejpeg($im);

			imagedestroy($im);
			ob_flush();
			flush();
		}
		else{
			echo 'captcha error';
			exit;
		}
	}
}

This code actually very simple. First i check for session. Then i check for a noise image. Then i create the image. I added the cache control here for any caching problem.

Now we implement it on our site. to do that we have to add a function the controller or we can add it to our pages controller.

    function captcha_image(){
		App::import('Vendor', 'captcha/captcha');
		$captcha = new captcha();
		$captcha->show_captcha();
    }

Then we call it in our view.

</pre>
<img id="captcha" src="<?php echo $this->Html->url('/pages/captcha_image');?>" alt="" />
<pre>

Simple right.

Now if your user doesn’t understand current captcha he will want another one. How you do that?
here is how

 
<a href="javascript:void(0);" 
onclick="javascript:document.images.captcha.src="<?php echo $this->Html->url("/pages/captcha_image");?>?" + Math.round(Math.random(0)*1000)+1" >Reset</a>

To check the captcha in controller we will use this one.

if($this->data['ContactMsge']['captcha']!=$this->Session->read('captcha'))
{
	$this->Session->setFlash(__('Please enter correct captcha code and try again.', true));
}

So as you can see you add this to you site very easily and it is very much customizable. You can download the vendor files along with image and font HERE.

About Zakir Hyder

This entry was written by .

02. May 2011 by Zakir Hyder
Categories: CakePHP, PHP, Web Development | Tags: , , , , , , , , | Comments

Comments

  1. […] Simple Way to Create Captcha in CakePHP Monday, May 02, 2011 3:25 PM When i start developing site using CakePHP, I was at wits end about how to implement capcha. I found couple ways using google but all of them seemed hard to implement. Now i am going to show you can do it in an easy simple way.There are many ways to add captcha to your CakePHP […] LD_AddCustomAttr("AdOpt", "1"); LD_AddCustomAttr("Origin", "other"); LD_AddCustomAttr("theme_bg", "ffffff"); LD_AddCustomAttr("theme_text", "333333"); LD_AddCustomAttr("theme_link", "0066cc"); LD_AddCustomAttr("theme_border", "f2f7fc"); LD_AddCustomAttr("theme_url", "ff4b33"); LD_AddCustomAttr("LangId", "1"); LD_AddCustomAttr("Autotag", "technology"); LD_AddCustomAttr("Tag", "php"); LD_AddSlot("wpcom_below_post"); LD_GetBids(); Rate this: Share this:FacebookDiggStumbleUponEmailLike this:LikeBe the first to like this post. This entry was posted in PHP. Bookmark the permalink. ← Using the Graph API to Get Permissions Granted By Facebook user […]

  2. miguel says:

    hi, can you upload the files,again?

  3. Zakir Hyder says:

    Download link is updated.

  4. hoss says:

    what is this line and image?:
    <img src="webroot;?>css/images/tst_reset_button.jpg” alt=”reset” border=”0″ />

  5. hoss says:

    i see this eror:Fatal error: Class ‘captcha’ not found in D:\xampp\htdocs\mb\app\Controller\UsersController.php on line 26

    when i have run your code.

    note: i have copy you code in app/vendor/captcha

    and i have UsersController and insert your function:
    function captcha_image(){
    App::import(‘Vendor’, ‘captcha’);
    $captcha = new captcha();
    $captcha->show_captcha();
    }
    in this controller and whene i am run this function i see this error.

  6. hoss says:

    i think your code not work with cakephp 2.1,please fix it.

  7. Zakir Hyder says:

    Hoss,
    “i think your code not work with cakephp 2.1,please fix it.”
    =>I updated code for importing vendor file. Should solve your problem.

    what is this line and image?:
    <img src="webroot;?>css/images/tst_reset_button.jpg” alt=”reset” border=”0″ />
    =>This is for reseting Captcha. Check the code. you can use image like this <img src="webroot;?>css/images/tst_reset_button.jpg” alt=”reset” border=”0″ /> or text as mention in the post

    “i see this eror:Fatal error: Class ‘captcha’ not found in D:\xampp\htdocs\mb\app\Controller\UsersController.php on line 26”
    =>Use App::import(‘Vendor’, ‘captcha/captcha’);

  8. hoss says:

    whene i run your code again i see this error: “captcha error”

    note:i am insert your code in my project, like you say.

    are you test your code in cakephp 2.1 ?

  9. hoss says:

    in cakephp 2.1 you must edit your code like this :
    $html->url => $this->Html->url

  10. Zakir Hyder says:

    Hoss, You have to put the “captcha” folder on path-to-cakephp-2.1/vendors/ for CakePHP 2.1 – on root vendors folder. $html->url will work up to CakePHP 1.3.

  11. Jonathan says:

    Thanks for the captcha however, I’m unable to get the captcha image to appear. I tried this on a freshly unzipped version of cake 2.1. I unzipped and added the captcha folder to vendors (not app/vendor). I added the function to my PagesController right above my display function (have also tried it below). And finally added the couple lines of code to the home.ctp view. Is there possibly something I’m missing or can you add a zipped working example to download? Thanks

  12. Zakir Hyder says:

    Jonathan,
    You are right. In fresh CakePHP 2.1 – the captcha_image() function on PagesController does not work. But what you can do is put the code on display() function
    App::import(‘Vendor’, ‘captcha/captcha’);
    $captcha = new captcha();
    $captcha->show_captcha();
    Then you will see the captcha.
    Since 2.1 the Pages Controller is no longer part of the core but ships in the app folder. But this is not ideal. So my advice would be create UsersController and put the captcha_image() on that controller and and use $this->Html->url(‘/users/captcha_image’).

  13. Jonathan says:

    Thanks, I got it working.

  14. Zakir Hyder says:

    You are welcome.

  15. hoss says:

    javascript error:

    syntax error
    [Break On This Error]

    javascript:document.images.captcha.src=

  16. hoss says:

    my code:

    <img id="captcha" src="Html->url(‘/users/captcha_image’);?>” alt=”” />

    <a href="javascript:void(0);"
    onclick="javascript:document.images.captcha.src="Html->url(“/users/captcha_image”);?>?” + Math.round(Math.random(0)*1000)+1″ >Reset

  17. Zakir Hyder says:

    “Html->url(‘/users/captcha_image’)” should be “$Html->url(‘/users/captcha_image’)” – you missed $ sign. Also depending on your CakePHP version use $this. Check the top part of the post

  18. hoss says:

    i am edit my code like you say,but i have this error:
    javascript error:

    syntax error
    [Break On This Error]

    javascript:document.images.captcha.src=

    ————

    <img id="captcha" src="Html->url(‘/users/captcha_image’);?>” alt=”” />

    Form->input(‘captcha’, array(‘label’ => ‘کد امنیت:’,’class’=>’validate[required] input_field ui-state-default ui-corner-all’,’data-prompt-position’=>’centerLeft’));
    ?>

    <a href="javascript:void(0);"
    onclick="javascript:document.images.captcha.src="Html->url(“/pages/captcha_image”);?>?” + Math.round(Math.random(0)*1000)+1″ >Reset

  19. hoss says:

    Zakir Hyder i am post my code,but your comment system change my code and remove some code like $,please email me

    hossbit{a}gmail{.}com

  20. Zakir Hyder says:

    Hoss,
    Can you send me the url so that i can check it. BTW you can post the code with http://pastebin.com/ . Also send the error you are getting?

  21. rahul vats says:

    Path for noise image is wrong
    please update with:

    $path= APP.’vendors\captcha\captcha\images\noise.jpg’;

    and for font
    $path2 = APP.’vendors\captcha\captcha\fonts\BIRTH_OF_A_HERO.ttf’;

  22. Zakir Hyder says:

    Which CakePHP version you are using? My path is correct on all the version I mentioned. I mentioned all of them at the start of the post. VENDORS constant will give you correct vendor path. Why are you using “\captcha\captcha” ? the captcha folder should be under VENDOR folder. so it will like this VENDOR->captcha not VENDOR->captcha->captcha.

  23. Milos says:

    I have a problem.. I have successfully made your plugin work as a single project (so I have all the things i need for this to run), but in cakephp i always get blank image.
    I noticed it has to do something with the header. I have checked every file for a blank space and line in the end, all of my files are utf-8, I have placed debug to 0 so that it doesn’t mix up with header information, and I just cant seem to find the thing. I am using cakephp 1.3 version. Can you please give me an idea on why I get the blank image always. I have placed my function in users controller, the function is allowed, and I have no idea what else I can do.
    Thank you !

  24. Milos says:

    It looks like cake does something to the output so it destroys or corrupts image. Is there a way for me to get the full page so I can compare normal one and cakes …

  25. Milos says:

    Addon to my question:

    in Mozilla firefox it says the image cannot be displayed because it contains errors..

    sorry for spamming Im just desperate now….

  26. Zakir Hyder says:

    Make sure the session_name() on captcha.php is same on core.php’s Configure::write(‘Session.cookie’,”); Then make sure $_SESSION[‘captcha’] is getting value to be sure. Then make sure $imgpath has correct value. BTW truning of debug mode does not turn off errors on captcha.php as it is separate from cakephp. Try putting on browser like http://server/controller/captcha_function.

  27. Milos says:

    Hey sorry for not answering sooner, I was delayed by some personal things.
    Anyways, I tried all you did, but it looks like I have some other problem because I tried some basic drawing of pictures and it failed (i went to http://php.net/).
    But you gave me a good place to start. I hope I’ll make now ..