Preventing CSRF attacks using PHP

I have code to prevent CSRF attacks like:

    if(!isset($_SESSION['mykey']) || $_SESSION['mykey'] !== $_POST['mykey'])
        throw new RuntimeException('CSRF attack');

When tested $_SESSION[‘mykey’] == $_POST[‘mykey’]) it should execute throw new RuntimeException(‘CSRF attack’);

How to enable error message in this case as it is transferred to confirmation page when I test == which should be !==

Say what? You mean how to handle the exceptions thrown or?

Is there any real example to implement the same step and working example?

I have replaced !== with ==
It is redirected to the confirmation page but it should execute line:throw new RuntimeException(‘CSRF attack’);

I’m not sure anymore if this is actually working script.

So what you are saying there is

  1. IF $_SESSION[‘mykey’] IS NOT SET throw exception
    OR
  2. IF $_SESSION[‘mykey’] is different from $_POST[‘mykey’] throw exception

Probably these conditions does not happen if it does not throw the exception. Try print_r() or var_dumping your variables to see what values they have. You can also var_dump conditions e.g var_dump($_SESSION[‘mykey’] !== $_POST[‘mykey’]);

I will test variable values. How to redirect or post message nice bootstrap message as CSRF attack. There is only

 throw new RuntimeException('CSRF attack');

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.