Howto do a Captcha in Symfony – with Plugins

May 3, 2007

There has quite some time passed since i blogged about how to do a captcha with the JpGraph library.
Since then, two new plugins have shown up in order to ease the captcha integration in symfony projects.

The sfCaptchaPlugin uses the JpGraph library while the sfCryptographpPlugin relies on the cryptographp library.
Both plugins have installation instructions in their wiki-pages, but there are small things that might confuse new users, so i decided to write a howto for both of them.

sfCaptchaPlugin

First, install the plugin:

symfony plugin-install http://plugins.symfony-project.com/sfCaptchaPlugin

and enable the module in the settings.yml file (e.g. apps/frontend/config/settings.yml):

all:
  .settings:
    enabled_modules: [default, sfCaptcha]

The sfCaptchaPlugin comes with the digits-only version of the JpGraph library (which is much more readable than the alphanumeric version), but in order to use it you need to open the plugins/sfCaptchaPlugin/lib/Captcha.class.php file and change:

require_once 'jpgraph/jpgraph_antispam.php';

to:

require_once 'jpgraph_antispam-digits.class.php';

Now we need to generate the captcha and save the key in the session. Add the following lines to the function which displays your form:

$g = new Captcha();
$this->getUser()->setAttribute('captcha', $g->generate());

and in the template, add:

<?php use_helper('Validation'); ?>

<img src="<?php echo url_for('sfCaptcha/index'); ?>" alt="captcha" />
<?php echo form_error('captcha'); ?>
<?php echo input_tag('captcha'); ?>

To validate the input, create a validation file in your modules validate folder and add:

fields:
  captcha:
    required:
      msg: Please enter the numbers in the captcha image
    captchaValidator:
      error: Incorrect code

Finally, clear your cache with symfony cc and the captcha should be ready.

sfCryptographpPlugin

Install the plugin with:

symfony plugin-install http://plugins.symfony-project.com/sfCryptographpPlugin

and enable the module in the settings.yml file (e.g. apps/frontend/config/settings.yml):

all:
  .settings:
    enabled_modules: [default, cryptographp]

Open the template file which contains your form, and add:

<?php use_helper('Cryptographp', 'Validation'); ?>

<?php echo cryptographp_picture(); ?>
<?php echo cryptographp_reload(); ?>

<?php echo form_error('captcha'); ?>
<?php echo input_tag('captcha'); ?>

To validate the input, create a validation file in your modules validate folder and add:

fields:
  captcha:
    required:
      msg: security code required
    sfCryptographpValidator:
      code_error: security code incorrect

Finally, clear your cache with symfony cc and you should be ready to go.

Unlike JpGraph, the cryptohraphp lib comes with a variety of config options, you can take a look at the documentation and the plugins/sfCryptographpPlugin/lib/crypt/config.inc.php file.
For example, if you want to modify the width of the captcha image, open your applications app.yml file and add:

all:
  cryptographp:
    width: 300
Advertisements

45 Responses to “Howto do a Captcha in Symfony – with Plugins”

  1. mumble Says:

    Excellent cookbook dude! Might I add that the php_gd2.dll extension of PHP needs to be enabled for the JPGraph library to run. I tried downloading the sfJPGraph plugin but it didn’t work so I downloaded the JPGraph library (v2.2) instead and installed it in my project’s lib folder. The library worked when I expanded the files into a folder like so: C:\home\vhosts\testbed.wlprojects.com\lib\jpgraph\

    Again, kudos to you good sir!

  2. Gwenaelle Says:

    Thanks a lot !!!
    You kinda save my life ;)
    I was making a mistake with the file settings.yml where I kept writing :
    enabled_modules: [default, sfCryptographpPlugin]
    and wonders why on earth it doesn’t work :s

  3. renji Says:

    i’ve got a question, why the image in captcha doesn’t show?where will i put my images in order to be called?
    thanks

  4. Martin H Says:

    Since I didn’t get sfCaptchaPlugin working after many tries the sfCryptographpPlugin worked at once. Thanks for your description.

  5. Susan Says:

    Hi,

    found your reCaptchaPlugin for symfony1.0.10 and was wondering, if there will be an update for symfony1.1 with the new formHandling.

    Greetings
    Susan

  6. Arthur Says:

    Hi Susan,

    As soon as Symfony 1.1 hits beta status i’m going to work on it.

    PS.: Further updates are going to be on my new blog http://arthurkoziel.com

    Arthur.

  7. Ben Wann Says:

    Thanks for this post! Very helpful!

  8. Jonathan Says:

    This tutorial is wrong re; jpGraph.

    It is not bundled with sfCaptchaPlugin.

  9. Susan Says:

    symfony1.1 is now better than beta. I started to think about a solution for sfReCaptcha. But maybe you are already working on this?

    Greetings
    Susan

  10. Arthur Says:

    Hey Susan, I indeed started to work on it but it’s still not finished. The documentation on sfForm in sf1.1 ist still very sparse so it may still take some time.

  11. Susan Says:

    yeah. I can imaging :-)
    I am glad, that we have now a sfForm-documentation. But it is still not enough. You are right. I try to be patient ;-)

  12. dfuentesh Says:

    problem: Image doesn’t appear.
    solution:
    1.-make sure you have gd libraries enabled.
    2.-if u’re using sfguardplugin, then disable security for this action.
    My first test was:
    in the file “project_name/apps/app_name/config/security.yml”
    change from:
    default:
    is_secure: on

    to
    default:
    is_secure: off
    and it worked..so I disable the security in the action, and validate every input in the form.
    Hope this help. C’ya

  13. nitin Says:

    Hi , I followed the eact same configuration steps provided by you.

    I was really in a serious fix gettimg the image to load and show up on the template…

    I would like to further add that I have configured security to

    default:
    is_secure: off

    in /apps/frontend/config/security.yml file

    any immediate help would be appreciated..

    thanks a million in advance :)

  14. nitin Says:

    Hi,

    I’ve been trying to figure out one thing,

    in my settings.yml file, I have enabled sfCaptcha using:
    enabled_modules: [ default, sfCaptcha ]

    but I’m still unable to fix the exception that says,

    The module “sfCaptcha” is not enabled.

    the steps given above are helping me set the session properly, but I am unable to get the image working

    I browsed through the plugin and found out that it is actions.class.php in the plugin using the index action

    which plots the image

    so I even created a view.yml with http_metas as image/png

    and when I directly access indexSuccess.php through the url to see if the image is getting generated,

    it throws an exception

    The module “sfCaptcha” is not enabled.

    can you please get me out of this mess…

  15. Marc Says:

    @nitin

    Had the same trouble with sf1.1, check this forum post: http://forum.symfony-project.org/index.php/m/83055/

    Hope it helps

  16. Cialis Says:

    kaMpvf Excellent article, I will take note. Many thanks for the story!

  17. scandi Says:

    Thehttp://www.scandi-tours.com – . details unbefitting overlie routes to Denmark, Norway, Sweden and Finland from the UK and Ireland. With a view the aid of connections within Scandinavia itself, formulate of the “Getting There” sections inasmuch as each Lone country. AT NEAR MEANS OF UNINTERRUPTED Flying to Scandinavia isn’t unusually cheap. Lowcost franchise flights do hint at, but they’re some and incomparably between and not skylarking tricks on at worst insignificant destinations; more Bumf follows, and is within reach from the operators listed controlled on “Packages”. In many cases the finest startingpoint in place of the cheapest deals to Scandinavia is the classified sections in the Sunday newspapers

  18. scandi Says:

    Thehttp://www.scandi-tours.com – . details protection mask routes to Denmark, Norway, Sweden and Finland from the UK and Ireland. During connections within Scandinavia itself, across the “Getting There” sections after each Lone country. RATHER THAN UNINTERRUPTED Flying to Scandinavia isn’t notably cheap. Lowcost sublease visible flights do breathe, but they’re some and unimportant between and be at someone’s beck on the antagonistic arranged destinations; more Think over follows, and is up to stage from the operators listed non-critical to “Packages”. Much the richest startingpoint on account of the cheapest deals to Scandinavia is the classified sections in the Sunday newspapers


  19. Hallo Admin , i love with ur article. LOL Please come to my blog

  20. geldeasy Says:

    Whenever an individual don’t possess self confidence, you will continually come across a way not to succeed

  21. UntortAlete Says:

    20 май 2011 Ледяная диета – эта диета балерин,так как именно они следят за своей фигурой используя холодную пищу. При переваривании холодной пищи
    Блог о диетах и полезном питании, диеты от знаменитостей. Фитнес и секреты похудения.
    Длительность диеты составляет 10 дней, в течение которых вы не только почистите свой кишечник, но и улучшите все обменные процессы организма,
    Самые эффективные диеты и полезные статьи для женщин собраны на нашем сайте. Заходите и выбирайте для себя более подходящую Вам! И худейте легко и правильно
    Кремлевская диета представляет собой одну из разновидностей низкоуглеводных диет. В целом, она является аналогом диеты Аткинса, однако, ее приверженцам

  22. Rxroqkdo Says:

    Would you like a receipt? little boys masturbation kehmsj

  23. Jloyzemo Says:

    We’ll need to take up references teen sex help :)))

  24. Uopipmte Says:

    I work for a publishers preteen angels
    40453

  25. Ytnxsljl Says:

    Is this a temporary or permanent position? pthc boys
    uozl

  26. Zcmyuyhr Says:

    Sorry, you must have the wrong number underage girl
    scj

  27. Lqbdgdsn Says:

    We’ve got a joint account smuggler bbs
    %[[

  28. Idpljjtw Says:

    We’ve got a joint account zeps bbs guide
    :]]]

  29. Cstqzdve Says:

    Could I have a statement, please? pedo paradise
    =D

  30. Kgihjgqc Says:

    I’m sorry, I didn’t catch your name cp top sites
    wnameb

  31. rerBragsBox Says:

    Лучшие футболки мира в России
    Заходи.
    Выбирай.
    Покупай!

  32. Mgudlfbk Says:

    I’d like to send this letter by http://pobiinimehe.de.tl japan porn model yu ppl dnt no gud quality if it hit yu in the head jus cuz its long doesnt mean its gud first off dem bitches cnt eat pussy second of all da shits so fake dey werent experimentin obviously da blonde one was gay to begin wit becuz of her tattoo dis shit was pure trash

  33. Focczlgj Says:

    Who would I report to? http://gulanauler.de.tl nymphet sweet Same, you have no idea how excited I got when the first Viv Thomas video came back. They are fucking amazing.


  34. Simply want to say your article is as amazing. The clearness in your post is simply excellent
    and i can assume you’re an expert on this subject. Well with your permission allow me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please carry on the gratifying work.


  35. Greate post. Keep posting such kind of info on your
    site. Im really impressed by it.
    Hey there, You’ve done a great job. I will definitely digg it and in my opinion recommend to my friends. I am sure they’ll be benefited
    from this web site.


  36. I was recommended this web site by my cousin. I am not sure whether this post is written by him as no one else know such detailed about my trouble.

    You are incredible! Thanks!


  37. Thanks for the auspicious writeup. It in truth was once
    a entertainment account it. Glance complex to far introduced agreeable from you!
    By the way, how could we keep in touch?


  38. Howdy! This article could not be written much better! Looking through this post reminds me of my previous roommate!
    He always kept talking about this. I am going to sennd this article tto him.
    Fairly certain he’ll have a very good read.
    Thank you for sharing!

  39. bigo Says:

    С тоником Skinformer растяжки и целлюлит останутся в прошлом! …
    http://big-butik.ru/


  40. whoah thjs blog is excellent i really like studying your
    posts. Keep up the good work! You understand, lots
    of individuals are looking round for this information, you can help them greatly.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: