View Full Version : password script and cookies

11-18-2007, 04:32 AM
Hey guys,
I got this simple password script for a page.

<script language="JavaScript">
var password = prompt("What's the password","Type password");

if (password == "yes")
} else {
alert("Sorry wrong password");

I want this code to create a session cookie until user leaves page or exits his browser, I want to eliminate the need to enter the password every time he goes to that page. Can you help?


11-18-2007, 03:06 PM
Not sure about JS... With PHP you can do a session variable.

Also, with JS you have to declair the password in the coding:

if (password == "yes")

This will show up when you view source., and if a browser turns off JS then it won't work at all.

I would go with PHP at a minimum, if you want to protect pages/directories then you really should use .htaccess

11-18-2007, 04:26 PM
Yes, I know. On my site I do use more advanced password protection.
However, this code is used on a site where I'm the user and I can only insert HTML inside body tags with no forms. This was the easiest way to somewhat protect content with prompt box, instead of form tags. The content is not that sensitive but I wanted to put password on it.


11-18-2007, 04:29 PM
Well, if session cookies in JS are what you want.. then you shall have (http://www.javascriptkit.com/javatutors/cookie.shtml)


11-18-2007, 05:04 PM
Javascript used in this manner is virtually no protection. A would be attacker could easily view the source code to get the password.

11-18-2007, 06:14 PM
You can always encode the password into HEX or something, but that won't stop anyone really, just deter them a little.

11-20-2007, 02:21 AM
I know it's very limited protection but content behind password is not sensitive or personal in any nature. All it is, discounted products for specific people. Just showing password box will let visitors know it's not for them.

Ok, thanks for the tutorial Blizzard, but I need help implementing it. I've never used cookies.

Thanks for the help,

11-20-2007, 01:51 PM
Read, read read. Honestly. I don't mind helping you at all, but part of this is you learning too. I could go step by step and show you what to do, but then if/when the code stops working right or it gets corrupt or out dated, etc. you need to know how to fix it.

If you Google "JS cookies" you will find a wealth of information and implementation, and I suggest you read as much as you can.

Once you have started and get stuck, then come back and ask for help with the code you have written.

It's not all that hard, honestly, and you will be all the better prepared for having done so :)