|
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net
[Spis]
[A]
[B]
[C]
[D]
[E]
[F]
[G]
[H]
[I]
[J]
[K]
[L]
[M]
[N]
[O]
[P]
[Q]
[R]
[S]
[T]
[U]
[V]
[X]
[W]
[Z]
session_start (PHP 4, PHP 5) session_start -- Inicjalizuj dane sesji Opisbool session_start ( void )
session_start() tworzy sesję lub wznawia bieżącą na
podstawie aktualnego identyfikatora sesji przekazanego przy wywołaniu,
poprzez metodę GET, POST lub ciasteczko.
Jeśli chcesz, aby sesja była nazwana, przed wywołaniem
session_start() musisz wywołać
session_name().
Ta funkcja zawsze zwraca wartość TRUE.
Notatka:
Jeśli używasz sesji opartych o ciasteczka, to
session_start() musi być wywołane przed wysłaniem
jakichkolwiek danych do przeglądarki.
Przykład 1. Przykład sesji: page1.php |
<?php
session_start();
echo 'Witaj na stronie #1';
$_SESSION['kolor'] = 'zielony';
$_SESSION['zwierze'] = 'kot';
$_SESSION['czas'] = time();
echo '<br /><a href="page2.php">strona 2</a>';
echo '<br /><a href="page2.php?' . SID . '">strona 2</a>';
?>
|
|
Po odwiedzeniu strony page1.php, druga strona,
page2.php będzie magicznie zawierała dane sesji. W
rozdziale Sesje znajduje się więcej
informacji na temat propagowania
identyfikatora sesji, gdzie można znaleźć na przykład
wytłumaczenie co zawiera stała SID.
Przykład 2. Przykład sesji: page2.php |
<?php
session_start();
echo 'Witaj na stronie #2<br />';
echo $_SESSION['kolor']; echo $_SESSION['zwierze']; echo date('Y m d H:i:s', $_SESSION['time']);
echo '<br /><a href="page1.php">page 1</a>';
?>
|
|
W celu stworzenia nazwanej sesji, niezbędne jest wywołanie funkcji
session_name() przed wywołaniem
session_start().
session_start() zarejestruje wewnętrzny uchwyt obsługi
wyjścia dla przepisywania URLi jeśli włączona jest opcja
trans-sid. Jeśli użytkownik używa
ob_gzhandler lub podobne z
ob_start(), kolejność uchwytów obsługi wyjścia jest
ważna dla prawidłowego wyjścia. Na przykład, użytkownik musi
zarejestrować ob_gzhandler przed rozpoczęciem sesji.
Notatka:
Od PHP 4.3.3, wywołanie session_start() podczas gdy
sesja już została rozpoczęta, spowoduje błąd poziomu
E_NOTICE. Drugie rozpoczęcie sesji zostanie
zignorowane.
Patrz także:
$_SESSION,
session.auto_start i
session_id().
User Contributed Notescrs at vankuik dot nl
01-Feb-2006 10: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().
moabie at NOSPAM dot o2 dot pl
26-Jan-2006 10:35
I confirm having same problems about strange variables behaviour when session variables have same names as non-session ones.
Thanks to author of previous note, because I got furious about that.. I didn't know what was wrong..
strange thing, cause the problem was despite those two same-named-variables were equal:
$_SESSION['line'] = $line; ('$line' was taken from URL call)
so just dont do such mistakes ;)
martinlarsen at bigfoot dot com
06-Jan-2006 01:07
Here is another way of losing session variables (not complete sessions):
I kept loosing *some* session variables controlling logins, but most of the session vars stayed intact. After nearly going crazy, I discovered that the web host had register_globals ON.
That meant that each time I assigned a variable with the same name as a session variable, the session variable changed too!
For example:
$_SESSION['id'] = 100;
$id = 0;
echo $_SESSION['id'];
// This prints 0, not 100!
If some of your session vars dissappear or change mysteriously, look out for register_globals = ON !!!
james at skinsupport dot com
23-Dec-2005 03: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
07-Dec-2005 02:57
Revise that use:
<address>?$_COOKIE['sessionname']='.SID
zackbloom at gmail dot com
04-Dec-2005 08: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.
Adrian
02-Dec-2005 11:58
Call session_start() first!
Using PHP v4.3.4, this worked fine:
<?php
require('includes/functions.php');
session_start();
...
?>
Using PHP 5.0.5, it broke, causing the session vars to be lost when the page was reloaded, even though nothing was '...output to the browser...' before calling session_start(). The fix, obvious now, was the devil to find:
<?php
session_start();
require('includes/functions.php');
...
?>
gocaballero at hotmail dot com
01-Dec-2005 07:46
in responce to gadgetguy03 at lycos dot com
SESSION LOST ON HEADER REDIRECT (CGI on IIS 5.0)
and ma at technoprint dot ch
I have the same server setup.
I fought this for days. Then I realized that If I create the session with session_start() without setting any session variables on the page before I needed to set session variables and then do a redirect, everything magically worked.
It was only when there was no session in existence that the following code would not work as expected.
/***** sess1.php *****/
session_start();
$_SESSION["key1"] = "testvalue";
session_write_close()
header("Location: sess2.php");
I've seen several post regarding this same issue, so I hope this is helpful.
shemszotATetkDOTca
22-Nov-2005 07:12
Regarding "lost session data in Firefox". Another reason why sometimes session data may appear lost in firefox or mozilla while it works in IE, is the handling of subdomains. If in mozilla you redirect from yourdomain.com to www.yourdomain.com, the session_start command will create a new session cookie on the new domain. Sessions are Domain Specific!! IE doesn't care if you're on www.yourdomain.com or on yourdomain.com, and it appears to use the same session information (as long as they map to the same IP).
jeremygiberson at gmail dot com
17-Oct-2005 08: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');
?>
info at dcooperinc dot com
14-Oct-2005 09:10
Someone mentioned a broken image link in IE dropping session variables - I had the same problem but in Firefox (vers. .9) I.E. Worked fine.
It took me a while to figure out that is was a broken image resulting in dropped session data - but not days - so thanks for your hint.
After I fixed the broken image, all was good.
Anonymous
27-Aug-2005 07:15
I think corey at eyewantmedia dot com's problem was really that each page was blocking on the same session. One session per user + one page loading concurrently per user = one database connection per user. He should use session_write_close(); after he's done with the session. I bet that will fix it.
kostik13 at gmail dot com
12-Aug-2005 11:33
using session_write_close() really hepls when session data disappear during redirect
ethomas at csd dot abdn dot ac dot uk
26-Jul-2005 08:34
I had a problem because I was using a session to store whether or not the the user wanted to save their session for 7 days. Unfortunately I could not use session_set_cookie_params() because I had to call it after a session_start and the default had been set. I got around this by calling
<?php
setcookie(session_name(),session_id(),time()+3600*24*7);
?>
After session_start() which undid the damage
bkatz at usefulengineering dot com
17-Jul-2005 05:08
Because session_start() does indeed prevent another page using session_start() from running until the first one is done, i use session_write_close() before doing any operation that takes significant time. For instance, session_write_close() worked as a lifesaver for me when automatically uploading files to a user (forcing a download instead of a link). When files are large, my site was not able to upload more than one file at a time to a user. By using session_write_close() before beginning the file upload, my users can now download as many big files as they like, at the same time. Example:
<?
session_start();
session_write_close();
header("Content-type: audio/x-mpeg"); header("Content-Disposition: attachment; filename=" . $filename);
header("Content-Length: " . $filesize);
header("Content-Transfer-Encoding: binary\n\n");
header("Pragma: no-cache");
header("Expires: 0");
$file_contents = file_get_contents($filepath);
print($file_contents);
?>
andrej at agsmart dot com dot au
15-Jul-2005 07:45
a quick note on sessions and ie6 losing them. this one took me months to work out..
in forefox everything worked fine between pages (in redirects and include statements) then in ie5 and 6 the session would be lost on only _one_ of my pages for no apparent reason.
long story short, it turned out that this particular failing page had references to broken images with alt text of "no image". every time ie requested the image and couldnt find it it displayed the icon of a broken image and killed the session as well! firefox behaved nicely and displayed "no image"
an if statement later to display text instead of a broken image and everything worked. hope this saves someone the headache it gave me..
servers affected: apache2/php4/win32, apache1/php4/linux and most likely more
aidan at snogspot dot com
06-Jul-2005 06:04
For all IIS5 (W2K) + PHP users with sessions dropping:
I was tearing my hair out with $_SESSION[] variables being lost between pages on a header("Location: ...") command.
Fortunately another user on here had posted something that helped me... the solution was to use the ISAPI module instead of the cgi exe.
Hope this helps someone in the same situation.
aaron at brackenclan dot com
15-Jun-2005 05:51
I struggled with this for 3 days and wanted to share my thoughts, if anything is wrong, someone please correct me.
When you do a session_start() and it isn't a persistant session (meaning when the browser is closed the session is ended) it does not write a cookie to your computer and it does not re-write the url if you have cookies turned off. Instead it simply passes it along in the http header inforamation as Cookie: PHPSESSID=79b928a4cc86d5761d074e40f5f9b7f7 and references the file on the server that corresponds to store variables
Then next step is under IE 6.0 all child windows share the http information with the parent. Meaning if you have a window open and you have a link that opens a new window, they share that info.
My problem was I have two subdomains with seperate securities. I wanted to pass a user from one to the other using seperate securities and sessions. The only way to do this is to name the sessions using session_name('whatever'); on at least one of the sites or else the cookies will over write each other. Once I did this the http header info looked like this Cookie: intranet=cd429d1947ffc947856065f0bfdee799; PHPSESSID=79b928a4cc86d5761d074e40f5f9b7f7
and everything worked fine
ventr[at]wp.pl
28-May-2005 01:30
As a side note, if You use in your script
<?
session_start();
$_SESSION["foo"] = 'bar';
session_write_close()
require("some_script.php");
?>
//some_script.php
<?
session_start();
$tmp = $_SESSION["foo"];
session_write_close();
print("$tmp");
?>
In required script session values aren't visible.
Only way is to redirect browser to some_script.php
and then sessions start to work.
This happens at Windows platform. If someone could input
results from Unix/Linux platform, it would be nice then.
Still have no idea how to put working sessions in required
script, hope someone will save time from avoiding this.
erm[at]the[dash]erm[dot]com
27-May-2005 10: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);
?>
k dot remizov at gmail dot com
24-May-2005 03:55
Unfortunatly session_start doesn't update the cookie info
so if I use such construction:
session_set_cookie_params(SESSION_LIFETIME);
session_start();
cookies expiration time doesn't updates every time((
So, after some time spent dancing with tambourine I start using :
setcookie(session_name(),session_id(),time()+SESSION_LIFETIME);
corey at eyewantmedia dot com
20-May-2005 04: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!
frank_hayward at hotmail dot com
03-May-2005 09: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 07: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
12-Apr-2005 01: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.
jorrizza at gmail dot com
02-Apr-2005 03: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 09: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 02: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 11: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(); ?>
raphael at cynage dot com
22-Feb-2005 05: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.
Jos
|