note 39695 deleted from function.session-start by didou

From: Date: Sat, 07 Feb 2004 20:09:33 +0000
Subject: note 39695 deleted from function.session-start by didou
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-64795@lists.php.net to get a copy of this message
Note Submitter: scott mcnair (code demon) ---- Using $_SERVER['PHP_SELF'] to recall script and then losing/lost all your $_SESSION vars? $_SESSION vars not being saved or dissappearing? I had 3 seperate forms for a registration process. 1) get a login/password info 2) get user info address, etc. 3) get user preferences I tried to combine these into ONE script that would peform all the steps neccessary by having all the forms in one script, but, showing only the appropriate form at the proper time. (Using a POST var in each form called "nextstep" then using a switch in the script to decide which form to show.) This made the entire process more managable and encapsualted. At the beginning of the script I had the usual if (!session_id()) {session_start();} In each form, I set: $SELF = $_SERVER['PHP_SELF']; echo <<<EOT <form method="post" action="$SELF" ...> <input type="hidden" name="nextstep" value="xxx" /> .... </form> EOT; BUT, when the form posted, it LOST ALL the $_SESSION vars and started a fresh session. What? Huh? Well, actually this is the EXPECTED behavior. Since many users disable cookies, the SID/session_id() is passed to the NEXT html/page with a GET variable (ie. After you start a session and click on submit, the target/next page/URL is http://xxx.xxx.xxx/page2.php?PHPSESSID=asgakdslsjdldsl) PROBLEM: I was calling "$SELF" which does NOT have the ?PHPSESSID=ddlsfjasj appended automatically. ANSWER: You need to MANUALLY pass the ?PHPSESSID=sldjfdlj. HOW? Two possibilities: a) $SELF= $_SERVER['PHP_SELF'] . "?PHPSESSID=" . session_id(); <form method="post" action="$SELF" ...> This causes a problem in that now the full session_id() is seen by the user in the URL as a GET var and a hacker my hi-jack the session. b) Pass the session_id() as a HIDDEN POST var in the form Ex: function getlogininfo() { $SELF = $_SERVER['PHP_SELF']; $SID = session_id(); echo <<<EOT <form method="post" action="$SELF" ....> <input type="hidden" name="PHPSESSID" value="$SID" /> <input type="hidden" name="nextstep" value="getuserinfo" /> ..... </form> EOT; } function getuserinfo() { $SELF = $_SERVER['PHP_SELF']; $SID = session_id(); echo <<<EOT <form method="post" action="$SELF" ....> <input type="hidden" name="PHPSESSID" value="$SID" /> <input type="hidden" name="nextstep" value="getuserprefs" /> ..... </form> EOT; } **NOTE** you have to set $SELF/$SID as LOCAL variables if you are using the HEREDOC form of printing the html code because $_SESSION / superglobals and defines such as SID can't be parsed in HEREDOCS but local vars can. Hope this helps someone else, it annoyed me for two days...

« previous php.notes (#64795) next »