Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, is there any harm in running session_start() multiple times?

Tags:

php

session

Presumably there's some tiny performance hit, but beyond that?

like image 844
sprugman Avatar asked Apr 05 '10 18:04

sprugman


People also ask

What happens if I call session_start twice?

Calling session_start() a second time in a request doesn't do anything unless the existing session was destroyed (via session_destroy() ). 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.

Do I need to use 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 session_start () is called PHP will call the open and read session save handlers?

Description ¶When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers. These will either be a built-in save handler provided by default or by PHP extensions (such as SQLite or Memcached); or can be custom handler as defined by session_set_save_handler().

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

As of PHP 4.3.3, calling session_start() while the session has already been started will result in an E_NOTICE warning. The second call to session_start() will simply be ignored.You could check if the session has been started first or not with:

if (session_id() == "")   session_start(); 
like image 85
rkulla Avatar answered Sep 21 '22 12:09

rkulla


From the docs:

As of PHP 4.3.3, calling session_start() after the session was previously started will result in an error of level E_NOTICE. Also, the second session start will simply be ignored.

So no, it won't "cause harm", but it'll throw an error. And the fact that it's happening is probably an indicator that you're doing something incorrectly, and might need to re-think how your code is laid out.

like image 34
Chad Birch Avatar answered Sep 19 '22 12:09

Chad Birch