Htaccess redirection does not keep session

Hello,

I am trying to use custom error pages with a htaccess file.
I am using ErrorDocument 404 /404.php.
This page will check whether the user is logged in. It only displays when he/she is, otherwise it asks the user to log in.
But session variables are not available after an ErrorDocument redirection, so the page always thinks the user is not authenticated.
Here is the code:
session_start();

if(isset($_SESSION['user'])){
	
	echo "not found";
	
}else{
	
	header('Location: login.php');
	
}

Variable $_SESSION[‘user’] is never set after the redirection, but it is if we manually access the page.

Add this to your .htaccess

php_flag output_buffering on 

I added php_flag output_buffering on but nothing changed.

Is login.php correctly setting the session?

Yes:

  • I log in, I am taken to the home page for the members (it sees the session variables, and normally shows)
    (Redirection is done with header('Location: ...');)

  • I type an URL to a not-existing page, the 404.php shows but it does not see the session variables, and shows the error page for the not-authenticated visitors

  • I edit the URL again (manually) and put back an address to a valid page. The pages says I’m still logged in (session variables are here again).

UPDATE:
I solved my problem.

I was looking for a way to keep POST data when redirecting after a 404 error, and I found this:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /404.php [L]

I replaced the line ErrorDocument 404 /404.php with the above, and in addition to keep $_POST data, it gives access to the $_SESSION variables.

However, I do not know whether this solution may be used with errors other than 404 Not Found.

1 Like