I'm trying to introduce a token to prevent CSRF in the login form since I reviewed some post here where it was said it's recommended. The way I send the token inside the logged area is through headers. (I've to do it on that way).
the login form is "as always":
login.php
<?php
session_start();
$_SESSION['csrf_token'] = 'the_token_string';
header('X-CSRF-Token: '.$_SESSION['csrf_token']);//I'm not sure if is really neccessary to set this header here).
?>
<html>
<form method="post" action="flogin.php">
<input type="text" name="user"/>
<input type="password" name="pass"/>
<input type="hidden" name="token" value="<?php echo $_SESSION['csrf_token'] ?>"/>
<input type="submit"/>
</form>
</html>
In the file the data is received, I check everything is fine about user name, password and token. In case the user logs succesfully, I just redirect him/her to the main page. Let's call main.php
flogin.php
//irrelevant code. Everything is fine.
$_SESSION['logged'] = true;
header('Location: main.php');
exit;
Now, in main.php the first thing I've to do (it's a must) is check if user is really logged and also check the token.
main.php
<?php
session_start();
if(!isset($_SESSION['logged'] || !$_SESSION['logged'])){
header('Location: logout.php');
exit;
}
$headers = apache_request_headers();
if(!isset($_SESSION['csrf_token']) || !isset($headers['X-CSRF-Token']) || $headers['X-CSRF-Token']!=$_SESSION['csrf_token']){
header('Location: logout.php');
exit;
}
...
?>
And here is where I'm having the problem. Since the header ('Location: main.php') in the flogin.php file is before any output and it directly redirects to main.php, and the first thing I've to do there among other things is to check about the header with the token I always get the problem the header is not already set.
I don't know how to send that header with the token value to main.php. I'm very stuck with this problem and I even don't know if this is the right way.
I googled about this but everything I found was about curl and I don't use curl at all (unless this becomes a must).
(I apologize about the code errors, if there's. I'm wrote it at raw).
Thank you so much for your time.