CSRF-prevention mechanism for a form I am using codeigniter framework in PHP. In signup form I have:

Controller:

$info['csrf_token'] = array('signup'=&gt;$this-&gt;csrf_token('signup'));
echo $this-&gt;load-&gt;view('/signup',$info,TRUE);

// generate token:
public function csrf_token($form_name){
    if (function_exists('mcrypt_create_iv')) {
        $t = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
    } else {
        $t = bin2hex(openssl_random_pseudo_bytes(32));
    }

    $sess_array = array();
    $sess_array[$form_name] = $t;
    $this-&gt;session-&gt;set_userdata('csrf', $sess_array);

    return $t;
}


View:

&lt;form&gt;
&lt;input type="hidden" name="csrf_token" value="&lt;?=hash_hmac('sha256', 'signup', $csrf_token['signup'])?&gt;" /&gt;
&lt;/form&gt;


Validation check on form submit:

$csrf_sess = $this-&gt;session-&gt;userdata('csrf');
if(hash_hmac('sha256', 'signup', $csrf_sess['signup'])==$_POST['csrf_token']){
    return true; // Valid request.
}else{
    return false;
}


Will it prevent website from CSRF (Cross-Site Request Forgery)?
From what it looks like, you are correctly checking the submission form for a valid CSRF token before processing, therefore a separate, malicious website [EDIT: without access to the hidden CSRF token on the submission form] would be unable to execute CSRF.

From here: Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious web site, email, blog, instant message, or program causes a user's web browser to perform an unwanted action on a trusted site for which the user is currently authenticated