/    Sign up×
Community /Pin to ProfileBookmark

$_SESSION empty after going to other php page

Hi, I am confused about how sessions work in PHP. Here is what I am confused about exactly:
I have a login page and then a dashboard page.
At the start of every page I do:
`session_start()`
Also, my code works like this:
After the username and password were entered they get verified and if correct I do:
`
$_SESSION[‘username’] = $username;
?>
<script type=”text/javascript”>
window.location = ‘../../../dashboard.php’
</script>
<?php
`

The problem I am facing is that at the dashboard.php page right after I do `session_start()` I then do `print_r($_SESSION)` and it is empty.

I tried refreshing the page cash and it didn’t help. Also, I tried putting `print_r($_SESSION)` right before the page login.php was closed and dashboard.php opened, and the $_SESSION was correct!

What am I doing wrong? Why does the $_SESSION get errase after swapping the pages?

Thank you!

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@NogDogJul 25.2021 — If you're going to do a location re-direct, in my experience that can short-circuit the session processes. Therefore you might want to try adding a call to session_write_close(); just before you output that JavaScript.
Copy linkTweet thisAlerts:
@weareandreiauthorJul 25.2021 — @NogDog#1634694

Thanks for help!

But actually it appears that it was simpler than that. I didn't quite understand how the sessions work in PHP.

Also, I didn't find any answer on the internet, I only understood my mistake by try and error method. So all the new php-programmers listen up!

session_start() function must be executed every time you are accessing the php script that uses $_SESSION variable. So I had a separate script session.php which checked for $_SESSION['username'] variable. And It always showed NULL because I should have put session_start() in the beginning of the php script!

Hope this helps to anyone like me.
×

Success!

Help @weareandrei spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.24,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...