session_start(); $token = bin2hex(random_bytes(32)); $_SESSION['token'] = $token; // In HTML form
if(isset($_POST['submit'])){ if($_POST['token'] == $_SESSION['token']){ // Form data validation and processing // ... // Destroy token after submission unset($_SESSION['token']); }else{ // Token verification failed echo "Token verification failed"; } }In the above example, we use the PHP session to store the generated token and retrieve it later when a form is submitted. We compare the submitted token with the stored token to ensure they match. The get_token function is not a PHP built-in function, but it can be found in various PHP security libraries such as 'phpseclib'. This library provides functions for secure encryption, random number generation, and token generation. It is recommended to use these libraries to ensure secure and efficient code.