Logic behind the code? - php

There are two blocks of PHP code
Block 1
<?php
setcookie("test_cookie","0",time()-3600);
if(empty($_COOKIE["test_cookie"])){
echo "First time browsing";
setcookie("test_cookie","1",time()+3600);
}else{
$count = $_COOKIE['test_cookie'];
$count++;
setcookie("test_cookie",$count,time()+3600);
echo "Cookie set as " . $_COOKIE["test_cookie"] ;
}
Block 2
<?php
if(empty($_COOKIE["test_cookie"])){
echo "First time browsing";
setcookie("test_cookie","1",time()+3600);
}else{
$count = $_COOKIE['test_cookie'];
$count++;
setcookie("test_cookie",$count,time()+3600);
echo "Cookie set as " . $_COOKIE["test_cookie"] ;
}
setcookie("test_cookie","0",time()-3600);
In Block 1 cookie named test is unset which should echo "first time browsing"
but what i get is cookie count
In block 2 cookie named test is unset at last which echo "first time browsing" which is fine and i understand logic no matter what i set i unset at last which results in "first time browsing"
But what is wrong with with Block 1 i should have got same result as BLock 2 .. why am i getting Cookie count here ?
Please do explain this in simplest way possible .

The setcookie function does not modify the $_COOKIE array. It just state changes, that will be sent to the client. Your changes will be available in the $_COOKIE array only on the next page loads.
If you want the $_COOKIE array to be up to date with your setcookie calls in the current request, you should updates it manually every time:
setcookie("test_cookie","0",time()-3600);
unset($_COOKIE["test_cookie"]);
setcookie("test_cookie","1",time()+3600);
$_COOKIE["test_cookie"] = "1";
Also calling setcookie after any output, as in your code, may lead to errors.

Related

Counting using session variables and cookies

Probably a dumb question but I just started learning PHP and now I have to do an exercise in which, on the one hand, the session variables have to count how often you have visited the page before closing the browser. And on the other hand, the cookies should count how often you have visited a website in total.
So also if you have closed your web browser, the cookie should continue counting.
This is my problem though.
If I close my web browser and start it again, the cookie starts all over again with counting. How to solve this?
PHP File
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 1;
} else {
$_SESSION['count']++;
}
echo "You have visited this page " . $_SESSION['count'] . " times before you closed your browser";
$count = $_SESSION['count'];
setcookie("count", "$count", time() + 3600);
if (!isset($_COOKIE['count'])) {
$_COOKIE['count'] = ($_COOKIE['count'] + $_SESSION['count']);
} else {
$_COOKIE['count']++;
}
echo "<br> In total you have visited this page " . $_COOKIE['count'] . " times";
?>
You are overwritting the cookie value with the session value.
Instead check if the cookie is already set, and if so, just add to it:
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 1;
} else {
$_SESSION['count']++;
}
$count = $_SESSION['count'];
if (!isset($_COOKIE['count'])) {
setcookie("count", $count, time() + 3600);
$_COOKIE['count'] = $count; //setcookie does not update the superglobal $_COOKIE
} else {
setcookie("count", $count + $_COOKIE['count'], time() + 3600);
$_COOKIE['count'] += $count; //see above
}
//also headers (eg for setting cookies) can only be sent BEFORE the response body, so no echos
echo "You have visited this page " . $_SESSION['count'] . " times before you closed your browser";
echo "<br> In total you have visited this page " . $_COOKIE['count'] . " times";
I think you must set cookie with path
setcookie("count", "$count", time() + 3600, "/");
Most major browsers bundle developer tools that include a cookie inspector. In Firefox it's called Storage Inspector. It can be found in program menus but default short-cut is Shift+F9:
Your cookie should show up there. Also, the Network Monitor (Ctrl+Shift+Q) allows to diagnose whether the cookie is being received and sent back (since you are setting cookies from server-side, the transport mechanism used is HTTP headers).
You should also check PHP manual as often as needed. If your IDE won't generate links from code, there's a little trick you can use: append the function name to http://php.net/, e.g.: http://php.net/setcookie.
Last but not least, you have a condition to run when a given array keys does not exist, yet you use the variable anyway:
if (!isset($_COOKIE['count'])) {
$_COOKIE['count'] = ($_COOKIE['count'] + $_SESSION['count']);
^^^^^^^^^^^^^^^^^
If PHP did not warn you, it's because your PHP set-up is configured to hide it from you. You need to fix it ASAP because coding without the aid of error messages is hard. As quick start, you can set the error_reporting and display_errors directives in your computer's system-wide php.ini file (details here). Errors thumb rule: show in development, log in production.
These tools should suffice to trouble-shoot your issue.

The Cookie set is not detected

Hi guys i set a cookie using my script known as cookieset.php
setcookie("atid", $atid, time() + 60 * 60 * 24 * 365, "/", ".mydomain.com");
and it is shown in the browser
Name atid
Content 1234
but when i try to retrieve it like this from another script
echo 'value is: ' . $_COOKIE['atid'];
it gives the error saying
undefnied index: atid in.........
can anybody help me over this
setcookie("atid",$atid,time()+315360,"/");
// use
if (isset($_COOKIE['atid'])) {
echo "cookeies set ";
} else {
echo "cookeies not set ";
}
use mozila firebug / cookies to see cookies file
The $_COOKIE array is populated with information sent from the browser. The first time you request the file that calls setcookie - cookieset.php - the server sends the cookie to the browser, but at this time the $_COOKIE array was already populated without the cookie you just set.
The cookie will be available in subsequent requests until it expires.
To see the cookie in PHP, just do like this.
if (isset($_COOKIE['atid'])) {
echo 'Cookie found with value ' . $_COOKIE['atid'];
} else {
setcookie('atid', $atid, time() + 60 * 60 * 24 * 365, "/", ".mydomain.com");
echo 'Cookie was set. Please refresh to see it working';
}
The problem (from the error), seems to be that $_COOKIE['atid'] (depending on what line the error is at) is undefined - that means it has not been set, and seeing that you actually set the cookie, I am saying that its the atid that is undefined. Make sure you are getting it, check with isset()
Try this :
if (isset($_COOKIE['atid'])) {
echo $_COOKIE['atid'];
} else {
echo "No cookie Set";
}
And one more point :
it won't be available until the next page load or by doing the page request again.
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

setcookie(); does not set cookies

I have following problem, I am trying to set cookies without any success. setcookie(); function returns true so it looks like it setting cookie however when I am trying to access it on the same or following page I get error 'Undefined Index....'
<?
session_start();
ob_start();
echo setcookie("order",$_SESSION['cart'],time()+3600,'/',NULL);
//added to see if Cookie is set
echo "<br/>";
var_dump($_COOKIE);
exit();
if($_GET['paypal'] == 1){
header("Location: /paypal-express-checkout/process.php");
}else{
header("Location: /insert_order.php");
}
ob_end_flush();
exit();
?>
next page follows like this
<?php
session_start();
include_once("../includes/inc_config.php");
include_once("../order.php");
include_once("config.php");
include_once("paypal.class.php");
#region POST
if(!isset($_GET['token'])) //Post Data received from product list page.
{
//Mainly we need 4 variables from an item, Item Name, Item Price, Item Number and Item Quantity.
if(!isset($_COOKIE['order'])){
exit();
}
$paypal_data = '';
$ItemTotalPrice = 0;
$order = unserialize($_COOKIE['order']);
print_r($order);
exit;
You are setting the domain value to NULL. Try leaving the NULL away:
echo setcookie("order",$_SESSION['cart'],time()+3600,'/');
OR set it to your domain:
echo setcookie("order",$_SESSION['cart'],time()+3600,'/',".yourdomain.com");
I would var_dump or print_r the $_COOKIE variable before I make a decision that it's not getting passed through. Holding that thought once you setcookie something gets registered into the $_COOKIE variable for sure.
I agree with the statements above since you only can access $_COOKIE on the next refresh but there is another way to do it to make your form or page more interactive.
I would register the cookie and use a php page refresh (display a working... div while thats happening) then come back to the page and try to do what you originally tried doing. Very basic but pretty much straight forward.

How to display correct output of Sessions & Cookies in PHP

I have a problem with this program of Sessions & Cookies.
Plz see the following code:-
<?php
session_start(); //session starts
if(! isset($_COOKIE['cnt']))
{
#$_SESSION['nv'] = 1;
}
else
{
#$_SESSION['nv'] += 1;
}
$val = $_SESSION['nv'];
echo $val;
setcookie("cnt", $val, time()+30 );
echo "<h1>No. of visits=".#$_COOKIE['cnt'] ."</h1>";
if (#$_COOKIE['cnt'] == 5)
{
setcookie("cnt", 0, time()-30);
session_destroy();
}
?>
It is not giving the correct output.
When I run the program for the first time, it shows:
No. of visits=
Means nothing..
& when I run the program for the second time, it shows:
No. of visits=1
I want that my output should be displayed as "No. of visits=1" when I run the program for the first time. But it shows this output at 2nd time.
Do help me please..
The cookie set by setcookie is sent along with the HTTP response the server sends to the client and, quoting the documentation:
Once the cookies have been set, they can be accessed on the next page
load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
You should print the session var
echo "<h1>No. of visits=" . $_SESSION['nv'] . "</h1>";

Cookies counter php

I'm trying to do this counter for cookies. The cookies give the right values when I visit the site more than once but for first visit, it always tell me that the cookies(both) are not set. I'm new at PHP so I'm not sure if I missed something. The cookies are set before html tags.
setcookie("user", isset($_COOKIE["user"])? ++$_COOKIE["user"] : 1);
setcookie("date", date("d/m/y h:i:s"));
$count = $_COOKIE["user"];
---------------------------------
<body>
<p><?php
if( $count == 1)
echo "Welcome! You're new here.";
else
echo "Hello, you have visited " .$_COOKIE["user"]. " times.";
echo "<br/>";
echo "Your last visit was ".$_COOKIE["date"];
?></p>
</body>
The setcookie function puts the cookie into the servers http header, which is sent along with the first request. The $_COOKIE array however does not get these values passed internally (from the setcookie function), instead it is generated from the request headers sent by the browser and this only happens after the browser got the cookie (from the first request) and sends it back on the second request.
What you could do is this:
$count = isset($_COOKIE["user"])?$_COOKIE["user"]:1;
I'm not sure but all I see for now is that else is used the false way.
You can write:
if (cond)
do();
else
doelse();
Just single lines work like this.
Use instead:
<?php
if($count == 1)
echo "Welcome! You're new here.";
else {
echo "Hello, you have visited " .$_COOKIE["user"]. " times.";
echo "<br/>";
echo "Your last visit was ".$_COOKIE["date"];
}
?>

Categories