4kizuki/php-actg

Anti CSRF Token Generator for PHP


License
MIT

Documentation

php-actg

Anti CSRF Token Generator for PHP.

Installation

composer require 4kizuki/php-actg:@beta

Usage

Generate( )

final public static function Generate( ) : string;

Generate a new token.

  • Example
<?php
use Akizuki\ACTG\CSRFToken;
$token = CSRFToken::Generate( );

Verify( )

final public static function Verify( string $token, bool $nothrow = false ) : bool;

Verify the given token.

  • Example ( nothrow )
<?php
use Akizuki\ACTG\CSRFToken;

$given = $_POST['csrf_token'] ?? '';
if( !CSRFToken::Verify( $given, true ) ) {
    echo 'CSRF ATTACK!';
}
  • Example ( throw )
<?php
use Akizuki\ACTG\CSRFToken;

$given = $_POST['csrf_token'] ?? '';
if( !CSRFToken::Verify( $given, true ) ) {
    echo 'CSRF ATTACK!';
}

GenerateHiddenInput( )

final public static function GenerateHiddenInput( ) : string;

Generate a new token and returns HTML input tag.

<input type="hidden" name="AKIZUKI_ACTG_TOKEN" value="(token)" />

PostVerify( )

final public static function PostVerify( bool $nothrow = false ) : bool;

Verify the token posted.

  • Example
<?php
use Akizuki\ACTG\CSRFToken;

if( !CSRFToken::PostVerify( true ) ) {
    echo 'CSRF ATTACK!';
}

Customization

Customizable Values

  • Session Key
    Variable $_SESSION[(Session Key)] is used for this library. The default value is '4kizuki/php-actg': string.
  • Token Period
    Token's term of validity. The default value is 1800: int.
  • Session Auto Start
    Whether this libeary starts session automatically or not. The default value is false: bool.
  • HTML Input Name
    Used in GenerateHiddenInput( ) and PostVerify( ). The default value is 'AKIZUKI_ACTG_TOKEN': string.

How to customize?

  • Use Set*** Functions.
  • Set $_ENV[].
  • Create new class which extends CSRFToken and overwrite Default*** constants.