session_start

(PHP 4, PHP 5)

session_start -- Initialize session data

Description

bool session_start ( void )

session_start() creates a session or resumes the current one based on the current session id that's being passed via a request, such as GET, POST, or a cookie.

This function always returns TRUE.

注: If you are using cookie-based sessions, you must call session_start() before anything is outputted to the browser.

例子 1. A session example: page1.php

<?php
// page1.php

session_start();

echo
'Welcome to page #1';

$_SESSION['favcolor'] = 'green';
$_SESSION['animal']   = 'cat';
$_SESSION['time']     = time();

// Works if session cookie was accepted
echo '<br /><a href="page2.php">page 2</a>';

// Or maybe pass along the session id, if needed
echo '<br /><a href="page2.php?' . SID . '">page 2</a>';
?>

After viewing page1.php, the second page page2.php will magically contain the session data. Read the session reference for information on propagating session ids as it, for example, explains what the constant SID is all about.

例子 2. A session example: page2.php

<?php
// page2.php

session_start();

echo
'Welcome to page #2<br />';

echo
$_SESSION['favcolor']; // green
echo $_SESSION['animal'];   // cat
echo date('Y m d H:i:s', $_SESSION['time']);

// You may want to use SID here, like we did in page1.php
echo '<br /><a href="page1.php">page 1</a>';
?>

If you want to use a named session, you must call session_name() before calling session_start().

session_start() will register internal output handler for URL rewriting when trans-sid is enabled. If a user uses ob_gzhandler or like with ob_start(), the order of output handler is important for proper output. For example, user must register ob_gzhandler before session start.

注: Use of zlib.output_compression is recommended rather than ob_gzhandler()

注: As of PHP 4.3.3, calling session_start() while the session has already been started will result in an error of level E_NOTICE. Also, the second session start will simply be ignored.

See also $_SESSION, session.auto_start, and session_id().


add a note add a note User Contributed Notes
info at methodus dot de
19-May-2006 02:42
To avoid the notice commited by PHP since 4.3.3 when you start a session twice use this function:

<?php
function start_session(){
   static
$started=false;
   if(!
$started){
      
session_start();
      
$started = true;
   }
}
?>

This should help you when your error reporting is set to E_ALL
admin at haravikk dot com
10-May-2006 09:00
Just a note for any of you who have the same trouble as I did. $_SESSION appears to break horribly if you attempt to assign information into integer keys.

For example, a result from a MySQL query may look like:

<?php
array(
  
0 => 'haravikk',
  
'username' => 'haravikk',
  
1 => 'fish',
  
'password' => 'fish'
  
);
?>

Attempting to assign that to $_SESSION either as a straight array, or by placing all keys (for example using a foreach) will FAIL and the data will be unavailable when you move to another page. My solution was to do this:

<?php
function storeSessionArray($array) {
   foreach(
$array as $k => $v)
       if (
is_string($k)) $_SESSION[$k] = $v;
}
?>

This worked correctly =)
phpguru at orangethink dot com
19-Mar-2006 03:57
"SESSION FUNCTION IS DOMAIN SPECIFIC.

So, to savage the situation. be domain specific."

Umm. No, it isn't. It is however only domain specific when the domains are hosted on the same server.
You can still share session data between domain2.com and domain3.com just with that caveat.
crs at vankuik dot nl
01-Feb-2006 05:56
As the previous note said, the session_start() function needs a directory to write to.

You can get Apache plus PHP running in a normal user account. Apache will then of course have to listen to an other port than 80 (for instance, 8080).

Be sure to do the following things:
- create a temporary directory PREFIX/tmp
- put php.ini in PREFIX/lib
- edit php.ini and set session.save_path to the directory you just created

Otherwise, your scripts will seem to 'hang' on session_start().
james at skinsupport dot com
23-Dec-2005 10:17
One thing of note that caused me three days of trouble:

It's important to note that Firefox (for one) makes two calls to the server automatically.  One for the page, and one for favicon.ico.

If you are setting session variables (as I was) to certain values when a page exists, and other values when pages don't exist, the values for non-existent pages will overwrite the values for existing pages if favicon.ico doesn't exist.

I doubt many of you are doing this, but if you are, this is a consideration you need to address or you'll be bald over the course of a three day period!
zackbloom at gmail dot com
04-Dec-2005 03:16
Yes php does not automatically insert the SID in header redirects.  You must use something like:
'<address>?SID='.SID
to manually insert the SID.
jeremygiberson at gmail dot com
18-Oct-2005 02:13
foltscane at yahoo dot com wrote about people losing session information on page redirects.

The problem is some times the redirect may kick you off to the next page before all the session variables have been saved. The true solution to lost session vars on redirect is to simply call session_write_close(); before setting the redirect header. This will insure that php finishes writing the session info before page redirect gets underway.

ie:
<?
   session_start
();
  
$_SESSION['forward'] = "This session data will not be lost!";

  
session_write_close();
  
header('Location: nextpage.php');
?>
erm[at]the[dash]erm[dot]com
28-May-2005 04:04
If you are insane like me, and want to start a session from the cli so other scripts can access the same information.

I don't know how reliable this is.  The most obvious use I can see is setting pids.

// temp.php

#!/usr/bin/php -q
<?php

session_id
("temp");
session_start();

if (
$_SESSION) {
  
print_r ($_SESSION);
}

$_SESSION['test'] = "this is a test if sessions are usable inside scripts";

?>

// Temp 2

#!/usr/bin/php -q
<?php

session_id
("temp");
session_start();

  
print_r ($_SESSION);

?>
corey at eyewantmedia dot com
20-May-2005 10:19
Here is a crazy feature -- you get one concurrent database connection per session, transparent to the programmer!

I am running php 5.0.4 on iis 6 (yeah, I know...). I noticed under stress testing that database connections were my bottleneck. I spent like 5 hours turning this on, that off, etc because I could not get php to create more than one database connection at a time, regardless of how many requests it was servicing. I tried running php as fastcgi, cgi, and isapi module. I tried using mysql and mysqli extensions. Same thing every time. Then I happened to turn off auto-start sessions and commented out my session_start() calls, and all of the sudden I get multiple connections like I expected!

Don't let this happen to you -- don't freak out! Apparently something somewhere tries to make sure your visitors don't get more than their share of your resources, so they get one db connection per session. I can't say it is what I would like to happen, but now that I know, it doesn't bother me much :) Hope this saves someone some time and headache!
Jose Cavieres
13-Apr-2005 01:11
For the problem of session lost after of redirect with header location...

Try with this:
<?
session_start
();
$_SESSION['mySession'] = "hello";

header ("Location: xpage.php");
exit();
//This sentence do the magic
?>
jorrizza at gmail dot com
02-Apr-2005 09:33
If you open a popup window (please no commercial ones!) with javascript window.open it might happen IE blocks the session cookie.
A simple fix for that is opening the new window with the session ID in a GET value. Note I don't use SID for this, because it will not allways be available.

----page.php----
//you must have a session active here
window.open('popup.php?sid=<?php echo session_id(); ?>', '700x500', 'toolbar=no, status=no, scrollbars=yes, location=no, menubar=no, directories=no, width=700, height=500');

----popup.php----
<?php
session_id
(strip_tags($_GET['sid']));
session_start();
//and go on with your session vars
?>
hbertini at sapo dot pt
14-Mar-2005 04:29
workaround when using session variables in a .php file referred by a frame (.html, or other file type) at a different server than the one serving the .php:

Under these conditions IE6 or later silently refuses the session cookie that is attempted to create (either implicitly or explicitly by invoquing session_start()).

As a consequence, your session variable will return an empty value.

According to MS kb, the workaround is to add a header that says your remote .php page will not abuse from the fact that permission has been granted.

Place this header on the .php file that will create/update the session variables you want:

<?php header('P3P: CP="CAO PSA OUR"'); ?>

Regards,
Hugo
raphael at cynage dot com
23-Feb-2005 12:35
Quick point, since this had been going round in circles for days...

IE will not accept sessions from a domain that has an non alpha-numeric character in it. My development site was running under the vhost mos_dev and it was killing me, trying to work out why IE kept dropping my sessions.
lukasl at ackleymedia dot REMOVESPAM dot com
18-Dec-2004 02:18
About the Session not getting saved on a header("Location:") redirect.

Make sure to call session_write_close() before doing the redirect.  This will make sure that the session values get written to the disk.
m dot kuiphuis at hccnet dot nl
24-Jun-2003 06:37
[Editors Note: For more information about this
http://www.zvon.org/tmRFC/RFC882/Output/chapter5.html ]
 
I use name-based virtual hosting on Linux with Apache and PHP 4.3.2.
Every time when I refreshed (by pressing F5 in Internet Explorer) I noticed that I got a new session_id. Simultaneously browsing the same site with Netscape didn't give me that problem. First I thought this was some PHP issue (before I tested it with Netscape), but after searching a lot on the internet I found the problem.
Since I was using name based virtual hosting for my testserver and we have different webshops for different customers I used the syntax webshop_customername.servername.nl as the domain-name.
The _ in the domain name seemed to be the problem. Internet Explorer just denies setting the cookie on the client when there is a special character (like an _ ) in the domain name. For more information regarding this issue: http://support.microsoft.com/default.aspx?scid=kb;EN-US;316112
Stupidly enough, this information was related to asp (yuk :o)
gadgetguy03 at lycos dot com
21-Jun-2003 10:18
SESSION LOST ON HEADER REDIRECT (CGI on IIS 5.0)

I realize there are numerous scattered posts on this issue, but I would like to add my 2 since it took me a whole day and a download of the LiveHTTPHeaders Mozilla plugin to figure it out.

On the **CGI** version of PHP on IIS 5.0/Windows 2000, the following code will not work as expected:

/***** sess1.php *****/
session_start();
$_SESSION["key1"] = "testvalue";
header("Location: sess2.php");

/***** sess2.php *****/
session_start();
echo "key1 = '".$_SESSION["key1"]."'";

PROBLEM:
All session data is lost after a header redirect from the first page on which the session is initialized. The problem is, the PHPSESSID cookie is not being sent to the browser (ANY browser, IE or Mozilla) on the initial session page with the header("Location: ...") redirect. This is unrelated to client cookie settings - the set-cookie: header just isn't sent.

SOLUTION:
I was able to remedy the problem by switching to the ISAPI DLL version. This seems to be an MS/IIS bug, NOT a PHP bug - go figure. I hope this saves you some headaches especially with your user authentication scripts!!

The closest matching "bug" report I found:
http://bugs.php.net/bug.php?id=14636
benja at benja dot be
16-Apr-2003 02:45
Just for info, session_start() blocks if another PHP using the same session is still running in background. It seems it's waiting the other PHP to finish... and sometimes it can be a problem. Create 2 different sessions by setting 2 different names : session_name() solve the problem.

Benja.
mickey at UNSPAMwebsoft dot com
20-Mar-2002 09:00
A note on Windows installations with an NTFS file structure:

Make sure you give your Internet user account (usually IUSR_MACHINENAME) "Modify" access to the session.save_path directory.  Otherwise session_start() will silently - and oh, so slowly - fail.

("Modify" is a Win2k term, but the concept translates to older IIS installs).