Oct 222011
 

I built a captcha for a friend a while back for a shopping site, obviously it was too simple to be corrupted so I built this new one last night. It was not perfect though, as I don’t have enough knowledge to create dynamic fonts.

Under Ubuntu it is easy to get things work – install php5-gd, luckily it brought couple of fonts and then the script works like a charm. Under my friend’s machine I need to install some extra packages to get TrueType fonts, but it is not that hard.

Let’s see how this works, I believe the captcha is a little bit hard to be read, but it can block spammers.

  2 Responses to “Captcha”

  1. Forgot to post code …

    <?php
    session_start();
    
    $fonts = array(
        '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf',
        '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf',
        '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono.ttf',
        '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono-Bold.ttf',
        '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif.ttf',
        '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif-Bold.ttf',
    );
    
    $code = sprintf("%06d", rand(0,999999));
    $weird = imagecreatetruecolor(160, 30);
    
    $left = 5;
    for ($index=0; $index<strlen($code); $index++) {
        $size = rand(15, 20); // sizes are between 10 and 20
        $angle = rand(0, 90) - 45; // angles are between -45 and 45 degrees
        $base_height = rand(20, 25); // bottom line of the character are between 20 and 25
        $color = imagecolorallocate($weird, rand(128,255), rand(128,255), rand(128,255)); // random color needs to be bright
        $font = $fonts[rand(0, count($fonts)-1)];
        $coords = imagettfbbox($size, $angle, $font, substr($code, $index, 1));
        $left -= min($coords[0], $coords[6]);
        imagettftext($weird, $size, $angle, $left, $base_height, $color, $font, substr($code, $index, 1));
        $left += max($coords[2], $coords[4]);
    }
    
    for ($index=0; $index<6; $index++) {
        imageline($weird,rand(0,160),rand(0,30),rand(0,160),rand(0,30),imagecolorallocate($weird, rand(128,255), rand(128,255), rand(128,255)));
    }
    
    $_SESSION['secret'] = md5($code);
    header("Content-type: image/png");
    imagepng($weird);
    ?>
    
  2. I need to find a good plugin for WordPress for better code posting, so far the codes look really ugly …

Sorry, the comment form is closed at this time.