Using Sessions Without Cookies


PHP stores a user's session ID in a cookie, so it can determine which set of session data it should load as needed. But what if the user has cookies turned off? In that case, PHP can try to encode the session ID in all URLs accessed by the user. To enable that capability, set the session.use_trans_sid item in php.ini to 1 (you can also specify that PHP use only cookies for session IDs by enabling session.use_only_cookies):

 ; trans sid support is disabled by default. ; Use of trans sid may risk your users security. ; Use this option with caution. ; - User may send URL contains active session ID ;   to other person via. email/irc/etc. ; - URL that contains active session ID may be stored ;   in publically accessible computer. ; - User may access your site with the same session ID ;   always using URL stored in browser's history or bookmarks. session.use_trans_sid = 0 

This way, the user's URLs will look something like this:

 script.php?PHPSESSID=322fe03120041e6c5285480a4fbf1037 

This item, session.use_trans_sid, is turned off by default because explicitly listing the session ID like this is a security problem. So what if the user has cookies turned off and session.use_trans_sid is turned off too? In that case, you can explicitly pass the session ID to other pages yourself. You do that by storing the session ID, which you can get with the function session_id, in a hidden variable named PHPSESSID, as shown in phpsessionnocookies.php, Example 9-16.

Example 9-16. Passing session ID without cookies, phpsessionnocookies.php
 <HTML>     <HEAD>         <TITLE>Storing data in sessions without cookies</TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>Storing data in sessions without cookies</H1>             <?php                 session_start();                 $_SESSION['temperature'] = "72";             ?>             Stored the temperature as 72 degrees.             <BR>             To read the temperature in a new page, click Submit.             <BR>             <FORM ACTION="phpsession2.php" METHOD="POST">                 <INPUT TYPE="HIDDEN" NAME="PHPSESSID" VALUE="                 <?php                     echo session_id();                 ?>                 ">                 <INPUT TYPE='SUBMIT' VALUE='Submit'>             </FORM>         </CENTER>     <BODY> </HTML> 

You can see this page at work in Figure 9-15.

Figure 9-15. Handling sessions without cookies.


No further programming is needed to pick up the session ID in the target page, phpsession2.php, which is unchanged from Example 9-13. You can see the successful results in Figure 9-16. Nice.

Figure 9-16. Using session data without cookies.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net