I wrote a script which generates an authentication token in order to prevent CSRF attacks.
It works well on local server but returns the 403
error on live server
Here is the code that checks if a token already exists or not
// Generate authentication token to prevent CRSF attacks // Check if a token is present for the current session if (!isset($_SESSION["auth_token"])) { // No token present, generate a new one $auth_token = bin2hex(random_bytes(35)); $_SESSION["auth_token"] = $auth_token; } else { // Reuse the token $auth_token = $_SESSION["auth_token"]; }
And here is the code that validates the token upon submission
if ($_SERVER["REQUEST_METHOD"] == "POST") { // Validate token to avoid CSRF attacks $token = trim($_POST['auth_token']); if (!isset($token) || !isset($_SESSION['auth_token']) || $token !== $auth_token) { // show an error message echo '<h1 class="error">Error: invalid form submission</h1><p>Your request was denied as this request could not be verified.</p>'; // return 403 http status code http_response_code(403); die(); exit(); } }
UPDATE
I checked in on my error_log.php and this was the error displayed
session_start(): Cannot start session when headers already sent in /home/refermec/public_html/user/login.php on line 15
I have the same code as stated earlier in all pages with a form that requires authentication
Advertisement
Answer
According to your error, you have content ABOVE session_start();
Once any content, no matter a HTML comment, an echo
, a header()
happens before session_start();
, php will throw that error.
All these things need to come AFTER the session_start();
…
Make sure session_start();
is at the top of the file, or at the top of an included file.