Haren Sarma
Haren Sarma

Reputation: 2553

What is proper way to calling session_start()

I have two shared host. my problem is realated with calling session_start(). In my localhost and one of my shared host. session start works well with user notice that : cannot call header. then i used to write the below code:

<?php
if(! isset($_SESSION)){
 session_start()
}
?>

But in another host, it still echo message that "Notice: cannot start session()..." also my problem that session doesn't starts in first visit. When I refresh my browser window again then starts session. what is relation between client and server side. again what is wrong with my session_start() ? please help me.

May anyone tell me that what is the proper way to calling a session_start() which will never fail. and where should I call. very top of the page or anywhere in the configuration file. a little example will help me surely.

Upvotes: 3

Views: 2390

Answers (1)

Jon
Jon

Reputation: 437514

Two simple things:

1. Always call session_start unconditionally.

2. Always call session_start before you output anything on the page.

So you should do it like this:

<?php
session_start();

// and now anything else

In particular, be aware that you can violate directive #2 in many different ways, e.g. by:

  • Explicitly printing anything yourself with echo etc.
  • Having any characters at all in your PHP script before the <?php tag
  • Inlcuding other scripts that do the above

There are lots and lots of questions here on SO that describe point #2 and how to solve it.

Upvotes: 8

Related Questions