Sometimes, we want to add a cross-site request forgery (CSRF) token using PHP.
In this article, we’ll look at how to add a cross-site request forgery (CSRF) token using PHP.
How to add a cross-site request forgery (CSRF) token using PHP?
To add a cross-site request forgery (CSRF) token using PHP, we can use the bin2hex
function.
For instance, we write
session_start();
if (empty($_SESSION["token"])) {
$_SESSION["token"] = bin2hex(random_bytes(32));
}
$token = $_SESSION["token"];
to call bin2hex
with a random byte string created with random_bytes(32)
to return a random token.
Then we set it as the value of $_SESSION["token"]
.
Conclusion
To add a cross-site request forgery (CSRF) token using PHP, we can use the bin2hex
function.