473,480 Members | 3,017 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

How do I make a session cookie?

11 New Member
How do I make this code below into a session cookie that deletes once the page is closed?

Expand|Select|Wrap|Line Numbers
  1. <script>
  2.  
  3. /*
  4. Very simple validation for the login.
  5. */
  6. function validateLogin()
  7. {
  8.    var username = document.getElementById("username").value;
  9.    var pwd = document.getElementById("password").value;
  10.    // encrypt the username and password
  11.    var userEntryEncryption = hex_md5 (username + pwd);
  12.  
  13.    /* 
  14.    Encrypt "username" + "books" and compare to what the user entered in the 
  15.    username and password fields. The comparison takes the 'hash' of the
  16.    'userEntryEncryption' variable and the 'md5Encryption' variable and test
  17.    whether they match.
  18.    NOTE: On a production site, the 'userEntryEncryption' would be sent to some server 
  19.    side code on a webserver, which would perform the validation and return true or
  20.    false, depending on whether it succeeded.
  21.    */
  22.    var md5Encryption = hex_md5 ("username" + "books");
  23.  
  24.    // both hashes must match
  25.    if (userEntryEncryption === md5Encryption)
  26.    {
  27.       /*
  28.       Determine the expiry for the cookie depending on whether the user
  29.       wants the login information remembered.
  30.       */
  31.       var remember = document.getElementById("rememberMe").checked;
  32.       var expiry = getCookieExpiry(remember);
  33.  
  34.       // the value of our cookie is the encrypted username + password
  35.       setCookie(md5Encryption, expiry);
  36.  
  37.       // redirect to the "members" page
  38.       document.location.href = "checkout2.html";
  39.       return true;
  40.    }
  41.  
  42.    document.getElementById("errorMessage").innerHTML = 
  43.             "The login information is incorrect. Please try again.";
  44.    return false;
  45. }
  46.  
  47.  
  48. /*
  49. Sets the cookie for a single logon.
  50. */
  51. function setCookie(encryptedPwd, expiry)
  52. {
  53.    var key = "userLogin";
  54.    var value = encryptedPwd;
  55.    var path = "/";
  56.  
  57.    document.cookie = key + "=" +escape( value ) +
  58.        ( ( expiry ) ? ";expires=" + expiry.toGMTString() : "" ) +
  59.        ( ( path ) ? ";path=" + path : "" );
  60. }
  61.  
  62.  
  63. /*
  64. If the user wants the login information remembered 
  65. (i.e. "rememberMe" is true), set a long expiry date, 
  66. otherwise, leave the expiry date empty so that the cookie
  67. will be deleted when the browser is closed.
  68. */
  69. function getCookieExpiry(rememberMe)
  70. {
  71.    var expiresDate;
  72.  
  73.    if (rememberMe === true)
  74.    {
  75.       // set time, it's in milliseconds
  76.       var today = new Date();
  77.       today.setTime( today.getTime() );
  78.  
  79.       /*
  80.       This will set the expiry date for x number of days.
  81.       To make it for hours, delete * 24, for minutes, 
  82.       delete * 60 * 24.
  83.       */
  84.       var expires = 365;
  85.       expires = expires * 1000 * 60 * 60 * 24;
  86.       expiresDate = new Date( today.getTime() + (expires) );
  87.    }
  88.  
  89.    // if "rememberMe" is false, "expiresDate" has no value 
  90.  
  91.    return expiresDate;
  92. }
  93.  
  94.  
  95.  
  96.  
  97. /*
  98. Returns the cookie associated with the "key" variable.
  99. */
  100. function getCookie( key ) 
  101. {
  102.    // first we'll split this cookie up into key/value pairs
  103.    // note: document.cookie only returns key=value, not the other components
  104.    var allCookies = document.cookie.split( ';' );
  105.    var tempCookie = '';
  106.    var cookieName = '';
  107.    var cookieValue = '';
  108.    var cookieFound = false; // set boolean true/false, default is false
  109.  
  110.    for ( i = 0; i < allCookies.length; i++ )
  111.    {
  112.       // now we'll split apart each key=value pair
  113.       tempCookie = allCookies[i].split( '=' );
  114.  
  115.       // and trim left/right whitespace while we're at it
  116.       cookieName = tempCookie[0].replace(/^\s+|\s+$/g, '');
  117.  
  118.       // if the extracted cookieName matches the "key" parameter
  119.       if ( cookieName == key )
  120.       {
  121.          cookieFound = true;  // cookie is found
  122.          // we need to handle case where cookie has no value but exists (no = sign, that is):
  123.          if ( tempCookie.length > 1 )
  124.          {
  125.             cookieValue = unescape( tempCookie[1].replace(/^\s+|\s+$/g, '') );
  126.          }
  127.          break;
  128.       }
  129.       tempCookie = null;
  130.       cookieName = '';
  131.    }
  132.    if ( !cookieFound )  // the user has not logged in yet so go to the login page
  133.    {
  134.       location.href = "checkout.html";
  135.    }
  136.    // otherwise, set the CSS style to visible
  137.    else
  138.    {
  139.       document.getElementById('content').style.visibility = "visible";   
  140.    }
  141. }
  142.  
  143. </script>
Thanks
Mar 7 '11 #1
3 2267
Dormilich
8,658 Recognized Expert Moderator Expert
if you want to delete the cookie when the page is closed, you have to do that by JavaScript itself (e.g. the unload or beforeunload event). if it suffices to delete the cookie when the browser is closed, set the cookie lifetime to 0.
Mar 7 '11 #2
Taylor Smith
11 New Member
To set the life of the cookie to 0 would i do this?

Expand|Select|Wrap|Line Numbers
  1. <script>
  2. function getCookieExpiry(rememberMe)
  3. {
  4.    var expiresDate;
  5.  
  6.    if (rememberMe === true)
  7.    {
  8.       // set time, it's in milliseconds
  9.       var today = new Date();
  10.       today.setTime( today.getTime() );
  11.  
  12.       /*
  13.       This will set the expiry date for x number of days.
  14.       To make it for hours, delete * 24, for minutes, 
  15.       delete * 60 * 24.
  16.       */
  17.       var expires = 0;
  18.       expiresDate = new Date( today.getTime() + (expires) );
  19.    }
  20.  
  21.    // if "rememberMe" is false, "expiresDate" has no value 
  22.  
  23.    return expiresDate;
  24. }
  25. </script>
Will that make it a session cookie?

Thanks
Mar 9 '11 #3
Dormilich
8,658 Recognized Expert Moderator Expert
The Expires directive tells the browser when to delete the cookie. It is specified in the form of “Wdy, DD-Mon-YYYY HH:MM:SS GMT”, indicating the exact date/time this cookie will expire.
… if you just omit the Expires directive, the lifetime is set as 0
Mar 9 '11 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

7
3353
by: Henry Hartley | last post by:
I've got a PHP system working on a development server (Windows 2000/IIS5/PHP 4.3.3) but it doesn't seem to be working quite right on the testing server (same except PHP 4.2.3). I upgraded the PHP...
1
2929
by: Matt | last post by:
I want to know what's the differences between session cookie and regular cookie. In ASP, when we create cookie, we do the following to identify an user: Response.Cookies("name") = value Is...
3
5944
by: M Wells | last post by:
Hi All, Just wondering how you go about changing the value of a session cookie via javascript? I have a PHP page that sets a session cookie when it first loads. I'd like to be able to change...
5
1966
by: Yossi | last post by:
I want to set the asp session id path property. how can I do that? I mean, asp session id is stored in a cookie and like any other cookie it should have properties (or attributes), how can I...
3
7359
by: Karsten Grombach | last post by:
Hi, I'm trying the following: - Imitate a Logon using a Post with HttpWebRequest on remote Webserver (asp 3.0 page using https) - On success redirect to the page (encapsuled in an iframe)...
2
1856
by: Earl Teigrob | last post by:
I am trying to find storage mechanism that will store a variable until the browser window is closed. A query string variable would be my first choice for this but that is not easily done in my...
1
9149
by: Daniel Michaeloff | last post by:
Hi all, I have an application that when finished redirects to a non-ASP.NET app which is choking on a huge ASP.NET session cookie. The cookie "ASP.NET_SessionId" gets transmitted by the browser...
7
7756
by: Doug | last post by:
An ASP.NET session cookie set on "www.mydomain.com" can not be accessed on "search.mydomain.com"; hence, a new session and cookie are being created on every sub-domain. This is occuring because...
4
1234
by: nico | last post by:
I store the authenticated user in a session cookie. This cookie expires after an hour. Now for some reason sometimes the client browser decides not to send the session cookie information with a new...
4
1686
by: Ibrahim. | last post by:
Hi, Kindly clarify the followings; 1. Is the session cookie & FormsAuthenticationTicket cookie Interdependent? 2. When a new SessionID is generated, I have noticed the Session Cookie and...
0
6920
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6760
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7022
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5365
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4799
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3004
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1311
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
206
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.