Cookie value empty in ajax php script - php

when i make a jQuery AJAX request the cookie is being shown as empty. I tried setting a session instead and that works however i want this to be a cookie not a session. It is not cross domain and it is only storing a simple 1 character number. i want to retrieve the number, do something, then update the number. Sure i can use a session but i want this to be a cookie.
setcookie("currentResult", "", time()+60*60*24*30*12, "/", "*(mysite)**.com", 0,1);
then i add a value to it later in my script like this
$_COOKIE["currentResult"] = $ii;
Then when i call an AJAX php script like this;
jQuery.ajax({
type: "POST",
url: "****(myscriptname.php)****",
dataType: "html",
data: "start=" +start,
success: function(data)
{
dataq = jQuery.trim(data);
} });
But alas the cookie is empty in that script.
I am echoing it out on the page im on and its set fine and works no problem.
I tested doing the exact same with a session and the session is there in the AJAX script. I only seem to be having a problem with cookies.
It is any cookie i try to use in a ajax request.
I can only find other people talking about cross domain problems but this isnt cross domain... im confused!
Please Help!

Take a look at the 7th parameter...
1 = don't let javascript see this cookie
httponly
When TRUE the cookie will be made accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. It has been suggested that this setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers), but that claim is often disputed. Added in PHP 5.2.0. TRUE or FALSE

The below was the solution! thanks Brad!!!
changed to;
setcookie("currentResult", "", time()+60*60*24*30*12, "/", "*(mysite)**.com", 0,0); and its fixed!
Take a look at the 7th parameter... 1 = don't let javascript see this cookie
httponly
When TRUE the cookie will be made accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. It has been suggested that this setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers), but that claim is often disputed. Added in PHP 5.2.0. TRUE or FALSE

Related

Laravel Cookie Not Showing Up Via Javascript

I'm newbie learning laravel and have the following in my route file::
Route::get("/setcookie", function(){
$cookie = Cookie::make("low-carb","almond cookie",30);
return Redirect::to("getcookie")->withCookie($cookie);
});
Route::get("/getcookie", function(){
$cookie = Cookie::get("low-carb");
return View::make("getcookie")->withCookie($cookie);
});
I set a cookie and redirect to a different page. I want to be able to show the cookie via javascript dialog box in a view page. The "getcookie" view page looks like::
<html>
<body>
this is the cookie page
<script language="javascript">
window.onload = showCookies;
function showCookies(){
alert("Cookie is: " + document.cookie);
}
</script>
</body>
</html>
The only thing i see on the popup dialog box is "Cookie is". The value am expecting doesn't show up.
I know definitely that am doing something wrong because when i check the cookies in the chrome developer tools, i see for the "setcookie" route, the keys REQUEST COOKIE and RESPONSE_COOKIE (laravel_session and low-carb) both have values but for the "getcookie" route where it is redirected to, the REQUEST COOKIE key in chrome has both "laravel_session and low-carb" but the RESPONSE_COOKIE key only has the "laravel_session" and the "low-carb" key-value is missing.
What am i doing wrong?
By default Laravel cookies are marked as httponly - this means that they they can't be accessed via JS. This is often what you want, hence it being the default.
If you look at the source here: https://github.com/laravel/framework/blob/master/src/Illuminate/Cookie/CookieJar.php#L41, you'll see that the method signature looks like:
public function make($name, $value, $minutes = 0, $path = null, $domain = null, $secure = false, $httpOnly = true)
where the last variable passed in is the httpOnly variable.
So, if you change from:
Cookie::make("low-carb","almond cookie",30);
to
Cookie::make("low-carb","almond cookie",30, null, null, false, false);
Then your cookie will not be marked as httponly, and will be accessible via JS.
You can check if a cookie httponly or not by using your browsers dev tools, in Chrome's Dev Tools go to Resources, then to Cookies, then to oyur domain, and there is a column in that table called HTTP - it has a Tick if that cookies is HTTPonly.
Edit: All cookies are encrypted and signed in Laravel, so that users can't tamper with them. Not 100% on this personally - $_SESSION is for persistent data that the user can't edit, $_COOKIE is for data that you want the user to be able to read and edit. Anyway, just use PHP's native:
setcookie("low-carb", "almond cookie", time()+(30*60));
instead of the laravel method if you want to do this.
You might also want to think whether there is a "better" way to deal with this - perhaps you don't need Cookies for this anyway (remember they are sent with every request that matches the cookie's path, CSS, JS, images, fonts - everything)

this.checked creating false positive?

I have a page that has 4 checkboxes that are checked by default. If you uncheck a box, it writes a cookie so that return trips to the page will have saved preferences. The problem I'm having is that the cookies seem to be written no matter what. Going to the page for the first time should create no cookies, but unchecking a box should throw the following code. As it stands, the first time I'm going to my site, the cookies are created.
Where have I gone wrong (I wouldn't be surprised if it is in multiple places).
$('#mycheckbox').change(function() {
if (! this.checked) {
<?php setcookie('key', 'Value', time() + 4800); ?>
}
});
No, this.checked works.
The problem is that the PHP code will always be run, since it's run on the server-side and not interpreted by the browser. All PHP code is executed before the browser even gets the files.
A solution would be to put that PHP in an external file and use jQuery $.ajax to request that file, which would run the code only when desired.
You could also check out the jQuery $.cookie plugin.
As #MarkB already said you are mixing up javascript and php. In this case you should set your cookie with javascript in stead of php. See this post to find out more.
The code as you have it now will always set the cookie, as you already noticed, because the server ignores the javascript code and just runs the php code to set the cookie.

Setcookie won't work?

I set the cookies regularly in a callback page in my Twitter application. Everything works fine.
Now, using jQuery, I submit a form, and the callback function activates a PHP script. That script only needs to set one cookie to the serialized values of $_POST; and the values run fine (both serialized and normal, I echoed them out to debug). The expiration time is set to 1 year ahead. But for some reason, the cookie just won't appear anywhere. Here's the code:
// js/main.js
$('#settings-form').live('submit', function() {
$.post('controllers/settings.php', $(this).serialize(), function(data) { // Everything here works.
if (data == 'OK') // no errors spits out "OK". this works
changeView({'msg': 'Your settings were saved successfully.'}); // This just resets the view and adds a message div at the top. This works
else
changeView({'msg': data}); // This echoes the error if any exists. Doesn't happen, no errors arise
});
return false; // Cancels redirecting after submitting form
});
// controllers/settings.php
setcookie('user_settings', serialize($_POST), strtotime('+1 year'));
I checked all the variables and I even tried setting dummy ones for test (like "boo" instead of serialize($_POST). for some reason that doesn't work.
Any ideas why this is happening? I tried doing a chdir('..'); to make the cookie dir go to the right place, but that doesn't seem to be the problem, checking the cookies inside my browser doesn't seem to work at all, for any path. It just doesn't work at all. I also just tried manually changing the domain and path, but those don't work either.
Firstly, the chdir() thing is a red-herring -- Cookies are domain-specific; the directory path doesn't have any bearing on them.
Cookies can work a bit strangely when you're making ajax type calls, and I think this is what you're seeing -- The server is probably setting the cookie, but the browser may not be setting it in the cookies data it as it's not a page load.
I would suggest you'd be better off using PHP's session handling rather than cookies; it's better for security, less bandwidth (because the whole of the cookie data is transmitted in both directions with every http single request), and more likely to work.
If you really want to use cookies, it may work better if you use Javascript to do it. You can set cookies in your javascript code by accessing document.cookie. (you need to get the syntax right for the cookie string, but JQuery probably has its own functions that makes them easier to work with)

How to detect cookie and javascript with browsers

I am using PHP/JavaScript/MySQL on XAMPP to develop the prototype.
I need to use session that in-turn makes use of cookies. Here is the question,
how do I know whether or not the user's browser supports cookies or not.
For detecting javascript, I use <noscript></noscript>. Please correct me if I am wrong.
Thank you
You have to set a cookie and test it to see if they're enabled:
<script type = "text/javascript" language = "JavaScript">
var tmpcookie = new Date();
chkcookie = (tmpcookie.getTime() + '');
document.cookie = "chkcookie=" + chkcookie + "; path=/";
if (document.cookie.indexOf(chkcookie,0) < 0) {
window.location = 'nocookies.html';
}
else {
window.location = 'cookies.html';
}
</script>
Here is the question, how do I know whether or not
the user's browser supports cookies or not.
If a cookie isn't set, set a cookie and redirect to a page that checks if the cookie is set. If it is, redirect back, otherwise redirect to a "Sorry, we really need cookies" page.
Only do this if you do really need cookies.
For detecting javascript, I use <noscript></noscript>. Please correct me if I am wrong.
Better to build on things that work.
I will choose different style of detecting.
To detect whether javascript is enabled/disabled, i will write some little elements (perhaps div) and i will execute some javascript to remove such elements. Hence, when the javascript is disabled/doesn't exist, those elements will still be there saying that "Please activate your Javascript". On the other hand, those element(s) will be gone since javascript is already remove them. After all, it comes back to your website concept. Some website can't do anything when javascript is not exist/disabled and further they choose to redirect the request into another page (through tag). Some websites still can function but certain feature will not be available, and this concept leads to "warning" technique.
To detect whether cookie is enabled/disabled, just set a cookie using Javascript. In next request, you can check whether such cookie is set or not. If it's set, then both Javascript and Cookie is enabled. If it's not set, then Javascript or Cookie or both is disabled.
Good luck

Question on PHP cookies

I came across the snippet below:
setcookie('foo', 'v1', time() + 60*60*24, '/');
setcookie('foo', 'v2');
What is the effect of setting 2
cookies with same name but different
values?
Is it common in practice?
Where is it used?
The above example will simply overwrite the first cookie with the second one. If you want to update a cookie to store a newer value, you can overwrite its value.
Two cookies may have the same name if they were set for different domains or paths. example :
<?php
setcookie("testcookie", "value1forhost", time(), "/", ".domain.com", 0, true);
setcookie("testcookie", "value2forsubdom", time(), "/", "subdom.domain.com", 0, true);
?>
The v1 vs v2 part makes it look like a trick to detect a cookie handling bug in the browser: if foo equals v1, the browser did not process the value change.
It'd be interesting to know about the code context.
Edit
Will it set 2 cookies or will it
overwrite
It depends on where you call the script from. A setcookie() call without a path sets a cookie for current path (where path is an URL path, not the internal file system path). So a call from http://example.com/ would create a single cookie and a call from http://example.com/somewhere/inside/ would crate two separate cookies, one for / and one for /somewhere/inside/.
I think this is not intended. The second cookie call will overwrite the original set cookie. After the first call there is no knowing if browser support is available, as no input from the browser is received when processing a script. A cookie is sent as a HTTP header, and sent back by the browser on consecutive requests.

Categories