Set cookie in PHP from a getJSON call on two different servers - php

I have two servers, 'www.domain.local' and 'api.domain.local'. I want to set a cookie in a script on the api server that is called from the www. Chrome does not let me do that (didn't try other browsers yet)
my PHP code:
header("Access-Control-Allow-Origin:*");
echo json_encode(array("cookie"=>print_r($_COOKIE,true)));
setcookie("test","ok",time()+24000*3600,"/",".domain.local");
in my jQuery:
$.getJSON("http://api.domain.local/test.php",{
command:"setcookie"
},function(fb){
alert(fb.cookie);
});
The PHP is first returning the cookies it has, the first run this should be zero, and it is. In the header of the PHP script I see the following:
Set-Cookie:test=ok; expires=Tue, 27-Oct-2015 22:52:52 GMT; path=/; domain=.domain.local X-Powered-By:PHP/5.3.14
Which is what I expect. But the cookie isn't set. When I run the jQuery again I am expecting the cookie to be set (get an alert with the print_r of $_COOKIE), but I get nothing. One thing I noticed in the 'cookies' tab of the network resources in the debug part of Chrome is that the expiry was set as "Invalid Date". If I run the PHP script directly I don't have this problem though.
Is it possible to set a cookie in a PHP script called from jQuery and if so, how?

Let's see, set a cookie on a different domain to the one that the page is loading on and in PHP from jQuery
Someone might post how you're supposed to do it.
I might just cheat.
www.domain.local/test.html includes
$.getScript("http://api.domain.local/test.php?dowhat=setcookie");
api.domain.local/test.php is
<?php
switch ($_GET['dowhat']){
case 'showcookie':
print_r($_COOKIE);
break;
case 'setcookie':
setcookie("test",date('Y m D H:i:s'),time()+24000*3600,"/");
break;
}
header("Content-type: application/javascript"); // may as well, it expects this
die;
Now go to http://api.domain.local/test.php?dowhat=showcookie
Array ([test] => 2013 01 Thu 00:20:52 )
Ta-da!
P.S. I wouldn't advise doing it this simply if you need it to be set without someone naughty being able to cheat too.

There seems to be a problem with your code. On the first line you forgot to close your string with ".

Related

why is my cookie not set , is it my localhost? [duplicate]

I have a cookie that will not set on the remote server, works find locally. No error messages, var_dump gets me Null, echo is blank.
<php
setcookie('ymp','14', time()+3600);
session_start();
?>
I can set a javascript cookie fine. The opening tag is line 1 of the page.
Any ideas
Thanks
Gary
On Edit
I have some comments I posted below, it is a 3 file process.
Page one is to set the cookie, as above.
Page two I have for debugging
<php var_dump($_COOKIE['ymp']); echo'<br />'.$_COOKIE['ymp'];?>
Page 3, and again this all worked locally I have
<?php
if($_COOKIE['ymp']!=='14')
{die('Sorry, you have not had your delightful little pastry yet.... try again.');}
?>
I set a js cookie, and changed the code to reflect the different cookie name and it worked fine.
I also reset the time to +86400, because of the two hour time difference to the server, though I don't think that is really required.
Thanks for all the help
Gary
You can't read the value of a cookie until a new page request is made. This is because the value of cookie data is sent with the page request. So it isn't available for to access its value until after it is set and a new page request is made.
Also, session_start() has no effect on cookies. They are two different things. (Sessions do typically use cookies to store the session ID but that is irrelevant).
This is rather peculiar - I assume this could have something to do with PHP configuration.
See what the return value of setcookie function is - it may be FALSE if output has been already sent before the function call. You did mention it is right at the start of your script, however there could be other entities outputting data (pre-executed scripts on the server perhaps?)
It's also possible that your browser is set to not accept cookies from certain domain - check your configuration.
Please provide any other relevant code and indicate how you check if cookies are set.
This problem never did solve, I ended up writing a new file to a different domain on the same host, gave the cookie a different name and value (is it possible that a 3 character name cookie with a 2 digit value too small??) and it worked as supposed expected.
Thank you all for your help... too busy to do a CSI investigation as to the how's and whys.
Gary
It could be because you don't specify a path and/or a domain for the cookie. Try this instead:
<?php
setcookie('ymp','14', time()+3600, '/', 'yourdomain.com')
?>

Redirect randomly failing in IE 8 and older

On our adserver, we use the following simple PHP script to redirect to the landing page of the ad:
<?php
$lp=array_key_exists('lp',$_REQUEST)?trim($_REQUEST['lp']):"";
$location = sprintf('Location: %s', $lp ) ;
header( $location ) ;
?>
The script takes its lp parameter and redirects to that URL. The purpose is so that we can scan our access log to track clickthroughs (the URL also includes an id parameter, which the script ignores).
We have one customer (that I know of so far) where this isn't working consistently, but only in IE 8 and older. The URL with the problem is:
http://webutil.bridgebase.com/v2/ad_lp.php?id=340&lp=http%3A%2F%2Ftravelinsingles.com%2Fhome.htm
This should redirect to http://travelinsingles.com/home.htm, but sometimes it goes to http://webutil.bridgebase.com/home.htm (which doesn't exist). It always seems to happen on the first click on the ad; sometimes subsequent clicks follow the redirect correctly, sometimes they continue to go to the bad URL.
I performed a packet capture on our webserver, it looks like we're sending the correct header:
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.2.1
Date: Thu, 06 Jun 2013 01:39:12 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: close
X-Powered-By: PHP/5.4.15-1
Location: http://travelinsingles.com/home.htm
I captured both on a failing and successful redirect, and the headers were identical except for the Date.
I'm using a Mac, so I use BrowserStack to test IE, which limits my debugging ability at the client end. Does anyone know what could be causing this, and if there's something we can do to work around it?
I reproduced the problem with BrowserStack's screenshots feature:
http://www.browserstack.com/screenshots/3659c3b992a1738594d2fd370caef2852fecb3fa
Does adding exit or die(); to the end of your PHP make a difference?
Sometimes HTTP clients don't like it when a redirect header is sent while content still exists in the body (even if it's empty content: spaces, line returns, etc.)
What happens if you use rawurldecode($lp)? I've tested in Windows 7 in IE7-10 and it works fine for me (both ways). Strange!
Check the URL you're being redirected to in IE, what's the address bar say?
To prevent problems with header redirects I usually use ob_start(); and ob_flush();
<?php
ob_start(); //at the top of the page//
header( $location ) ;
ob_flush();
?>
Maybe you have output buffering on the server. Output buffering can get the header out because of the buffer (as you know, the headers should be sent first).
Hope it could be the problem

Set cookie after output without ob_start

I'm guessing not, but is there a way to set a cookie in PHP without having to put ob_start() at the start of the output?
My problem is, that I am developing a class, which among others, needs to set a cookie. Now I can't tell the person who uses it "you have to make a new instance of the class before you make any output", cause that would be lame. So can I somehow pull it off?
See Headers already sent by PHP
The unprofessional workarounds listed there apply. Specifically:
<META HTTP-EQUIV="Set-Cookie"
CONTENT="cookievalue=xy;expires=Friday, 14-Dec-12 12:12:12 GMT; path=/">
Or use javascript and set document.cookie.
You cannot. Cookies are sent as part of the header, so if you've already sent the body, it's too late. Output buffering is the solution.
Perhaps you could use session variables instead.
This is my workround and is working fine for me.
// Force set cookie now
$_COOKIE['ref_url'] = $_SERVER['HTTP_REFERER'];
// Set cookie after refresh site
setcookie('ref_url', $_SERVER['HTTP_REFERER'], Affiliate::$cookieTime);
// Diplay $_COOKIE
var_dump($_COOKIE['ref_url']);

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)

what could some of the reason be to why a cookie wont be destroyed?

i have a cookie named MVCID that's set and its value is some generated hash.
when i write this
setcookie("MVCID","", time()-60*60*24);
and load the page, not only is the contents of the cookie not being erased but it also isn't dying.
what can be the possible problem? this isnt the first time this is happening.
ps: im also trying this on an empty page with no other code but this and it still wont die.
Try passing "/" as the fourth parameter -- path.
Are you calling this function before outputting any HTML? That's a known foible of the call since cookies have to appear in the HTTP header.
You might want to also check the time on the client side. Even though you're setting to expire one day ago, it's possible that the clock skew might be greater (if times aren't set correctly).
And I prefer to populate all parameters rather than relying on defaults (which can change based on many things).
In addition, you may want to check the return code although I have no idea how it could fail, something like:
<?php
$ret = setcookie("MVCID","", time()-60*60*24);
?>
<html>
<head></head>
<body>
Hello<br>
<pre>
<?php
print_r ($ret);
?>
</pre>
</body>
</html>
Failing that, you may need to have a look at what's going on at the wire level. In other words, examine the HTTP response to ensure there's a Set-Cookie in the HTTP headers and examine the actual values being passed along with it.
And one last trick to try: delete the cookie totally and exit from the browser (some of them cache in memory). Then try again. If the PHP setcookie is not working then no cookie will be created - the one you have that's not being changed or expired may be left over from a previous successful variant of your code.
Use something like firebug or fiddler to examine the actual response headers (both, the one containing the "real" cookie and the one containing the "delete" cookie)

Categories