Create captcha in php

3 Steps Simple Captcha In PHP (Free Download)

Welcome to a tutorial on how to create a simple captcha in PHP. Have a website that is constantly being spammed by angry keyboard warriors? Time to put in some security and prevention measures. Let us walk through an example in this guide, without the use of any 3rd party frameworks – Read on!

TABLE OF CONTENTS

PHP CAPTCHA

All right, let us now get into the details of creating a simple PHP captcha.

STEP 1) PHP CAPTCHA CLASS

 if (session_status()==PHP_SESSION_NONE) < session_start(); >> // (C) PRIME THE CAPTCHA - GENERATE RANDOM STRING IN SESSION function prime () : void < $char = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $max = strlen($char) - 1; $_SESSION["captcha"] = ""; for ($i=0; $ilength; $i++) < $_SESSION["captcha"] .= substr($char, rand(0, $max), 1); >> // (D) DRAW THE CAPTCHA IMAGE function draw ($mode=0) : void < // (D1) FUNKY BACKGROUND IMAGE if (!isset($_SESSION["captcha"])) < exit("Captcha not primed"); >$captcha = imagecreatetruecolor($this->capW, $this->capH); list($bx, $by) = getimagesize($this->capB); $bx = ($bx-$this->capW) < 0 ? 0 : rand(0, ($bx-$this->capW)); $by = ($by-$this->capH) < 0 ? 0 : rand(0, ($by-$this->capH)); imagecopy($captcha, imagecreatefromjpeg($this->capB), 0, 0, $bx, $by, $this->capW, $this->capH); // (D2) RANDOM TEXTBOX POSITION $ta = rand(-20, 20); // random angle $tc = imagecolorallocate($captcha, rand(120, 255), rand(120, 255), rand(120, 255)); // random text color $ts = imagettfbbox($this->capFS, $ta, $this->capF, $_SESSION["captcha"]); if ($ta>=0) < $tx = rand(abs($ts[6]), $this->capW - (abs($ts[2]) + abs($ts[6]))); $ty = rand(abs($ts[5]), $this->capH); > else < $tx = rand(0, $this->capW - (abs($ts[0]) + abs($ts[4]))); $ty = rand(abs($ts[7]), abs($ts[7]) + $this->capH - (abs($ts[3]) + abs($ts[7]))); > imagettftext($captcha, $this->capFS, $ta, $tx, $ty, $tc, $this->capF, $_SESSION["captcha"]); // (D3) OUTPUT CAPTCHA if ($mode==0) < ob_start(); imagepng($captcha); $ob = base64_encode(ob_get_clean()); echo ""; > else < header("Content-type: image/png"); imagepng($captcha); imagedestroy($captcha); >> // (E) VERIFY CAPTCHA function verify ($check) < if (!isset($_SESSION["captcha"])) < exit("Captcha not primed"); >if ($check == $_SESSION["captcha"]) < unset($_SESSION["captcha"]); return true; >else < return false; >> > // (F) CAPTCHA OBJECT $PHPCAP = new Captcha();

First, we start with the “core engine”, the Captcha library. Yes, this looks complicated at first, but keep calm and explore it slowly.

Оцените статью