![]() |
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]()
![]() |

|
| Programming tutorials All Knowledge Info and links to posted here |
![]() |
|
PHP Script Tips - Understanding and Using Sessions
|
LinkBack | Thread Tools | Display Modes |
|
|
#1 (permalink) |
|
Administrator
Posts: 18,715
Join Date: Jan 2006
Rep Power: 10
IM:
|
A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests. There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor. Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor. How To Turn On the Session Support? The session support can be turned on automatically at the site level, or manually in each PHP page script:
When session is turned on, a session will be automatically created for you by the PHP engine. If you want to save any values to the session, you can use the pre-defined associative array called $_SESSION. The following PHP script shows you how to save values to the session: <?php session_start(); print("<html><pre>"); $_SESSION["MyLogin"] = "FYICenter"; print("A value saved in the session named as MyLogin.\n"); $_SESSION["MyColor"] = "Blue"; print("A value saved in the session named as MyColor.\n"); print("Click <a href=next_page.php>Next Page</a>" ." to retrieve the values.\n"); print("</pre></html>\n"); ?> </pre> If you save this script to your Web server as first_page.php and visit it with a browser, you will get: A value saved in the session named as MyLogin. A value saved in the session named as MyColor. Click Next Page to retrieve the values. </pre> How To Retrieve Values from the Current Session? If you know some values have been saved in the session by an other script requested by the same visitor, you can retrieve those values back by using the pre-defined associative array called $_SESSION. The following PHP script shows you how to retrieve values from the session: <?php session_start(); print("<html><pre>"); $myLogin = $_SESSION["MyLogin"]; print("Value of MyLogin has been retrieved: ".$myLogin."\n"); $myColor = $_SESSION["MyColor"]; print("Value of MyColor has been retrieved: ".$myColor."\n"); print("</pre></html>\n"); ?> </pre> You need to save this script to your Web server as next_page.php. Now visit first_page.php and click the "Next Page" hyper like, you will get: Value of MyLogin has been retrieved: FYICenter </pre>What Is a Session ID? A session ID is an identification string of a session. Since there might be multiple visitors coming to your Web site at the same time, the PHP engine needs to maintain multiple sessions concurrently. Session IDs are created and maintained by the PHP engine to identify sessions. When a visitor comes to your Web site requesting the first PHP page for the first time, the PHP engine will create a new session and assign a unique session ID to this new session. The first PHP page can set some values to the session. When the same visitor clicks a hyper link requesting the second PHP page, the PHP engine will use the same session ID to find the same session created for the first page and give it to the second page. No new session will be created for the second page. How To Retrieve the Session ID of the Current Session? Normally, you don't need to know the session ID of the current session. But if you are interested to know the session ID created by the PHP engine, there are two ways to get it:
<?php session_start(); print("<html><pre>"); $sid = session_id(); print("Session ID returned by session_id(): ".$sid."\n"); $sid = SID; print("Session ID returned by SID: ".$sid."\n"); $myLogin = $_SESSION["MyLogin"]; print("Value of MyLogin has been retrieved: ".$myLogin."\n"); $myColor = $_SESSION["MyColor"]; print("Value of MyColor has been retrieved: ".$myColor."\n"); print("</pre></html>\n"); ?> You need to save this script to your Web server as next_page.php. Now visit first_page.php and click the "Next Page" hyper like, you will get something like this: Session ID returned by session_id(): rfnq17ui6c7g6pjbtc46n0vi97 Session ID returned by SID: PHPSESSID=rfnq17ui6c7g6pjbtc46n0vi97 Value of MyLogin has been retrieved: FYICenter Value of MyColor has been retrieved: Blue Now you know that the session ID created by the PHP engine is 26 characters long with alphanumeric characters only. What Are the Options to Transfer Session IDs? Once a new session is created, its session ID must be transferred to the client browser and included in the next client request, so that the PHP engine can find the same session created by the same visitor. The PHP engine has two options to transfer the session ID to the client browser:
How Session IDs Are Transferred on Your Web Server? As you know there are two options the PHP engine can use to transfer session IDs to the client browsers. But how to do know which option is your PHP engine is using? The PHP sample script will help you to find out: <?php session_start(); print("<html><pre>"); $queryString = $_SERVER["QUERY_STRING"]; print("Query string of the incoming URL: ".$queryString."\n"); print("Cookies received:\n"); foreach ($_COOKIE as $name => $value) { print " $name = $value\n"; } $myLogin = $_SESSION["MyLogin"]; print("Value of MyLogin has been retrieved: ".$myLogin."\n"); $myColor = $_SESSION["MyColor"]; print("Value of MyColor has been retrieved: ".$myColor."\n"); print("</pre></html>\n"); ?> You need to save this script to your Web server as next_page.php. Now visit first_page.php and click the "Next Page" hyper like, you will get something like this: Query string of the incoming URL: PHPSESSID=meml483hk4dvm1n2ii8k9hvjj1 Cookies received: Value of MyLogin has been retrieved: FYICenter Value of MyColor has been retrieved: Blue Base on the output, your PHP engine is using URL parameters to transfer session IDs, because you can see the session ID parameter in the query string of the incoming URL, and there is no cookies related to session ID. Another way to confirm that your PHP engine is using URL parameters to transfer session IDs is to look at the address field of your browser, it will show something like: http://localhost/next_page.php?PHPSE...m1n2ii8k9hvjj1 </pre> How To Force the PHP Engine to Use Cookies to Transfer Session IDs? If you want to force your PHP engine to use cookies to transfer session IDs instead of URL parameters, you can open the PHP configuration file, php.ini, and make the following changes: session.use_cookies = 1 session.use_only_cookies = 1 </pre> Now re-run the first_page.php and next_page.php scripts presented in the previous tutorials. You will get something like: Query string of the incoming URL: Cookies received: PHPSESSID = r66hq1bcg8o79e5i5gd52p26g3 Value of MyLogin has been retrieved: FYICenter Value of MyColor has been retrieved: Blue </pre> Base on the output, your PHP engine is using cookies to transfer session IDs now, because you can see the cookie named as PHPSESSID contains the session ID, there is no URL parameters related to session ID. Is It More Secure to Use Cookies to Transfer Session IDs? Is it more secure to use cookies to transfer session IDs? The answer is yes, because attacking your Web site using URL parameters is much easier than using cookies. So if you are the system administrator of your Web server, you should set session.use_only_cookies=1. If your Web server is provided by a hosting service provider, ask them to set session.use_only_cookies=1. Where Are the Session Values Stored? When a value is saved into the current session by one PHP page, the PHP engine must stored this value somewhere on Web server, so that the PHP engine can retrieve it back when same visitor comes back to request another PHP page. Where are the session values stored on the Web server? The answer depends on the setting named, session.save_path, in the PHP engine configuration file. If session.save_path = "/temp", session values will be stored in special files, one file per session, in the /temp directory on the Web server. If you re-run the first_page.php and next_page.php scripts presented in the previous tutorials, you can find a special file named like: \temp\sess_r66hq1bcg8o79e5i5gd52p26g3. If you open this file, you will see: MyLogin|s:9:"FYICenter";MyColor|s:4:"Blue"; </pre> Now you know that session values are stored on the Web server as text files, and values are formatted with value names and lengths. What Is the Timeout Period on Session Values? The PHP engine has no direct settings on session timeout period. But it has a session garbage collection mechanism that you can set to remove those special files containing session values. There are 3 settings you can use to define the session garbage collection mechanism: session.gc_probability = 1 session.gc_divisor = 1000 session.gc_maxlifetime = 1440 </pre> The first two settings tell the PHP engine to run the garbage collection process once every 1000 requests received by the Web server. The last setting tells the PHP engine to treat session values as garbage 1440 seconds after they have not been used. Putting all settings together, your session values probably be removed 1440 seconds after the visitor stopping using your Web site. The probability of this removal is one over 1000 requests received after the 1440-second period. In another word, if visitor John stopped using your site, and there is no other visitors coming to your site, session values created for John will never be removed. However, if you have a busy site, like 1000 requests per minute, John's session values will be removed about one minute plus 1440 seconds after John stopped using the site. How To Test the Session Garbage Collection Process? In order to test the session garbage collection process, you need to change the settings to expire session variables in 10 seconds and run the process on every request: session.gc_probability = 1 session.gc_divisor = 1 f you re-run the first_page.php and next_page.php scripts presented in the previous tutorials, you will see some thing like: Query string of the incoming URL: Cookies received: PHPSESSID = grm557vicj1edmiikgsa8hbd11 Value of MyLogin has been retrieved: FYICenter </pre>How To Close a Session Properly? Let's say you site requires users to login. When a logged in user clicks the logout button, you need to close the session associated with this user properly in 3 steps:
<?php session_start(); $_SESSION = array(); if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time()-42000, '/'); } session_destroy(); print("<html><pre>"); print("Thank you for visiting FYICenter.com.\n"); print(" <a href=login.php>Login Again.</a>\n"); print("</pre></html>\n"); ?> What Is session_register()? session_register() is old function that registers global variables into the current session. You should stop using session_register() and use array $_SESSION to save values into the current session now. Value of MyColor has been retrieved: Blue </pre>Wait for 10 seconds, and start another browser window to run first_page.php. This is to triger the session garbage collection process to remove values stored in session grm557vicj1edmiikgsa8hbd11. Go back to the first browser window on second_page.php, and click the browser refresh button, you will get something like: Query string of the incoming URL: Cookies received: PHPSESSID = grm557vicj1edmiikgsa8hbd11 Value of MyLogin has been retrieved: Value of MyColor has been retrieved: As you can see, session values are gone, the browser is still sending the same session ID as a cookie, but the all sesion values are expired (actually, the session file is removed by the garbage collection process). How To Set session.gc_maxlifetime Properly? As you know that session.gc_maxlifetime is the session value timeout period. You should set this value based on the usage pattern of your visitors. Here are some suggestions: # Set it to 20 minutes for a normal Web site: session.gc_maxlifetime = 1200 # Set it to 24 hours if visitors comes to the site many time a day: # Example: Yahoo email site expires your session in 24 hours. session.gc_maxlifetime = 86400 How To Set session.gc_divisor Properly? As you know that session.gc_divisor is the frequency of when the session garbage collection process will be executed. You should set this value based on the income request traffic. Here are some suggestions: # Set it to 10, if traffic is less than 10,000 per day: session.gc_divisor = 10 # Set it to 100, if traffic is between 10,000 and 100,000 per day: session.gc_divisor = 100 # Set it to 1000, if traffic is greater than 100,000 per day: session.gc_divisor = 1000 How To Remove Values Saved in the Current Session? If you want to remove values saved in the current session, you should use the unset() function on those saved values in $_SESSION, or use array() to empty $_SESSION:
There is not direct way to tell if a session is new or old. But you can design your site to have a required session value in all sessions. Then you can check the existence of this value in a session to determine if it is a new session by isset($_SESSION['name']). Let's say you decided to have a required session value called "Status" with two possible values: "Guest" and "Registered". The landing script of your site should look like: <?php session_start(); if (!isset($_SESSION['Status'])) { $_SESSION["Status"] = "Guest"; print("<html><pre>"); print("Welcome to FYICenter.com!\n"); print(" <a href=login.php>Login</a>\n"); print(" <a href=guest_home.php>Stay as a guest</a>\n"); print("</pre></html>\n"); } else { if ($_SESSION["Status"] == "Guest") { header( 'Location: http://localhost/guest_home.php'); } else if ($_SESSION["Status"] == "Registered") { header( 'Location: http://localhost/home.php'); } } ?> session.gc_maxlifetime = 10 </pre> Value of MyColor has been retrieved: Blue </pre> |
|
|
|
|
|
|
![]() |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Vulnerability discovered in YIM webcam sessions | Anilrgowda | Yahoo | 0 | 15-Aug-2007 11:47 PM |
| Auto-create locked interactive login sessions for all users on Windows boot | Anilrgowda | Microsoft windows vista error | 1 | 10-Jul-2007 12:09 AM |
| Understanding OU better | Anilrgowda | Microsoft windows 2003 error | 1 | 05-Jun-2007 02:43 AM |
| Understanding Msn | Anilrgowda | MSN Search Optimization | 0 | 30-Dec-2006 11:09 AM |
| PHP Script Tips - Understanding and Managing Cookies | Anilrgowda | Programming tutorials | 0 | 21-Dec-2006 02:07 AM |