Php 7.1 session cookies


#1

Hi,
I have been struggling for the past few days trying to get php session cookies working. They work on my own local network and they work fine on namecheap (which I am considering leaving) but I have been fighting to get session cookies working on dreamhost.

Today I wrote this very simple code that just increments by one each time the browser is refreshed. Works like a champ on my local apache2 server, dreamhost refuses to increment.

<!doctype html>
<?php 
 if (session_status() === PHP_SESSION_NONE)
    session_start();
 if (! isset($_SESSION['X']) )
	$_SESSION['X'] = 0;
 $_SESSION['X'] += 1;
?>
<html>
 <body>
   <h2> X=<?php echo $_SESSION['X']; ?> </h2>
 </body>
</html>

the test site is here:
https://johnfrumm.faith/sessioncookietest.php

What could I be doing wrong?


#2

If you look at the site’s error.log, you will probably see an error like this:

PHP Warning:  session_start(): Cannot start session when headers already sent
           in /home/user/example.com/test.php on line 4

A session needs to be started before the script has sent any output, so you’ll need to move the doctype declaration below the PHP code. For example:

<?php 
 ...
?>
<!doctype html>
<html>
 <body>
   ...

Possibly your local development environment is setup to auto-start sessions, so you don’t see the above session start warning. Dreamhost’s default setup has session.auto_start disabled.


#3

yes, you are right, that error is rife throughout the log.
I moved the line as you suggested, however the error persists.

Could this also have something to do with the phprc file? I thought perhaps something needed to be set there, but I have no idea how, or even if I did how to restart apache2.


#4

unreal. I had a blank line above the "<?php " at the top. Once I deleted that (and made the correction that habilis suggested) it started working.

That was my entire afternoon…

thank you, habilis.


#5

hey @habilis
thanks for your solution . i was going through the same issue and your solution worked for me .
best regards!!