If the victim has not viewed any forms on your site, he will not yet have a token stored in his session.
If the attacker presents the victim with a form with no token field at all, the POST request made by the victim will pass the CSRF check because $_POST['token']
and $_SESSION['token']
will both be null. (Or both empty strings depending on how PHP initialises unknown variables.)
You must also check that the token exists in the session before checking for equality and abort if either of those tests fail.
Depending on your site, a user not having seen a form may be very likely or it may be an extreme edge case. With checking for the existence of the token first, it doesn't matter how many forms you have on your website, there is no possibility of a CSRF attack.
Apart from that small problem, I can't see any CSRF vulnerability in it. That code looks like it will do the job.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…