开发者

non captcha token timestamp in cookie vs session

The last days I have been reading some articles about NON Captcha's and more in particular on techniques on how to distinguish robots from humans.

  • Stackoverflow - Alternative to Annoying Captcha in Forms: How to SMELL the difference between a Human Customer and a Spammy Robot?

  • SmashingMagazine - In Search Of The Perfect CAPTCHA

  • Sitepoint - Beyond CAPTCHA: No Bots Allowed!

At the end I went for a jquery/PHP approach which goes like this:

index.php

$(document).ready(function() {

    $.get("captcha-token.php", function(txt) {
        $("#email-form").append('<input type="hidden" id="input-ts" name="ts" value="' + txt + '" />');
    });

    $("a.send-email-form").live('click', function() {
        $.ajax({
            url: _site_root + "ajax-email.php",
            type: "POST", 
            dataType: "json", 
            data: {
                from:   $("#input-from").val(), 
                to:     $("#input-to").val(), 
                body:   $("#input-body").val(),
                ts: $("#input-ts").val()
            },
            success: function(data, textStatus, XMLHttpRequest) {
                if (data.status) {
                    msg.text("Send!").addClass("email-msg-success");                    
                } else {
                    msg.text(data.msg).addClass("email-msg-error"); 
                    // show error field开发者_运维问答s
                    for (x in data.errorFields) {
                        $("#input-" + data.errorFields[x]).addClass("error");
                    }
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                msg.text("Error!" + " (" + textStatus + ")").addClass("email-msg-error");
            },
            complete: function(XMLHttpRequest, textStatus) {}
        });

        return false;
    });
});

captcha-token.php

$ct = mktime();
setcookie('token', md5('secret salt' . $ct), 0, '/');
echo $ct;

ajax-email.php

$proceed = false;
$seconds = 60 * 10;

if ( isset($_POST['ts']) && isset($_COOKIE['token']) && $_COOKIE['token'] == md5('secret salt' . $_POST['ts']) ) $proceed = true;

if (!$proceed) {
    echo '{"status":false, "msg":"! ' . _("Error. Form processing halted for suspicious activity.") . '"}';
    exit;
}

if ( ((int)$_POST['ts'] + $seconds) < mktime() ) {
    echo '{"status":false, "msg":"! ' . _("Error. Too much time elapsed. Please try again.") . '"}';
    exit;
}

mail($_POST['to'], $_POST['body'], "From: $from");

Now I was wondering….. why a cookie? Why not use PHP's $_SESSION? Is there any reason for using a cookie vs session? I believe $_SESSION is more secure as it is more difficult to manipulate right?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜