As you probably already know, session_start is an in-built PHP function that will start a new session.
The problem is:
- If you call it more than once, your script will throw an E_NOTICE error.
- Although the solution seems pretty straight forward (don’t call it more than once), in certain scenarios, you won’t be entirely sure if a session has already been started or not.
- In some cases, it might be out of your control.
- There are two ways to approach this.
If you are using a PHP version that is lower than 5.4.0, you can do the following:
- If you run the code above, you’ll see that a session is always started. This is because:
- We check to see if the function session_id returns an empty string.
- If session_id returns an empty string, we can conclude that the session has not been started yet.
- If this is the case, we can start the session by calling the function session_start.
- In PHP version 5.4.0 and above, we can make use of the function session_status, which returns the status of the current session.
- This function can return three different integer values, all of which are available as predefined constants.
These are:
[ad type=”banner”]
As you can see, using this function makes your code a little more self-explanatory!
Note that you can also check to see if the $_SESSION array has been set. However, it is worth noting that $_SESSION can be manually initialized like so:
i.e. The $_SESSION array might exist, even if a session hasn’t already been started.
Prior to PHP 5.4 there is no reliable way of knowing other than setting a global flag.
Consider:
[ad type=”banner”]
Sample code:
Good
Nice
good
very good keep it up