<?php
    $img_width = 175;
    $img_height = 50;
    
    $handle = imagecreatetruecolor($img_width, $img_height);    

    $colA = array(mt_rand(175, 255), mt_rand(175, 255), mt_rand(175, 255));
    $colB = array(mt_rand(175, 255), mt_rand(175, 255), mt_rand(175, 255));
    imagecolorgradient($handle, 0, 0, $img_width, $img_height, $colA, $colB);
    
    //random lines
    $num = mt_rand(30, 50);
    for ($i = 0; $i < $num; $i++)
    {
        random_line($handle);
    }
        
    $CURRENT_X = mt_rand(10, 25);

    $length = mt_rand(4, 6);
    $char_arr = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9');

    $code = '';

    for ($i = 0; $i < $length; $i++)
    {
        $char = $char_arr[mt_rand(0, count($char_arr) - 1)];
        apend_letter($handle, $char);
        $code .= $char;
    }

    header('Content-type: image/png'); 
    imagepng($handle);

    if ($GLOBALS['auth']['id'])
    {    
        mysqli_query_logged("REPLACE INTO security_code_last SET user_id = '".$GLOBALS['auth']['id']."', code = '" . $code . "', posted_on = NOW()");
    }
    elseif (isset($_COOKIE['cache']) && $_COOKIE['cache'])
    {    
        mysqli_query_logged("REPLACE INTO security_code_cache SET cache = '".$_COOKIE['cache']."', code = '".$code."', posted_on = NOW()");
    }

    function apend_letter($handle, $letter)
    {
        global $CURRENT_X;
        $gitter = 40 + (mt_rand(-3, 3));
        $font = 'include/fonts/dirtyheadline.ttf';
        $color = imagecolorallocate($handle, mt_rand(0, 200), mt_rand(0, 200), mt_rand(0, 200));
        imagettftext($handle, 32, mt_rand(-10, 10), $CURRENT_X, $gitter, $color, $font, $letter);
        $CURRENT_X += 20 + mt_rand(-2, 6);
    }
    
    function imagecolorgradient($img, $x1, $y1, $width, $height, $colA, $colB) 
    {
        $varC1 = ($colA[0] - $colB[0]) / $height;
        $varC2 = ($colA[1] - $colB[1]) / $height;
        $varC3 = ($colA[2] - $colB[2]) / $height;
        for ($i = 0; $i <= $height; $i++)
        {
            $col = imagecolorallocate($img, $colA[0] - floor($i * $varC1), $colA[1] - floor($i * $varC2),    $colA[2] - floor($i * $varC3));
            imageline($img, $x1, $y1 + $i, $x1 + $width, $y1 + $i, $col);
        }
    }
    
    function random_line($handle)
    {
        global $img_width, $img_height;
        $col = imagecolorallocate($handle, mt_rand(180, 255), mt_rand(180, 255), mt_rand(180, 255));
        imageline($handle, mt_rand(0, $img_width), mt_rand(0, $img_height), mt_rand(0, $img_width), mt_rand(0, $img_height), $col);    
    }
?>