Best way To handle a Cookie - javascript

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.

Related

How i can use PHP Session in React?

I have a question of session PHP in React. I have to create an online shop in React and PHP. I currently programming a shopping cart. To do this, I have to use PHP Session. I can't use JWT, so my questions are:
How to start a Session if I can't include PHP code in index.html (react-create-app, MVC, I can't include start_session() at the beginning of the page)
How to retrieve data from Session (is it possible by ajax?)
I have never used PHP and React. So far I have only used restful API.
Please help.
Yes i think you can. Check this question and the most voted answer:
The answer is yes:
Sessions are maintained server-side. As far as the server is concerned, there is no difference between an AJAX request and a regular page request. They are both HTTP requests, and they both contain cookie information in the header in the same way.
From the client side, the same cookies will always be sent to the server whether it's a regular request or an AJAX request. The Javascript code does not need to do anything special or even to be aware of this happening, it just works the same as it does with regular requests.
Do AJAX requests retain PHP Session info?
What you can do is initialize a Javascript variable with your PHP variable. This is possible because PHP, a server-side language executes on the page before Javascript, so it's almost like entering plain text where the right-hand side of the JS line is.
An example would be something like this in your index.html file:
index.php (you must rename your index.html file to index.php so the computer knows there's some PHP in there). Also, must ensure PHP is installed in your local environment hosting this. Something like npm install PHP, brew install PHP, or yum install PHP will do.
<script>
// Note here: we must ensure name is set,
// otherwise it would look something like
// let name = ;
// this would cause an error
// that is why I check the value is present with isset()
let name = <? echo isset($name) ? $name : "Air"; ?>;
</script>
Therefore, I think you would just need to ensure your environment supports PHP. You can also use a subroutine/webservice/ajax call to do the same; however, this is a little bit more complex in regards to its setup.

java session in servlet the same as sessionstorage in javascript

I have a servlet which I call the following:
request.getSession().setAttribute("name", nameObj);
Can I access it from the following page using
console.log('IH HERE' + sessionStorage.getItem('name') );
It doesn't seem to work. Either js or jquery solution would be nice.
Thanks,
Scott
This won't work, for two reasons:
sessionStorage is client-side only; it's not sent to the server via HTTP requests and the server can't write it without talking to the client.
request.getSession() is server-side only, with a session ID stored in a cookie but nothing else stored in a client-accessible format.
You'll have to use cookies if you want to achieve this effect (read / write by both) or loop over the session and provide it all in the page somewhere (read only by client).

When to create cookies at client side(browser)

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

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.

Persist javascript variables between GET requests?

ASP .NET is allowed
Storing the values in hidden input fields is allowed
Query String is not allowed
POST request is not allowed
It is possible to store JS variables between GET requests ?
I want to reinitialize them on the client using ClientScript.RegisterStartupScript
Can I use cookies for this ?
Are there other posibilities?
Where cookies are stored when Request is made ?
Can I use cookies for this ?
Yes, see this tutorial on using cookies in Javascript.
Are there other posibilities?
If you are not allowed to append anything the URL of your requests, I can't come up with any.
Where cookies are stored when Request is made ?
In the HTTP request header. The aforementioned tutorial will tell you how to read their values from Javascript. On the server side with ASP.Net, you can read cookie values using Request.Cookie["cookieName"] which returns an instance of HttpCookie.
I wouldn't highly recommend this, but the other option is to alter the window.name property.
You can save some minor bits of data here, then retrieve them on the next page load.
Pros:
Quick-n-dirty, but works
Cons:
Messes up any window references for popups/child iframes
Since its a "hack", browser vendors may break this "feature" in the future
Of course if you can exclude all the old browsers, then use Global/Client Session Storage!
At the moment using cookies is your best bet. You can serialize the JavaScript objects to strings, and unserialize them back into objects later. A good choice format is JSON, since it is a subset of JavaScript.
There is also storing objects in Flash.
Storing in Google Gears.
DomStorage
See this library that has an interface to each:
http://pablotron.org/?cid=1557
If you are in control of all aspects of the page, then you can also wrap the page in a top level frame. Then only refresh the child frame. You can then store content in the parent frame.
You can see this used in sites like GMail, and others where the only thing that changes in the URL is outside the #.
You don't even have to change the URL, that part is just put in for Human Friendly URLs. (So you can actually copy and paste URLs as is).

Categories