Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I have to declare session_start();?

Tags:

php

session

login

So Im a beginner when it comes to PHP so I need a little help. I am trying to figure out when to start the session. Should I do it when the user first registers or what about when they log in?

Also, are sessions 'universal' meaning when I check a session will it work or do I have to include a file to all pages that check if someone has a session?

like image 741
Matt Avatar asked Apr 14 '12 23:04

Matt


People also ask

Do I need session_start on every page?

It must be on every page you intend to use. The variables contained in the session—such as username and favorite color—are set with $_SESSION, a global variable. In this example, the session_start function is positioned after a non-printing comment but before any HTML.

When should you start a session using session_start ()?

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie. When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.

Where should I put session_start?

You want to put session_start(); at the top of your page before any other code. However, if you are using includes to make your life easier, it's best to put it at the very top of a file that is included in all files.

What is the use of session_start () and session_destroy () functions in PHP?

session_destroy() function: It destroys the whole session rather destroying the variables. When session_start() is called, PHP sets the session cookie in browser. We need to delete the cookies also to completely destroy the session. Example: This example is used to destroying the session.


2 Answers

"Should I do it when the user first registers or what about when they log in?"

You should do it every time you want to get or set any session information. Data stored in the $_SESSION array will only be available after the session is started.

"Also, are sessions 'universal' meaning when I check a session will it work or do I have to include a file to all pages that check if someone has a session?"

Calling session_start() is all you need to create a session. If a session was already created, that session will be used.

like image 121
Telmo Marques Avatar answered Oct 06 '22 02:10

Telmo Marques


just to session_start() once in every file you access the $_SESSION variable. best would be to do it in a central spot. for example a file which is included in every of your applications files.

like image 33
Andreas Linden Avatar answered Oct 06 '22 02:10

Andreas Linden