PHP How does PHP's session_start() function work?

  • Thread starter Thread starter Math Is Hard
  • Start date Start date
  • Tags Tags
    Php
Click For Summary
PHP's session_start() function is essential for managing sessions in web applications. It must be called on each page where session data is accessed. If a session already exists, session_start() will not create a new one; instead, it will load the existing session variables into the $_SESSION superglobal array. If session_start() is not called, a new session will be initiated each time the script runs, resulting in lost session data. This function is crucial for maintaining state across multiple page requests in PHP applications.
Math Is Hard
Staff Emeritus
Science Advisor
Gold Member
Messages
4,650
Reaction score
39
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.
 
Technology news on Phys.org
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:
 
Thanks, CompuChip! :smile:
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 21 ·
Replies
21
Views
6K
  • · Replies 13 ·
Replies
13
Views
2K
  • · Replies 7 ·
Replies
7
Views
7K
  • · Replies 4 ·
Replies
4
Views
6K
  • · Replies 7 ·
Replies
7
Views
5K
  • · Replies 2 ·
Replies
2
Views
5K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 6 ·
Replies
6
Views
6K
  • · Replies 15 ·
Replies
15
Views
3K
  • · Replies 22 ·
Replies
22
Views
2K