What would happen if i use session_start() twice ?

A few minutes back I was trying to create a function in which I was supposed to store a value in a session variable. It then occurred to me that in some of the other files I must have already created a session by using a session_start(). Now after doing few tests, i am documenting my work so that others might find it helpful.

I created a function in a file named functions.php.

function testSession()
{
session_start();
session_start();
}

testSession();

When I ran this function PHP would return me the following output:

Notice: A session had already been started - ignoring session_start() in /home/freefeas/Functions.php on line 35

I can see this error as my error reporting in on. If you have disabled yours you might not see anything as PHP would by default use the session that is already open.

In order to make sure that only one session is open at a time you can use the following code:

function testSession()
{
	//Already a session exists
        session_start();
	
       //here we check to see if a session is already set or not
       if(!isset($_SESSION))
	{
                //if the session is not set then we create a new session else we directly store in the old session
		session_start();
	}
}

Here i have made sure that the code is commented for you to understand. What is happening?  I am checking to see if a session is set or not. If the session is not set, then and then only a new session is initiated.

I hope this article is of some use to you. Keep coding!!

 

Add a Comment

Your email address will not be published. Required fields are marked *