Home Top Ad

Easy way to add captcha for cakephp , symfony , laravel and any PHP framework without plugin

Share:


CAPTCHA requires that the user type the letters of a distorted image, sometimes with the addition of an obscured sequence of letters or digits that appears on the screen. Because the test is administered by a computer, in contrast to the standard Turing test that is administered by a human, a CAPTCHA is sometimes described as a reverse Turing test. This term is ambiguous because it could also mean a Turing test in which the participants are both attempting to prove they are the computer.

As a web developer using cakephp like my best php framework when i tried to use captcha i've made many searching on internet for a easy way to add it in my form without any results so i figured out  an easy way that i would share with you all in this article.


  1. In your controller "pages" in my case Create a function call it captcha.
  2. Put your code of image in this function with " die(); " in the end .

    Code exemple :

    public function captcha() { $width = 150; $height = 50; //amount of background noise to add in captcha image $noise_level = 20; $code=rand(1110,9999); $this->Session->write('captcha', $code);//create session captcha $im = imagecreatetruecolor(150, 50); $bg = imagecolorallocate($im, 255, 255, 255); //background color blue $fg = imagecolorallocate($im, 101, 101, 101);//text color white $ns = imagecolorallocate($im, 200, 200, 200);//noise color $font=WWW_ROOT.'img/arial2.ttf'; imagettftext($im, 30, -5, 20, 30, $fg, $font, $code); imagesetpixel( $im, 16, 20, $ns ); imagefill($im, 0, 0, $bg); for ($i = 0; $i < $noise_level; $i++) { for ($j = 0; $j < $noise_level; $j++) { imagesetpixel( $im, rand(0, $width), rand(0, $height),//make sure the pixels are random and don't overflow out of the image $ns ); } } header("Cache-Control: no-cache, must-revalidate"); header('Content-type: image/png'); imagepng($im); imagedestroy($im); die(); }
  3. Now put this code : <img src="YourDomaine.com/pages/captcha/" style="border:1px solid #ddd;" > Here is an example of the results :
  4. To validate the captcha test if the val of code equals to session captcha " $this->session->read('captcha'); "

1 commentaire: