Skip to main content

PHP captcha code generation, submission and verification

PHP Code Submission & Verification:
The following code is for the submission and verification of the captcha code entered by user and redirect the user to an other page.

<?php
print '<html><head><link type="text/css" rel="stylesheet" href="http://localhost/php/account/photo.css"/><title>Captcha</title></head><body>';
$error = NULL;
if (isset($_REQUEST['confirm_code'])) {
    if (isset($_COOKIE['Captcha'])) {
        list($Hash, $Time) = explode('.', $_COOKIE['Captcha']);
        if (md5("OASDOIJQWOIJDASDOI" . strtoupper($_REQUEST['confirm_code'] . $_SERVER['REMOTE_ADDR'] . $Time)) != $Hash) {
            $error = '<marquee behavior="slide" direction="up" width="100%" height="2.5%" style="text-align: center;" id="pop-up"><div width="100%" style="text-align: center;"><em>Invalid Captcha Code!</em></div></marquee>';
        } elseif ((time() - 5 * 60) > $Time) {
            $error = '<marquee behavior="slide" direction="up" width="100%" height="2.5%" style="text-align: center;" id="pop-up"><div width="100%" style="text-align: center;"><em>Captcha code is only valid for 5 minutes!</em></div></marquee>';
        } else {
            if (isset($_GET[md5("signup")]))
                die(header("location:http://localhost/php/account/upload.php?" . md5("signup")));
            else
                die(header("location:http://localhost/php/account/login.php?" . hash('sha256', 'cookies')));
        }
    } else {
        $error = '<marquee behavior="slide" direction="up" width="100%" height="2.5%" style="text-align: center;
                    " id="pop-up"><div width="100%" style="text-align: center;
                    "><em>No captcha cookie given. Make sure cookies are enabled!</em></div></marquee>';
    }
}
if (isset($_GET[md5("signup")])) {
    print '<div id="main" align="center"><form method="post"><div style="background-color: #009CE8;"><img src="http://localhost/php/account/easycaptcha.php"/><br />
                    Enter code from above image: <input type = "text" autofocus name = "confirm_code" maxlength = "5"/><br /><a href = "?' . md5("refresh") . '" > Try another code?</a><br />
                    <hr></div><input type = "submit" value = "Submit"/></form></div></body></html>' . $error;
} else {
    //print $hd;
    print '
                    <style>
#main{
                    background-color: #009CE8;
                    color: white;
                    }
                    </style>
                    <div id = "main" align = "center">
                    <span id = "error">You must login before viewing this page. This for the safety of the contents of the page.<br>
                    <a href = "http://localhost/php/account/login.php">Click Here To Login</a>
                    </span>
                    </div>';
}
?>

easycaptcha.php Contains the following script:

<?php
require('php-captcha.inc.php');
$fonts = array('', 'Bd', 'BI', 'It', 'MoBd', 'MoBI', 'MoIt', 'Mono', 'Se', 'SeBd');
for ($i = 0; $i < count($fonts); $i++)
    $fonts[$i] = 'fonts/Vera' . $fonts[$i] . '.ttf';//define your own font path
$alphabet = 'A_B_C_D_E_F_G_H_I_J_K_L_M_N_O_P_Q_R_S_T_U_V_W_X_Y_Z_0_1_2_3_4_5_6_7_8_9';
//a_b_c_d_e_f_g_h_i_j_k_l_m_n_o_p_q_r_s_t_u_v_w_x_y_z;
$alphabet = explode('_', $alphabet);
shuffle($alphabet);
$captchaText = '';
for ($i = 0; $i < 5; $i++) {
    $captchaText .= $alphabet[$i];
}
$time = time();
setcookie('Captcha', md5("OASDOIJQWOIJDASDOI" . $captchaText . $_SERVER['REMOTE_ADDR'] . $time) . '.' . $time, null, '/');
$oVisualCaptcha = new PhpCaptcha($fonts, strlen($captchaText) * 23, 60);
$oVisualCaptcha->UseColour(true);
$oVisualCaptcha->CaseInsensitive(true);
$oVisualCaptcha->SetHeight(100);
$oVisualCaptcha->SetWidth(280);
$oVisualCaptcha->SetMaxFontSize(38);
$oVisualCaptcha->SetMinFontSize(28);
$oVisualCaptcha->Create($captchaText);
?>

php-captcha.inc.php contains the following code:

<?php
session_start();
define('CAPTCHA_SESSION_ID', 'php_captcha');
define('CAPTCHA_WIDTH', 200); // max 500
define('CAPTCHA_HEIGHT', 50); // max 200
define('CAPTCHA_NUM_CHARS', 5);
define('CAPTCHA_NUM_LINES', 70);
define('CAPTCHA_CHAR_SHADOW', false);
define('CAPTCHA_OWNER_TEXT', '');
define('CAPTCHA_CHAR_SET', ''); // defaults to A-Z
define('CAPTCHA_CASE_INSENSITIVE', false);
define('CAPTCHA_BACKGROUND_IMAGES', '');
define('CAPTCHA_MIN_FONT_SIZE', 16);
define('CAPTCHA_MAX_FONT_SIZE', 25);
define('CAPTCHA_USE_COLOUR', false);
define('CAPTCHA_FILE_TYPE', 'jpeg');
define('CAPTCHA_FLITE_PATH', '/usr/');
define('CAPTCHA_AUDIO_PATH', '/tmp/');
class PhpCaptcha {
    var $oImage;
    var $aFonts;
    var $iWidth;
    var $iHeight;
    var $iNumChars;
    var $iNumLines;
    var $iSpacing;
    var $bCharShadow;
    var $sOwnerText;
    var $aCharSet;
    var $bCaseInsensitive;
    var $vBackgroundImages;
    var $iMinFontSize;
    var $iMaxFontSize;
    var $bUseColour;
    var $sFileType;
    var $sCode = '';
    function PhpCaptcha(
    $aFonts, $iWidth = CAPTCHA_WIDTH, $iHeight = CAPTCHA_HEIGHT
    ) {
        $this->aFonts = $aFonts;
        $this->SetNumChars(CAPTCHA_NUM_CHARS);
        $this->SetNumLines(CAPTCHA_NUM_LINES);
        $this->DisplayShadow(CAPTCHA_CHAR_SHADOW);
        $this->SetOwnerText(CAPTCHA_OWNER_TEXT);
        $this->SetCharSet(CAPTCHA_CHAR_SET);
        $this->CaseInsensitive(CAPTCHA_CASE_INSENSITIVE);
        $this->SetBackgroundImages(CAPTCHA_BACKGROUND_IMAGES);
        $this->SetMinFontSize(CAPTCHA_MIN_FONT_SIZE);
        $this->SetMaxFontSize(CAPTCHA_MAX_FONT_SIZE);
        $this->UseColour(CAPTCHA_USE_COLOUR);
        $this->SetFileType(CAPTCHA_FILE_TYPE);
        $this->SetWidth($iWidth);
        $this->SetHeight($iHeight);
    }
    function CalculateSpacing() {
        $this->iSpacing = (int) ($this->iWidth / $this->iNumChars);
    }
    function SetWidth($iWidth) {
        $this->iWidth = $iWidth;
        $this->CalculateSpacing();
    }
    function SetHeight($iHeight) {
        $this->iHeight = $iHeight;
        if ($this->iHeight > 200)
            $this->iHeight = 200;
    }
    function SetNumChars($iNumChars) {
        $this->iNumChars = $iNumChars;
        $this->CalculateSpacing();
    }
    function SetNumLines($iNumLines) {
        $this->iNumLines = $iNumLines;
    }
    function DisplayShadow($bCharShadow) {
        $this->bCharShadow = $bCharShadow;
    }
    function SetOwnerText($sOwnerText) {
        $this->sOwnerText = $sOwnerText;
    }
    function SetCharSet($vCharSet) {
        if (is_array($vCharSet)) {
            $this->aCharSet = $vCharSet;
        } else {
            if ($vCharSet != '') {
                $aCharSet = explode(',', $vCharSet);
                $this->aCharSet = array();
                foreach ($aCharSet as $sCurrentItem) {
                    if (strlen($sCurrentItem) == 3) {
                        $aRange = explode('-', $sCurrentItem);
                        if (count($aRange) == 2 && $aRange[0] < $aRange[1]) {
                            $aRange = range($aRange[0], $aRange[1]);
                            $this->aCharSet = array_merge($this->aCharSet, $aRange);
                        }
                    } else {
                        $this->aCharSet[] = $sCurrentItem;
                    }
                }
            }
        }
    }
    function CaseInsensitive($bCaseInsensitive) {
        $this->bCaseInsensitive = $bCaseInsensitive;
    }
    function SetBackgroundImages($vBackgroundImages) {
        $this->vBackgroundImages = $vBackgroundImages;
    }
    function SetMinFontSize($iMinFontSize) {
        $this->iMinFontSize = $iMinFontSize;
    }
    function SetMaxFontSize($iMaxFontSize) {
        $this->iMaxFontSize = $iMaxFontSize;
    }
    function UseColour($bUseColour) {
        $this->bUseColour = $bUseColour;
    }
    function SetFileType($sFileType) {
        if (in_array($sFileType, array('gif', 'png', 'jpeg'))) {
            $this->sFileType = $sFileType;
        } else {
            $this->sFileType = 'jpeg';
        }
    }
    function DrawLines() {
        for ($i = 0; $i < $this->iNumLines; $i++) {
            if ($this->bUseColour) {
                $iLineColour = imagecolorallocate($this->oImage, rand(100, 250), rand(100, 250), rand(100, 250));
            } else {
                $iRandColour = rand(100, 250);
                $iLineColour = imagecolorallocate($this->oImage, $iRandColour, $iRandColour, $iRandColour);
            }
            imageline($this->oImage, rand(0, $this->iWidth), rand(0, $this->iHeight), rand(0, $this->iWidth), rand(0, $this->iHeight), $iLineColour);
        }
    }
    function DrawOwnerText() {
        $iBlack = imagecolorallocate($this->oImage, 0, 0, 0);
        $iOwnerTextHeight = imagefontheight(2);
        $iLineHeight = $this->iHeight - $iOwnerTextHeight - 4;
        imageline($this->oImage, 0, $iLineHeight, $this->iWidth, $iLineHeight, $iBlack);
        imagestring($this->oImage, 2, 3, $this->iHeight - $iOwnerTextHeight - 3, $this->sOwnerText, $iBlack);
        $this->iHeight = $this->iHeight - $iOwnerTextHeight - 5;
    }
    function GenerateCode() {
        $this->sCode = '';
        for ($i = 0; $i < $this->iNumChars; $i++) {
            if (count($this->aCharSet) > 0) {
                $this->sCode .= $this->aCharSet[array_rand($this->aCharSet)];
            } else {
                $this->sCode .= chr(rand(65, 90));
            }
        }
        if ($this->bCaseInsensitive) {
            $_SESSION[CAPTCHA_SESSION_ID] = strtoupper($this->sCode);
        } else {
            $_SESSION[CAPTCHA_SESSION_ID] = $this->sCode;
        }
    }
    function DrawCharacters() {
        $palette = array();
        for ($i = 0; $i < 10; $i++) {
            if ($this->bUseColour) {
                if ($this->bCharShadow)
                    $palette[$i] = imagecolorallocate($this->oImage, 225, 225, 225);
                else {
                    $palette[$i] = imagecolorallocate($this->oImage, 225, 225, 225);
                }
            } else {
                if ($this->bCharShadow)
                    $palette[$i] = imagecolorallocate($this->oImage, $iRandColour, $iRandColour, $iRandColour);
                else {
                    $iRandColour = rand(0, 100);
                    $palette[$i] = imagecolorallocate($this->oImage, $iRandColour, $iRandColour, $iRandColour);
                }
            }
        }
        for ($i = 0; $i < strlen($this->sCode); $i++) {
            $sCurrentFont = $this->aFonts[array_rand($this->aFonts)];
            $iTextColour = $palette[array_rand($this->aFonts)];
            $iFontSize = rand($this->iMinFontSize, $this->iMaxFontSize);
            $iAngle = rand(-30, 30);
            $aCharDetails = imageftbbox($iFontSize, $iAngle, $sCurrentFont, $this->sCode[$i], array());
            $iX = $this->iSpacing / 4 + $i * $this->iSpacing;
            $iCharHeight = $aCharDetails[2] - $aCharDetails[5];
            $iY = $this->iHeight / 2 + $iCharHeight / 4;
            imagefttext($this->oImage, $iFontSize, $iAngle, $iX, $iY, $iTextColour, $sCurrentFont, $this->sCode[$i], array());
            if ($this->bCharShadow) {
                $iOffsetAngle = rand(-30, 30);
                $iRandOffsetX = rand(-5, 5);
                $iRandOffsetY = rand(-5, 5);
                imagefttext($this->oImage, $iFontSize, $iOffsetAngle, $iX + $iRandOffsetX, $iY + $iRandOffsetY, $iShadowColour, $sCurrentFont, $this->sCode[$i], array());
            }
        }
    }
    function WriteFile($sFilename) {
        if ($sFilename == '') {
            header("Content-type: image/$this->sFileType");
        }
        switch ($this->sFileType) {
            case 'gif':
                $sFilename != '' ? imagegif($this->oImage, $sFilename) : imagegif($this->oImage);
                break;
            case 'png':
                $sFilename != '' ? imagepng($this->oImage, $sFilename) : imagepng($this->oImage);
                break;
            default:
                $sFilename != '' ? imagejpeg($this->oImage, $sFilename) : imagejpeg($this->oImage);
        }
    }
    function Create($inText = false, $sFilename = '') {
        if (!function_exists('imagecreate') || !function_exists("image$this->sFileType") || ($this->vBackgroundImages != '' && !function_exists('imagecreatetruecolor'))) {
            return false;
        }
        if (is_array($this->vBackgroundImages) || $this->vBackgroundImages != '') {
            $this->oImage = imagecreatetruecolor($this->iWidth, $this->iHeight);
            if (is_array($this->vBackgroundImages)) {
                $iRandImage = array_rand($this->vBackgroundImages);
                $oBackgroundImage = imagecreatefromjpeg($this->vBackgroundImages[$iRandImage]);
            } else {
                $oBackgroundImage = imagecreatefromjpeg($this->vBackgroundImages);
            }
            imagecopy($this->oImage, $oBackgroundImage, 0, 0, 0, 0, $this->iWidth, $this->iHeight);
            imagedestroy($oBackgroundImage);
        } else {
            $this->oImage = imagecreate($this->iWidth, $this->iHeight);
        }
        imagecolorallocate($this->oImage, 0, 156, 232);
        if ($this->sOwnerText != '') {
            $this->DrawOwnerText();
        }
        if ($inText === false)
            $this->GenerateCode();
        else {
            $this->sCode = $inText;
            $this->SetNumChars(strlen($inText));
        }
        $this->DrawCharacters();
        $this->WriteFile($sFilename);
        imagedestroy($this->oImage);
        return true;
    }
    function Validate($sUserCode, $bCaseInsensitive) {
        if ($bCaseInsensitive) {
            $sUserCode = strtoupper($sUserCode);
        }
        if (!empty($_SESSION[CAPTCHA_SESSION_ID]) && $sUserCode == $_SESSION[CAPTCHA_SESSION_ID]) {
            unset($_SESSION[CAPTCHA_SESSION_ID]);
            return true;
        }
        return false;
    }
}
?>

Comments

Popular posts from this blog

Java Program to calculate the Run Rate per over in a cricket match

import java.io.*; import java.util.*; public class RunRate{     Scanner scan=new Scanner(System.in);     int runs, balls;     float runRate;     public void input(){         try{             System.out.println("Enter Runs Scored: ");             runs=scan.nextInt();             System.out.println("Enter Balls Delivered: ");             balls=scan.nextInt();         }         catch(NumberFormatException e){             System.out.println("Error Code: "+e);             System.exit(0);   ...

Vanilla Javascript each()

JQuery's each() is very useful when iterating through elements. But you don't want to use JQuery in your project you can simply add the following javascript code which works somewhat similar to the JQuery's each function. Here the fnc parameter is the function string which is converted to a valid function call replacing all the $(this) with this /**  * This function binds a particular function to every element with the specified selector. It is somewhat same as JQuery's each() with less functionality  * @param {String|DOMElement} selector  * @param {Function} fnc  */ function each(selector, fnc) {     var elem;     if (typeof selector === "string") {         elem = $_(selector);     } else {         elem = selector;     }     fnc = (fnc.toString().replace("$(this)", "elem") + "();").replace("function () {", "").replac...

Java Program to display Welcome Message

import java.io.*;// I/O package imported. public class Welcome{        //class name is "Welcome"     public Welcome(){      //constructor declaired to print the message.         System.out.println("Welcome to Java Programming Language!");/* System.out.println is used for output. Welcome Message is written within " ".*/     }//display() closes here.     public static void main(String[] args){        //main() is declaired to declair an object in it.         Welcome obj=new Welcome();  //Object "Obj" is bean created.     }//main() closes. }//class "Welcome" ends here. Above program displays the message which is written by you in " ".  In programs "/*" and "*/" are use for multiple line comment(s) and "//" is use for single line comment. Code line "Welc...