Hello, I'm stuck on something with a cookie and must be missing something obvious, but I can't see what.
In my script I want to load a page and
1 - Check if a cookie exists
2- If it does not launch a JavaScript function called myFunction and set a cookie
Now, the first time I launch the page the function shows (as there is no cookie in my browser) which is great but on subsequent loads when I refresh the page it should not show as a cookie should be created
as it happens the code works for me on firefox, but any issues are possibly down to the fact that setcookie expects a string value as the value, not a boolean (true/false) so if you used !== then you check might fail
MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)
That looks like you can never set a cookie. Since you don't check the existence of the cookie before reading from it, and you have output before the setcookie header, it will result in no cookie ever being set.
This is probably what you want:
MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)
Thanks. However the JavaScript function I call is still showing all the time and not one time only. It seems the cookie is never created.
My JavaScript is simply a "hello" alert, which I have placed in a function called myFunction().. I've even tried it on a different server and I still have the same problem.
Make sure you haven't sent any output prior to this point or you will toss a headers already sent error. You can even verify prior by simply checking the headers_sent function. Verify the cookie path and domain are valid too. If you are on a subdomain, you'll need to modify the domain, but this particular example shouldn't cause any issues when it comes to the cookie path.
As mentioned by firepages the cookie value is a string so should be set and compared as "true", not true (a boolean).
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS