When to create cookies at client side(browser) - javascript

I understand the importance of creating cookies at server side , it is for transferring information between server and browser ,since HTTP is stateless protocol.
But I am not aware about why and when cookies are created at client side (browser).
Hope my question makes sense.

But I am not aware about why and when cookies are created at client
side (browser).
Because if you want to save for example settings for the user you can use cookies. It might be easier as setting them in php $_COOKIE (serverside).
BUT make sure it is no data which contains password or similiar - cookies can be shown in the browser
document.cookie = "name=value";
document.cookie = "username=smith"; // setting two cookies
document.cookie = "lastlogin=Dec 1 2045";
...
alert(document.cookie); "username=smith; lastlogin=Dec 1 2045"
JS has a global document.cookie field (which is a magical string with
odd behavior) when you assign into document.cookie, it actually
appends / concatenates a new cookie (an unfortunate syntax that does
not match the expected semantics of the = operator)

This can be for many reasons. I use cookies on the client side to store non-sensitive information about the user that may be useful to know the next time they access the site.
For example if I am building a shopping website. I could ask the user to pick a currency and store that in a cookie so next time the user accesses the website I can read that cookie and set the currency without prompting the user.

Often, client-side cookies is used to store key to extract stored information from database or other storage
http://screencast.com/t/mzvp9jTP

Related

Does Javascript have a higher level API for accessing cookies?

All the cookie handling examples I've seen for Javascript treat cookies as a string and do their own splitting and parsing etc.
Before I do this myself by hand, I want to check that there isn't a higher level API already available in, say, HTML5 / new javascript, for treating cookies as an associative array or something.
Is there?
Natively no. The document.cookie property holds the cookies, as a string, as you mention, and simply sends that string in the Cookie request header of the requests.
Then, wherever you need these cookies to be parsed (either on the client by accessing the document.cookie or on the server by accessing the Cookie request header), you have to implement your own parser or use one built already.
For storing things on the client side, you can use localStorage:
localStorage.setItem("foo", "42");
localStorage.getItem("foo");
// => "42"
But again, the server has no access to the localStorage.

Users can set cookies in console?

I'm wondering the best way to implement cookies to my site. I would like a user to be able to edit a given post based off a cookie that I set at the time the post is created.
I'm using Angular to set the cookie. ie:
var favoriteCookie = $cookies.myFavorite;
$cookies.myFavorite = 'oatmeal';
(per the Angular tutorial for $cookies).
My question is more at the core of how to use cookies. Wouldn't it be easy for a user to set the cookie using the console? ie:
document.cookie = 'key=value';
And get access to a post for editing? Perhaps I should be creating a unique id to use as a cookie that I then check for when the actual creator visits the page? If so, how might I go about this to best ensure only the actual creator of the post has access to editing?
You can restrict JavaScript manipulation by setting the HttpOnly flag in the cookie on a response. The console won't be able to set it programatically.

Best way To handle a Cookie

i am newbie at developing web Application and like to learn best practices
i want to know what is the best practise to handle the cookie data should one use JavaScript or PHP to handle a cookie data?
1.Do you use javascript to get cookie and than pass it to PHP to do all the filtering ?
2.Do you use PHP to do all of the stuff?
3.Which one of the above will improve performance or is there another way?
should one use JavaScript or PHP to handle a cookie data?
To make this a little more general, let's call this "Client side" (which is almost exclusively JavaScript) and "Server side" (which can be PHP, JavaScript or any other language) code.
The short answer is that: It depends what you are doing with the cookie data.
Most of the time, dealing with cookies server side is simpler.
Sometimes, the information in the cookie needs to be secure, and you don't need to access it from client side code, so you'll set an http only flag on it so that if you suffer an XSS attack the damage is limited.
Sometimes you will want to avoid making a server round trip (to take a trivial example: You allow the user to pick different stylesheets for your website. You don't want to reload the entire page when their change their preference. You use client side code to change the stylesheet currently loaded, and client side code to store that preference in a cookie. In the future, when other pages are loaded, you can use server side code to set a different <link> element.)
Do you use javascript to get cookie and than pass it to PHP to do all the filtering ?
You might use client side code to set a cookie value, and then use server side code to read it. There is no point in using JavaScript to read it and then using some non-cookie based mechanism to send it to server side code. That just makes things complicated and more likely to go wrong.
Do you use PHP to do all of the stuff?
Only if all the stuff is better done with PHP
Which one of the above will improve performance or is there another way?
As is normal with questions of client side code vs server side code: If you aren't loading a new page anyway, then using client side code is usually faster.
It depends on the type of application.
If your application is full request based with PHP as backend, then use can PHP tot extract cookies.
check this link http://www.w3schools.com/php/php_cookies.asp
Or, if you application follows REST architecture or you want send data to the backend using Ajax. Then use javascript/Jquery to get cookie value and send it to the backend server that is PHP or in any other language.
Check this link to know, how to access cookies using jquey.cookie.js plugin:
https://github.com/carhartl/jquery-cookie
In handling cookies, it does not really matter whether you use javascript or PHP, it just depends on when it is more beneficial to access/manipulate them. Server-side stuff always seems more secure, but cookies are always accessible, client or server-side, so it doesn't really matter. You can create a cookie in PHP like this:
setcookie($cookieName, $cookieValue, time() + 3600);
That sets a cookie for an hour, you can then access it through the $_COOKIE superglobal array with array notation, for example
$var = $_COOKIE[$cookieName];
However, keep in mind that this won't work if cookies aren't enabled in the browser, such as when someone uses incognito mode.
In javascript, you can set cookies like this:
document.cookie="cookiename=cookievalue";
However, cookies in javascript are all concatenated as one big string in document.cookie, so the way to break them up into a normal array is with the split function, for example:
var arr = [];
function getCookieArray() {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
You can find more about that here http://www.w3schools.com/js/js_cookies.asp
So, remember, that cookies are not for storing sensitive data. They're often used to store preferences, but never anything that people shouldn't be able to have access to.

Getting Cookie for a website for a User

Is it possible to search a web page's cookie files for the cookies corresponding to a particular user?
For Example, given any of the functions defined here, I hope to be able to pass in a website URL and a name and function returns the cookie for that user(if any); All this happening when I run the script.
Or, how can I get the username from the cookies collected?
Also, When I run commands like document.cookie, it returns a dialog with some variables and values. Variable like localle, c_user, csm, sub, act, etc... What is the meaning of these variables? Is it possible to uniquely identify a cookie given the a username?
JavaScript, when embedded in an HTML document, has access to the cookies the browser has set for that page.
It cannot access cookies for a different page (unless the cookie is shared between them).
It cannot access cookies for other browsers (since the cookies are not stored in the browser running the JS).
Update re edit (which, BTW, should have been a new question):
document.cookie gives you a string containing the cookies for the document. The cookie names are determined by the author of the code that set them. They mean whatever that person wants them to mean.
Cookies can be identified by their name. Cookies do not have usernames (although the author of the code that set the cookie might store a username in a cookie).

Javascript storing variable

I want to store some variable to the client side, currently, I have few selection (javascript variable, cookie, session), because I want to reduce the workload from the server, so the incoming parameter will not check on the server side.
For example,
Client side
<div id="showmoney"></div>
<script>
var money=10000;
$('#showmoney').html(money);
function changemoney()
{
{ pass the variable 'money' by ajax to php...}
}
</script>
PHP side
<?
$money = $_POST['money'];
$sql = "UPDATE user_details SET money = ".$money." WHERE uid = 123";
{ do query...}
?>
Are there any method make it more secure, because I afraid someone can modify the javascript variable by tools(firebug? if yes, how?)
thanks a lot~:)
Every variable that you do not want the user to change (such as a price tag) HAS to be stored on the server and not on the client. There are A LOT of ways to change what the client sends to you, and FireBug is just the simplest tool. More sophisticated tools will allow to intercept and edit every HTTP request..
Are there any method make it more secure, because I afraid someone can modify the javascript variable by tools(firebug? if yes, how?)
You can never, ever trust incoming data from the client. It can always be manipulated. Essential checks like prices you need to do on server side - a client side check is merely for the user's convenience.
Also, the code you show has a SQL injection vulnerability that you should sort out.
Anything you store in the client (browser) can be manipulated. The fix for your issue, is to verify that the information sent back to the server hasn't been tampered.
People can do just about anything to the page they want.
In the Google Chrome debugger (accessed with Ctrl+Shif+J) they could do the following in the console:
money = 10000000000000; //Or whatever arbitrary value they choose
changemoney();
As other people have said, never trust anything that people pass into the server from the client. The server needs to do a sanity check.
you have to align your desire to store something on the client for performance with the need for security. Sensitive info should only be on the server. Any savvy web user can tweak the javascript. Save bandwidth by putting other, less sensitive info on the client.
are you know about client side database storage the brand new API in HTML5. trying to find sollution with them. maybe helpful for you to save some data on client side.

Categories