473,548 Members | 2,598 Online
Bytes | Software Development & Data Engineering Community
+ 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 2272
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
3357
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 on the testing server but that didn't seem to make any difference. One difference I noticed is that on the dev server, the session cookie is...
1
2935
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 this regular cookie? How about session cookie? and when to use which?
3
5957
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 the value of that session cookie in response to a button click in a form, without resubmitting the page. For some reason, the following doesn't...
5
1970
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 control it? Yossi.
3
7361
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) supplied by the remote Webserver I can successfuly logon but when I redirect to the supplied url, the webserver does not know me anymore an redirects...
2
1863
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 situation. Would a session cookie do the trick? From what I have read, it is persistent until the browser window closes. Is that correct? Even if the...
1
9181
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 (IE6 in test case) despite trying Microsoft's suggested method of expiring the cookie first. I'd like to be able to kill the cookie and do a...
7
7767
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 ASP.NET always sets the Session cookie domain to the full domain (e.g. "www.mydomain.com") instead of the parent domain (e.g. "mydomain.com") The...
4
1240
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 request. This means the server receives a request without user information and redirect the user to the login page. Somebody any bright ideas? ...
4
1693
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 the FormsAuthentication cookie are binded. 3. I need to know whether it's possible by Code or settings to treat the
0
7512
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7438
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7803
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6036
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5362
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3475
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1926
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 we have to send another system
1
1051
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
751
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.