PHP and sessions question

  • #1
Math Is Hard
Staff Emeritus
Science Advisor
Gold Member
4,527
28

Main Question or Discussion Point

I'm a little confused about how PHP's session_start() function works.
There's a tutorial I am reading here: http://www.tizag.com/phpT/phpsessions.php

Here's an example they give of a counter script:

Code:
<?php
session_start();  
if(isset($_SESSION['views']))
    $_SESSION['views'] = $_SESSION['views']+ 1;
else
    $_SESSION['views'] = 1;

echo "views = ". $_SESSION['views']; 
?>
It seems like every time I call this PHP script from a new page, a new session will start, because the first line is:

session_start();

Does PHP ignore this function if a session exists?

Thanks.
 

Answers and Replies

  • #2
CompuChip
Science Advisor
Homework Helper
4,302
47
You have to call session_start() at each page. If no session is started yet, this will start a new session (i.e. write a cookie with the session ID). I believe that if you already have a session running, this will load the variables into $_SESSION so you can access them.

So basically, session_start() is needed if you want to stay in the same session, if you don't call it you will get a new session all the time (or your variables just won't get stored, which is effectively the same).

In short: I Don't know how it works exactly, just use it :smile:
 
  • #3
Math Is Hard
Staff Emeritus
Science Advisor
Gold Member
4,527
28
Thanks, CompuChip! :smile:
 

Related Threads on PHP and sessions question

  • Last Post
Replies
8
Views
6K
  • Last Post
Replies
6
Views
3K
  • Last Post
Replies
8
Views
4K
  • Last Post
Replies
13
Views
832
  • Last Post
Replies
4
Views
639
  • Last Post
Replies
15
Views
4K
  • Last Post
Replies
3
Views
982
  • Last Post
Replies
6
Views
3K
Replies
4
Views
707
Top