Image verification code

How Can I generate Image verification code?

If you have to use custom image captcha David's solutions are great.

However i would recommend to always use Google Recatpca services. Pros:

  • easy for your users, you dont annoy them with hard to understand images

  • accessible (allows users with poor/no vision to use your application, while image only captchas fail)

  • better security

  • easy implementation

More info here: https://www.google.com/recaptcha/intro/index.html

Here is a sample implementation with Phalcon forms i did some time ago:

// Create your own form Element
use Phalcon\Forms\Element;
class Recaptcha extends Element
{ 
    public function render($attributes = null) 
    { 
        $html = '<script src="https://www.google.com/recaptcha/api.js?hl=bg"></script>';
        $html.= '<div class="g-recaptcha" data-sitekey="6LdnfAcTAAAAAM5V0z2SbpR0YfandnDmuc9wwzu1"></div>';
        return $html;
    }
}

// Validation
use Phalcon\Validation\Validator;
use Phalcon\Validation\ValidatorInterface;
use Phalcon\Validation\Message;

class RecaptchaValidator extends Validator implements ValidatorInterface
{ 
    public function validate(\Phalcon\Validation $validation, $attribute) 
    { 
        $value = $validation->getValue('g-recaptcha-response');
        $ip = $validation->request->getClientAddress();

        if (!$this->verify($value, $ip)) {
            $validation->appendMessage(new Message($this->getOption('message'), $attribute, 'Recaptcha'));
            return false;
        }
        return true;
    }

    protected function verify($value, $ip) 
    { 
        $params = array(
            'secret' => '6LdnfAcTAAAAAE4kxJ_eLL1dS9uZCj6PH3CU0bQH',
            'response' => $value,
            'remoteip' => $ip
        );
        $response = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?' .http_build_query($params)));

        return (bool)$response->success;
    } 
}

It would be even better if you set your recaptcha keys in a config file. Its a thing on my Todo list someday when i have more free time :)

edited Mar '16

https://github.com/pavlosadovyi/phalcon-recaptcha is just wrapper over http://www.google.com/recaptcha

Anyway, thanks for your code.

My bad i didnt even notice the repos were recaptca warppers. Sorry for the spam then :)