Reputation: 5073
I have a blog with locked content. User needs to enter their email address into a form in order to see the full content.
Problem now is that the same user has to enter their email on every post. How do I implement cookies so that:
1) on a form submit, user gets a cookie 2) on a blog page load, check to see if cookie exists, and if it does, load the full content
--
I have minimal experience using cookies. Thanks!
Upvotes: 0
Views: 466
Reputation: 718
You could probably use the localStorage
object for this:
HTML:
<input type="text" id="email"/>
<input type="button" id="submit" value="submit"/>
JS:
$(document).ready(function(){
if (localStorage.getItem("email")){
$("#email").val(localStorage.getItem("email"))
// unlockContent();
// otherStuff();
}
$("#submit").click(function(){
localStorage.setItem("email", $("#email").val());
alert("Saved: " + localStorage.getItem("email"));
// unlockContent();
// otherStuff();
})
})
Fiddle: here.
edit: but as Benjamin mentioned in his answer, this is not really a secure mechanism -- unless you simply want to verify an email rather a particular email.
Upvotes: 1
Reputation: 2998
Creating JS cookies on the front-end is simple:
document.cookie="[email protected]";
Which creates a cookie named "email" that has a content of "[email protected]."
When a user goes to your site again, you can check whether the cookie exists.
if (document.cookie.indexOf("email")>=0) {
// Log them in!
}
else {
// Show log-in field!
}
You might also want a cookie to expire after a certain period of time. When you create a cookie, you can set an expire date:
document.cookie="[email protected];expire=06/12/2015";
However this isn't as secure as using sever-side cookies.
Upvotes: 1
Reputation: 276286
Cookies on the client will not give you the protection you seek because anyone with a browser could insert these cookies themselves. Moreover - client-side security over server-side content (the articles) inherently doesn't work. Any clever user will be able to get over any form of security measure that is not on the server.
That said, if you're entirely OK with users who do not install a specific extension or run a specific script to "unlock" your site - you can do something along the lines of:
if(document.cookie.indexOf("entered_email=true") === -1){
// show email request field
} else {
// show content
}
And when the user enters their email:
document.cookie += (document.cookie ? ";" : "") + "entered_email=true";
Upvotes: 1