Quantcast
Viewing all articles
Browse latest Browse all 31

PHP Session Not Working $_SESSION being reset

My dumb ass was trouble shooting my PHP Session for at least an hour. The session was being reset everytime I would re-load the page or go to another page. I couldn’t store any session variables.

<!doctype html>
<?
session_start();

// Turn on all error reporting
error_reporting(0);

echo "session_id: " . session_id(); if (empty($_SESSION['count'])) {    $_SESSION['count'] = 1; } else {    $_SESSION['count']++; } echo "<br/>"; var_dump($_SESSION); ?> <p> Hello visitor, you have seen this page <?php echo $_SESSION['count']; ?> times. </p>

So, why wouldn’t the above code work? Because the <!doctype html> or any other content was ABOVE the session_start();

<!doctype html>

was at the top of my document. I wasn’t getting any error, “headers already sent” or whatever normally happens. As soon as I put the session_start(); at the beginning of my page it all worked properly!

I’ve seen similar things happen when you have a space at before your <?PHP init at the top of a page.

BAD:

 <?PHP

GOOD:

<?PHP

you probably can’t see it here, but there’s a ” ” / space at the beginning of the first document. Sometimes you might accidentally put a space in there.

 


Viewing all articles
Browse latest Browse all 31

Trending Articles