so i need a cookie set for 21 days on a browser when a user hits the site and everytime the user returns in that 21 day period i need to retrieve that value
if($_REQUEST['ref'] == "something"){
setcookie('something_value', "something" ,time()+60*60*24*21,'/','mydomain.com');
}
in the view
<?php if(isset($_COOKIE['something'])) { ?>
but when i view the cookies in safari and firefox i dont see "something"
am I missing something
Looks like you've swapped the first two parameters of setcookie. The first parameter should be the name of the cookie.
// prefix the mydomain.com with a . (makes it work on more browsers)
setcookie('something_value', "something" ,time()+60*60*24*21,'/','.mydomain.com');
I've also had that problem and putting a . in front of the domain name made wonders for me.
Do not view cookies in safari and firefox. Cookie is an HTTP header and nothing else. Do not rely on inner browser's mechanism. But rely on HTTP log only. Do you see your cookie in HTTP log?
what is it's name? "something_value"? Don't you mess something? ;)
Related
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')
?>
Basic situation and basic relevant info:
I have a php code that executes before the opening <doctype> tag. The hope was to (if necessary) send a redirect based on user's browser's language preferences before anything else loads.
The script attempts to do two things based on highest supported language preference:
Use php: setcookie() to create a cookie with the two-letter language code.
Example cookie name = value: x_language = es
Use php: header("Location: " . $requestedSite); to redirect to a subdomain,
Example domain: es.domain.com
Example:
if (isset($_COOKIE['x_language'])) {
-Determine correct subdomain based on cookie value-
-If not currently on that subdomain, redirect to it-
} else {
setcookie('x_language','es',time() + 31536000 ,'/','.domain.com' );
header("Location: " . $requestedSite);
}
The problem:
Firefox works perfectly. Chrome (and other browsers) fail to recognize the cookies at all.
I've boiled it down to this:
print_r($_COOKIE) works properly in Firefox, and returns a lovely, populated array.
print_r($_COOKIE) fails in Chrome, and returns an empty array.
This is the core of the problem, my function doesn't recognize the existence of a cookie because Chrome doesn't.
I've made sure every browser accepts cookies.
I've checked dev tools to make sure the cookie is in place on all browsers, (it is).
I realize a cookie's value isn't available until the next page load, but that isn't an issue here. Even after it is set, it won't read.
There is no output above the initial setcookie();
So how do I get Chrome (and other browsers) to recognize its own cookies?! Does anyone know why this would all work flawlessly on Firefox but fail elsewhere?
On a lark I decided to try this. I created a file that only contains:
<?php
print_r($_COOKIE);
?>
Again, I see the cookie array in Firefox. Meanwhile, in Chrome, IE, Opera, Safari, I get an empty array. Could this be a server issue?
OP returns with answer:
Alright, I'm adding this as an 'Answer' in case anyone else comes across this (totally bizarre) behavior and lands here:
It turns out my hosting provider was doing some seriously aggressive caching with my WordPress site that I was unaware of.
At the time I posted my question, I didn't think being on WordPress was relevant, but apparently it was.
Basically it was doing this:
With a clean Cache:
Visitor 1 visits the site.
The php processes and produces output as expected.
Visitor 1 is served php output (based on his browser's parameters and such).
Visitor 2 visits the site. Visitor 2 sees *Visitor 1's version of the site.
The php is processed once and only once per Cache-clear.
This caching behavior meant that accessing cookies through php was simply not going to work right, but accessing them with Javascript WOULD work.
(Important note: It turns out the above-stated caching behavior is disabled for any user viewing the site while logged into wordpress, and this is common behavior for WordPress Cache plugins. That is why I was seeing different behavior in Firefox than I saw in other browsers, because I was actively logged in with Firefox. This could be a helpful piece of information for someone out there.)
My solution:
Use Javascript to run an AJAX query to a .php file which would process the language preferences of the visitor and return the output as a 2-character code, (i.e. 'en' 'es' 'pt' 'de', etc).
Using AJAX to call php allowed me to use php's server-side access to a browser's language preferences while circumventing the super-agro caching of my host.
I hope this helps someone! And thanks to everyone who tried to help me out with this.
I was not having this problem with the code below. I was able to go to example.com and be redirected immediately to en.example.com and see the cookie in $_COOKIES. If I used en.example.com?set=fr I would be redirected to fr.example.com every time I tried example.com. Hopes this is what you were looking for!
<?php
print_r($_COOKIE);
if(isset($_GET['nuke'])) {
setcookie('x_language','',time()-1000,'/','.example.com');
echo 'It has been nuked!';
exit;
} else if(isset($_GET['set'])) {
setcookie('x_language',$_GET['set'],time() + 31536000, '/','.example.com');
$_COOKIE['x_language'] = $_GET['set'];
}
if (isset($_COOKIE['x_language'])) {
$redirect = $_COOKIE['x_language'].'.example.com';
if($_SERVER['HTTP_HOST'] != $redirect)
header('Location: http://'.$redirect);
} else {
setcookie('x_language','en',time() + 31536000,'/','.example.com');
$redirect = 'http://en.example.com';
header('Location: '.$redirect);
}
echo '<br />Cookie: '.$_COOKIE['x_language'].' Domain: '.$_SERVER["HTTP_HOST"];
?>
Im not sure where im going wrong. I have a form that when the contents of the form get processed and sent to the database it also sets a cookie
setcookie("bgremkey",$checkkey, time()+2592000);
then it will redirect the user back to the page they came from. All of this works fine (bar the cookie bit)
then i have it set at the top of every page providing there isnt an session active to check to see if the cookie exists and if it does to redirect but it wont work. im sure that the cookie is there but it wont pick it up
<?php
if(isset($_COOKIE['bgremkey']))
{
header("location:'Check.php?cklog=1");
}
?>
<script type="text/javascript" language="JavaScript">
var acookie = ReadCookie("bgremkey");
if(acookie.length != 0)
{
window.location = " Check.php?cklog=1";
}
this code doesnt generate any errors but it also doesnt do anything. i have tried putting it in the of the page but that didnt work so i then tried the body and that didnt work either
the check page does a bunch of other stuff but thats not the problem since the redirect never happens
i checked the cookies through chrome and the cookie exists and its path is / so the problem is definitely with reading them. it exists but for some reason cant be detected
http://php.net/manual/en/function.setcookie.php
setcookie("cookiename","cookievalue", $time); will only set it for the current path
Whereas: setcookie("cookiename","cookievalue", $time,"/"); will set the cookie for all pages/folders on that domain (note the 4th argument containing the path ).
If you press CTRL+SHIFT+J in google chrome, and click on the Resources tab, you can find the cookies and the path it is valid in. I'd check that out. perhaps this is why?
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')
?>
I've got to be missing something simple, but this is driving me batty.
I'm setting a whole bunch of array cookies, like so:
setcookie("adjusted[$title]", $title, time() + 3600, "/", ".domain.com");
This works just fine, the cookies are being set and I can see them in the browser's cookie list.
However, I can't seem to read only certain values back out! I have no idea why. For example, I set this cookie:
adjusted[calldelivernow.net]
and I can see that is its name in Firefox's cookies page, the content is "calldelivernow.net". But all attempts to do this return false:
if(isset($_COOKIE["adjusted"]["calldelivernow.net"]))
die("Cookie is set");
This is just one example of many, all under identical parameters just with different domain names. What on earth am I missing here? How can a cookie plainly exist in the browser, yet PHP not be able to read it?
Because you're not calling it by it's name correctly. Unlike form names, cookies do not get stacked to arrays.
Try $_COOKIE["adjusted[calldelivernow.net]"].
The problem appears to be that cookie names, cannot contain periods! Strangely, Firefox is in fact showing that the cookie name is correct and contains the period, but the $_COOKIE array replaces the period with an underscore, like so: ["calldelivernow_net"]=> string(4) "test"