Test for cookies in PHP - php

What is the best way to tell if someone has cookies enabled in their browser. I tried:
<?php
setcookie('cookies','yes',time()+7200);
if (!isset($_COOKIE['cookies'])) {
echo '<div class="error" style="float:right;">You must enable cookies and Javascript to use this site.</div>';
} else {
echo '';
}
?>
but sometimes it displays the alert even if cookies are enabled. I only want an alert if cookies are NOT enabled.

The reason that your code doesn't work is because cookies are sent with the request. The code you're trying will work, but setcookie has to be in a different request than the isset call. Try calling a redirect in between calling those 2 functions.

It is because your cookies are set at the same time as your request is sent to the browser.
It means that even if setcookie() is executed before the script ends the cookies are set after the browser received the request.
To do in a such way, you would need to redirect to a page with a trivial argument and then check for cookies.
A more flexible solution would be to check in javascript.

Related

Does the browser set the cookies when there's a redirection?

I think I'm making an awkward mistake here but I really fail to find it. I've used browser developer tools and watched each step closely. This is the code and I want the number of visits to get reset after the Restart link is pressed, but it just keeps incrementing:
//test.php:
<?php
if(isset($_COOKIE['visits']) && isset($_GET['restart'])){
if($_GET['restart']=='true') {
setcookie('visits',null,time()-24*3600*365,'/');
unset($_COOKIE['visits']);
header("Location: test.php");
exit;
}
}
if(!isset($_COOKIE['visits'])){
$visits = 1;
setcookie('visits',$visits,time()+24*3600*365);
echo "Welcome To This Website";
}
else{
$visits = $_COOKIE['visits']+1;
setcookie('visits',$visits,time()+24*3600*365);
echo "You've visited this website ".$_COOKIE['visits']. ' times before.<br>';
echo "<a href='?restart=true'>Restart</a><br>";
}
The final guess I've come up with right now is that when using a redirect header, the browser does the redirection request before setting the received cookies, I'm not sure though. Otherwise, I can't think of anything else that may cause this behavior. Anyone could please comment on this and make it clear?
In your code it looks like the header is sent and the user is redirected before the cookie is set. You could try output buffering and echo a dot echo "."; directly before the header(... line to ensure some communication with the client before they are redirected.
Edit: My understanding of what is happening here is that the cookie and redirect headers are being sent simultaneously, but in some server/client combinations the redirect is occurring before the browser has a chance to set the cookie. Pushing some content to the browser along with the headers gives it a chance to process the cookie, but you must obviously enable output buffering in your php.ini or use ob_start() and ob_end_flush() before and after the header setting and echoing.

PHP detect if session cookies are disabled

I know that with sessions in php, a cookie that stores the session ID is set on the client's side. The client can turn off these cookies, which I presumes makes sessions not work. How can I detect if the client has disabled the session cookies?
You can use javascript navigator.cookieEnabled. This returns true or false.
So
if(navigator.cookieEnabled)
//do something
else
//do something else
assuming you started a session on a previous page...
<?php
if(session_status() == PHP_SESSION_ACTIVE)
{
echo 'cookies & sessions enabled';
}
else
{
echo 'no cookies or sessions';
}
?>
or you're looking for a non-session cookies as well.
<?php
if(!empty($_COOKIE))
{
echo 'cookies are tasty';
}
else
{
echo 'no cookies to eat';
}
?>
with a pure php solution you can't check if sessions/cookies are enabled without setting a cookie on a previous page
If you know you MUST use a session, the usual approach is to redirect the user instantly at the start while trying to set a cookie, and then complain about the cookie not being set on the second page.
User goes to http://www.example.com
System sets a cookie (maybe only starts the session, maybe a dedicated test cookie).
System redirects to http://www.example.com/?cookietest=true
On that page, if the cookie is not sent back, complain to the user.
On the other hand, most of the time a session really is not needed if you do not have to log someone in. And IF you do, most users will understand they need to allow cookies, because otherwise the login will fail.

PHP Cookies are not being set

I'm having issues with setting up cookies. The problem is that my cookies aren't even being set, I have setup a test below to see if they are being set but they are never being set. I've even checked in my browser to see if anything is being set, but nothing from my site.
I would like you to help me make my cookies set. I'm not quite sure what to do. Thank you.
Here is my code:
<?php
session_start();
setcookie("ridArray","", time()+3600);
if (isset($_COOKIE['ridArray'])) {
echo "ridArray is set.";
}
?>
<head>
</head>
<html>
<body>
<?php
if (isset($_COOKIE['ridArray'])) {
echo "ridArray is set.";
} else { echo "not set"; }
?>
</body>
</html>
Here's the problem, from the SetCookie documentation:
Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string, or FALSE, and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client. This is internally achieved by setting value to 'deleted' and expiration time to one year in past.
You are setting the cookie value to empty string (""). Try:
setcookie("ridArray","not blank value", time()+3600);
The other issue is that when you set a cookie, it will not be in the request headers (accessed via $_COOKIE) until the next page load. This means when you load that page the first time, $_COOKIE['ridArray'] will NOT be set. On subsequent loads, it will be set, and it will be reset every time.
First page load, it won't be set. Refresh, and it will be set.
The easiest way to debug cookies is to use something like Chrome's developer tools or Firefox's FireBug and watch the response headers for the SetCookie header, and the request headers to see what cookies your browser is sending.

Cookies cannot be set the first time after clearing history in Firefox

I am trying to setup a session management with cookies in PHP.
My code is as follows:
if(empty($_COOKIE )) {
setcookie('session_id', md5(uniqid()), time()+(EXPIRE CONSTANT));
}
$session_id = isset($_COOKIE['session_id']) ? $_COOKIE['session_id'] : 0;
I will then check session_id for 0 and print an error message if cookies are disabled.
This works fine if cookies are really disabled.
The problem is, if a user clears his history the first time he visits
the site he will get the error message even if cookies are enabled.
Anyone have any clues about this ?
Thank you in advance
When you do the setcookie call, the cookies will be sent when the header is output to the browser. This means the cookie won't be available until the next page load (when the client sends the cookie back to the server). This is mentioned in the php manual for setcookie http://php.net/manual/en/function.setcookie.php:
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.
You won't be able to determine if cookies are enabled/disabled until the page has reloaded (from php). I think you'll have to do this check with javascript, or to stay in php do a redirect after setting the cookie for the first time, something like:
if(empty($_COOKIE)) {
if (isset($_GET['cookieset'])) {
// do error message, cookie should be set
}
setcookie('session_id', md5(uniqid()), time()+(EXPIRE CONSTANT));
header('location: http://mysite.com/index.php?cookieset=1');
exit;
}
$session_id = isset($_COOKIE['session_id']) ? $_COOKIE['session_id'] : 0;
#bencoder : I have done the test on iPad and Chrome/PC : you are right for iPad, you do need to refresh the page before you can read the cookie data, but on Chrome/PC, after deleting all cookies, if you set a new one from PHP, you can perfectly get the values directly on the first page load. Why ? There must be a more precise explanation. Why two different behaviors? Does the order of this output/availability of the data depend on the browser request to the server? Interesting to know...

Are Javascript/Cookies enabled or disabled?

I am looking for some code that will return me values if the user has JavaScript enabled or disabled, as well as cookies.
I know this is probably easy to do, but my time constraints are so tight, it hurts. There has to be something out there using php that does this. Ideally I would love to find code that has a page setup with all the possible values that could affect my scripts.
EDIT: Obviously JavaScript may be disabled, but, I am hoping that I can find something out there to test the two cases.
My Solution
For anoyone else looking for code to detect if the users has cookie enabled or disabled, here is what I ended up coming up with from the posts below... you can just drop this at teh top of any page and it works...
<?php
// do a cookie test
if (!isset($_SESSION['cookie_check']))
{
if (!isset($_GET['cc']))
{
// drop a cookie in their bag
setcookie("cookiecheck", "ok", time()+3600);
header("Location: ".$common->selfURL()."?cc=1");
exit(0);
}
else
{
// do we have a problem?
if (#$_COOKIE['cookiecheck'] != "ok")
{
// we have a problem
header("Location: /site-diag.php");
exit(0);
}
else
{
$_SESSION['cookie_check'] = true;
}
}
}
?>
You could use the jQuery cookie plugin to write a cookie and then see if you can read it back again. That would tell you if cookies were enabled in the client's browser or not.
For checking Javascript, either they have it or they don't. If not, you can use <noscript> tags to display a message asking them to turn it on, put a meta redirect inside, etc. That is the extent of your testing ability.
As for cookies, just try setting a cookie then reading it back! Since you're concerned about Javascript's ability to handle cookies, I assume you already have a cookie library that you are using, meaning that you can just use the set function for a test cookie then the get function to read it back. If the test cookie can't be read back, cookies are off.
Here is one for checking cookies
http://techpatterns.com/downloads/javascript_check_cookies.php
if javascript is disabled then you can't use jquery or prototype.
write a function that writes a cookie, then tries to read it.
and secondly puts out some js code to the screen that makes a ajax call to a basic php script.
you can use a database to set the boolean results of both tests on the visitor table if there is one.
This is the way I check if cookies and JavaScript are enabled:
if($_SESSION['JSexe']) { // 3rd check js
if($_COOKIE['JS']) {
setcookie('JS','JS',time()-1); // check on every page load
}
else {
header('Location: js.html');
}
}
// 2nd so far it's been server-side scripting. Client-side scripting must be executed once to set second cookie.
// Without JSexe, user with cookies and js enabled would be sent to js.html the first page load.
elseif($_COOKIE['PHP']) {
$_SESSION['JSexe'] = true;
}
else { //1st check cookies
if($_GET['cookie']) {
header('Location: cookies.html');
}
else{
setcookie('PHP','PHP');
header('Location: '.$_SERVER['REQUEST_URI'].'?cookie=1');
}
}
Explained in detail here: http://asdlog.com/Check_if_cookies_and_javascript_are_enable
First, realize that you can't use JavaScript to check for cookies if JavaScript is turned off. The usual check for cookies being on is to write one and then read it.
Do you care about the case when cookies are on but JavaScript is off? What are you going to do based on the information?
I found this code here for checking for a cookie via PHP. Doesn't rely on JavaScript. Is PHP your server language?
<?php
class cookieCheck
{
public function check()
{
if (setcookie("test", "test", time() + 100))
{
//COOKIE IS SET
if (isset ($_COOKIE['test']))
{
return "Cookies are enabled on your browser";
}
else
{
return "Cookies are <b>NOT</b> enabled on your browser";
}
}
}
}
?>

Categories