|
|
 |
session_start (PHP 4, PHP 5) session_start -- Initialize session data Descriptionbool 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.
Note:
If you are using cookie-based sessions, you must call
session_start() before anything is outputted to the
browser.
Example 1. A session example: page1.php |
<?php
session_start();
echo 'Welcome to page #1';
$_SESSION['favcolor'] = 'green';
$_SESSION['animal'] = 'cat';
$_SESSION['time'] = time();
echo '<br /><a href="page2.php">page 2</a>';
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.
Example 2. A session example: page2.php |
<?php
session_start();
echo 'Welcome to page #2<br />';
echo $_SESSION['favcolor']; echo $_SESSION['animal']; echo date('Y m d H:i:s', $_SESSION['time']);
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.
Note:
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().
User Contributed Notes
session_start
frank_hayward at hotmail dot com
03-May-2005 02:13
I found that this only worked for me if I put session_start() at the very top of the page before the html and header tags.
<?php
session_start();
?>
<html>
<head>
Jose Cavieres
12-Apr-2005 12: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(); ?>
susko at seznam dot cz
11-Apr-2005 06:58
One more note related to loosing sessions after header() redirects: I had problem with script, that after writing data to database redirected the user to a different page. I was loosing sessions after every redirect, and only solution I found was to pass session info in header URL itself:
<? header("Location: $my_domain/different_page.php?".Session_Name()."=".Session_ID()); ?>
I might not be safe (see sessions hijack), but it worked for me. Hope it will work for you, too.
christian dot froemmel at charite dot de
04-Apr-2005 10:15
If you're developing websites using the (OS-feature) of search-domains [1] it is likely, that the browser silently discards the php-cookie-request when doing session_start() and creates a new session everytime you reload.
[1] Ie. you have the search-domain "senpftopf.de" and you're pointing with your browser to "http://www/session.php" (where the OS does the completion on its own) instead of the full name "http://www.senpftopf.de/session.php".
I assume because the browser cannot determine for which domain the cookie is for and ignores the request. So you should use the full qualified hostname + domain.
jorrizza at gmail dot com
02-Apr-2005 07: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();
?>
hbertini at sapo dot pt
13-Mar-2005 02: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
msn : kiur / at / wannabe / dot / ee
10-Mar-2005 07:30
You see, that session_id creator
creates the id from md5-hashed $REMOTE_ADDR and some random numbers.
It is useful because you can check the hashed remote_addr using substr() function.
So there will be less possibilities to hijack the session using the id.
kiur / at / wannabe / dot / ee
09-Mar-2005 04:36
This is useful if you dont like 32digit session_id's.
This will create longer session_id and it will be passed well.
index.php:
<?php
$rand1=rand(100000,900000);
$rand2=rand(100000,900000);
$session_id=$rand1.md5($REMOTE_ADDR)."S3cur3d".$rand2;
session_id($session_id);
session_start();
echo "
Better PHPSESSID created!
<meta http-equiv=refresh content='0;url=index2.php'>
";
?>
index2.php:
<?php session_start(); ?>
istesin at gmail dot com
01-Mar-2005 10:28
I also noticed that adding session variables before redirect will lead to lose new ones.
My solution was to make every new variable go through session_register .
This function helped me to fix this problem
P.S. This was tested on LAMP.
raphael at cynage dot com
22-Feb-2005 10: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.
php staerk de
20-Feb-2005 06:53
As session_start is part of a php module that may be installed or not, you may want to check before calling it with function_exists('session_start').
have fun, Thorsten.
owen at jollywebs dot com
18-Feb-2005 12:45
Other users have mentioned rogue spaces at the beginning of includes tripping up headers, but you should also beware of spaces at the END of an included file.
To illustrate - I keep mySQL username and password details in a single file called my.php which I include wherever it's required. It was working fine in most pages but causing a 'headers already sent' error whenever
header("Location: blah.php");
was called.
The solution was to remove invisible spaces from the end of the included my.php file - ie AFTER the ?>
José Enrique Serrano Expósito
13-Feb-2005 01:38
Based in another note, I make this exercise...
<?php
if( !isSet( $_GET['FirstLoad'] ) ) {
session_start();
$s = 'location: '.$_SERVER['REQUEST_URI'].'?FirstLoad=NO&PreviousSessionId='. session_id();
header( $s ); } else {
session_start();
echo 'session_start();<br>';
echo '$_SESSION is set from now on with ', count( $_SESSION ), ' items.<br>';
session_regenerate_id(); echo 'session_regenerate_id(); // Must execute it after session_start()<br>';
echo '$_GET[\'PreviousSessionId\'] and session_id() .-<br>';
echo $_GET['PreviousSessionId'].'<br>'. session_id().'<br>';
}
?>
davidhw at email dot it
16-Jan-2005 03:39
If you're using $_COOKIE and $_SESSION to pass values from one page to another, do not use the same keys !
For example:
<page1.php>
<?
session_start();
$_COOKIE['key1']="foo";
$_SESSION['key1']="bar";
print($_COOKIE['key1']); print($_SESSION['key1']); ?>
<page2.php>
<?
session_start();
print($_COOKIE['key1']); print($_SESSION['key1']); ?>
It took me hour to understand
ryanch at gmail dot com
15-Jan-2005 03:40
If your sessions based cookies are not being set, make sure you do not have any output before you call session_start().
For example:
If you had this:
<?
echo "hi";
session_start();
?>
php would not send the cookie, and thereby your session would not be saved via the cookie.
A even more sneaky gothcha is if you have a single white space at the beginging of your file, before your opening "<?".
lukasl at ackleymedia dot REMOVESPAM dot com
17-Dec-2004 12: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.
laacz at laacz dot lv
28-Oct-2004 09:37
If You are not using cookies to store session_id's, that does not mean, that session_start() will not send any headers at all. It still sends cache controlling information to user. For example:
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Even, if You set cache_limiter to none (via ini_set('session.use_cookies', 0) or ini_set('session.cache_limiter', 'none')), session_start() still tries to send empty headers and that causes error message "Cannot send session cache limiter - headers already sent". So, use output buffering, if You need to output something before session_start(). session_start
Kevin
27-Oct-2004 12:31
If you're having a problem with a file download script not working with IE if you call session_start() before sending the file, then try adding a session_cache_limiter() call before session_start().
I use session_cache_limiter('none'), but 'public' and 'private' seem to fix the problem too; use whichever suits your application.
tech at insights dot net dot au
17-Oct-2004 01:28
I am sure anybody that is trying to use IIS and PHP is throughly annoyed with the session_start() bug that recreates a new session every time it is accessed.
The problem is the session_id isn't passed before the session_start() so it creates a new session. So a simple sollution is:
$id = 473483478383834;
session_id($id);
session_start();
Another way that is a bit more dynamic using a Cookie to hold the session_id:
if (isset($SessID)){ session_id($SessID); }
session_start();
header("Cache-control: private"); // IE 6 Fix.
setcookie("SessID", session_id(), time() + 3600);
There are probably much better ways of doing this but for use with my offline Win/IIS setup it seems to be fine.
tornbydesign at hotmail dot com
11-Oct-2004 08:21
The following behavior is given if the client uses the IE, the WinXP Service Pack 2 (plain) and the Server uses the "session_start()" function:
If history.back() (Javascript) or the Back-Button is used and the previous site is a destination of a POST Data Form, IE will send a error message "Page cannot be found - Server or DNS unavailable".
Insert this header in your php script after the session starts to avoid the issue:
header("Cache-control: private");
Tornby
flheide at hotmail dot com
12-Jul-2004 09:18
use of a session fails the readfile function. you can save the file, but it will not open - if you insert this line where you specify your headers prior to the readfile, it works!
header("Cache-control: private");
charlie at linuxdsl dot co dot uk
20-May-2004 02:59
The following code is a nice simple way to check for cookie support without needing any intermediary pages to check it has been set.
// Set the name of the cookie (nicer than default name)
session_name("SID");
// Set cookie to expire way into the future so it persists
session_set_cookie_params (60*60*24*365*10, '/', '.mydomain.com',0);
session_start();
if ( SID != "" ) {
header("Location: /nocookie.php");
exit();
}
If you would also like to check for a certain value (e.g. to see if they are logged in) you could use this code instead:
session_name("SID");
session_set_cookie_params (60*60*24*365*10, '/', '.mydomain.com',0);
session_start();
if ( SID != "" ) {
header("Location: /nocookie.php");
exit();
} else {
if (!(isset($_SESSION['uid']))) {
header("Location: /expired.php");
exit();
}
}
mzajonc at pomona dot edu
09-May-2004 02:27
The way PHP5 creates session ids has changed. No longer are session ids always 32 characters. Rather it depends on how session.hash_function and and session.hash_bits_per_character are set in php.ini. The default now gives 27 characters. To go back to 32 change the function to 1 and and bits to 5 or function 0 and bits to 4.
This problem is particularily relevant for people using custom session handlers. For example, it affects phpSecureSessions.
ma at technoprint dot ch
25-Jun-2003 07:17
I solved the Problem that the session cookie isn't set in IIS5/CGI after redirect with a client side redirect. Not very clean but it works. Like this:
<?
session_start();
$_SESSION["foo"] = "bar";
redirectJS( "proceed.php" );
function redirectJS( $uri ){?>
<script type="text/javascript">
<!--
document.location.href="<?php echo $uri ?>";
-->
</script><?
die();
}
?>
m dot kuiphuis at hccnet dot nl
24-Jun-2003 05: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
20-Jun-2003 09: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
15-Apr-2003 01: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.
jeroen at unfix dot org
14-Mar-2003 02:24
Ofcourse one can call the session functions from an object
and even stuff a class into the session, it just needs some tricks ;)
Example:
class Site()
{
var $db_open;
var $error;
function Site()
{
$this->db_open = false;
$this->error = "No errors";
}
function IsOpen()
{
return $this->db_open;
}
function OpenDB()
{
$this->error = "Not implemented";
}
}
function fireup()
{
global $site;
session_start();
if (isset($_SESSION["site"])) $site = &$_SESSION["site"];
else
{
$_SESSION["site"] = new Site();
$site = &$_SESSION["site"];
}
if (!$site->IsOpen() &&
!$site->OpenDB())
{
echo $site->error;
}
}
Now call the fireup() function from your main page et tada
$site is your globally retained class in which you can stuff interresting things like database connections. Do remember to
declare them with 'var' in your class base like above.
ming
25-Feb-2003 10:32
if you are dealing with forms and session_start() you might experience that all form-values will automatically be emptied after returning to the form with the browser's back-button or javascript's history.back().
this is especially annoying if you want to enable your users to use the browser's back button to apply corrections to the inputted data on the previous page.
add this line right after calling session_start() to solve the problem:
header("Cache-control: private");
now, users can hit the back-button to access the form containing all the information they've inputted before.
e8boman at etek dot chalmers dot se
27-Jul-2002 01:28
mickey at UNSPAMwebsoft dot com
19-Mar-2002 07: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).
| |