Counting using session variables and cookies - php

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.

Related

Logic behind the code?

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.

Using Cookie Expire with IF and ELSE PHP, echo not working on ELSE

Why?
I'm attempting to setup an Adword Campaign with my WordPress website, pretty easy stuff but I want to be able to SWITCH contact forms depending if they visited the site using AdWords or Bing/Google SERPS.
So the idea is that if they visit https://example.com/landing-page/ they will reach a page with different contact numbers and email form that has a title indicating that they have come from Adwords, all straight forward, but then, if they click the menu bar away from the landing page, they will get standard numbers and standard email forms, which makes the tracking process a little bit harder.
Setting the temporary cookie
So by using custom WordPress page template files, and when a visitor visits the landing page, it sets a cookie using:
<?php
// 60 Seconds, live environment set to 6000 (1 hour)
$date_of_expiry = time() + 60 ;
setcookie( "adwords-customer", "adwords-visit", $date_of_expiry );
?>
Checking the cookie and do A or B
Then throughout the rest of the website (not present on the landing page) it will check if the cookie is present, and if present it does A, if not it does B, here's the code:
<?php
if(!isset($_COOKIE['adwords-customer']) || ($_COOKIE['adwords-customer'] != 'true')){
echo "cookie set";
} else {
echo "cookie not set";
}
?>
The Problem
The results are always "cookie set" and never else echo "cookie not set", thanks for any help in advance.
You see the ! here?
if(!isset($_COOKIE['adwords-customer']) || ($_COOKIE['adwords-customer'] != 'true')){
^
echo "cookie set";
} else {
echo "cookie not set";
}
It means that you're checking if it is NOT set, so that should be removed or invert the echos.
And the != 'true' make sure you're not checking for boolean. If so, remove the quotes.
Try giving this code a go!
if(isset($_COOKIE['adwords-customer']) && ($_COOKIE['adwords-customer'] == true)){
echo "cookie set";
} else {
echo "cookie not set";
}
If you find it now works but only on the URL that sets the cookie then ensure that your setcookie is set using / to indicate the entire domain, rather than just the /path/, e.g:
$value = 'adwords-visit';
setcookie("adwords-customer", $value);
setcookie("adwords-customer", $value, time()+60);
setcookie("adwords-customer", $value, time()+60, "/");

Cookie warning alert doesnt dissapear on first click

I created this Cookie alert bar for my site, it works as intented. But you need to click the close link twice to close down the warning for some reason that I cannot figure out.
I use this following function to check if cookie exists or not.
function checkIfCookieExist($cookieName) {
if(isset($_COOKIE[$cookieName])) {
return true;
}
else {
return false;
}
}
if cookie does not exist, and the cookie get parameter exists and equals 1 I create a cookie
if (!checkIfCookieExist('cookieConfirmation') && isset($_GET['cookie']) && $_GET['cookie'] == 1) {
$cookieName = 'cookieConfirmation';
$cookieValue = 'Cookie confirmation';
$cookieDuration = 86400 * 30 * 3;
setcookie($cookieName, $cookieValue, time() + $cookieDuration);
}
Prints out the cookie bar, links to index with a get parameter for the cookie
function renderCookieBar() {
echo('
<div id="cookieBar">
<p>blabla cookie, cookies on this site yo</p>
I understand, close this box!
</div>
');
}
Calls function to print out cookiebar at given place in my html code
if(!checkIfCookieExist('cookieConfirmation')) {
renderCookieBar();
}
I appreciate any answers or help,
Cheers!
When you set the cookie in the header, the cookie is not directly present; means: the cookie is available up on the next page hit.
Check the manual: http://php.net/set_cookie
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST.
You can either
1. Set the cookie and immediately reload the page
Set the cookie and force a browser refresah by using header("Refresh:0");.
if (!checkIfCookieExist('cookieConfirmation') && isset($_GET['cookie']) && $_GET['cookie'] == 1) {
$cookieName = 'cookieConfirmation';
$cookieValue = 'Cookie confirmation';
$cookieDuration = 86400 * 30 * 3;
setcookie($cookieName, $cookieValue, time() + $cookieDuration);
header("Refresh:0");
}
2. Use Javascript
When setting the cookie with JavaScript it is directly available from the browser. You may also rewrite your script, so the JavaScript sets the cookie and removes the notification bar.
There are many solutions (also here on SO) how to work with cookies in JavaScript easily. If you are using a JavaScript library like jQuery you also have plugins handling the cookies.

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>";

Php sessions aren't working

I am new to php, and very new to sessions, so I have no idea what I am doing wrong. I followed the tutorial on tizag, and put this code on my site:
<?php
session_start();
echo SID . "<br><br>";
if(isset($_SESSION['views'])) {
$_SESSION['views'] = $_SESSION['views'] + 1;
} else {
$_SESSION['views'] = 1;
echo "views = ". $_SESSION['views'];
}
?>
The SID changes whenever I refresh, and the number does not count up.
Update: Url: http://121.73.150.105/PIA/
FIXED BY: Putting session_start() before my doctype, title etc.
Are cookies enabled in you're browser ? phpsessid is stored as a cookie , you can set different parameters for it , one that could be usefull in you're case could be session_get_cookie_params() , and see if everithing is oki with the session cookie params .
If anything is wrong like expiration date you can set the params with session_set_cookie_params()
Your PHP setup may have been configured to not save sessions in cookies.
To verify if this is the case, you can take a look at session.use_cookies in your php.ini, or using ini_get, like so:
<?php echo ini_get('session.use-cookies'); ?>
You can correct it at runtime, as well, using ini_set, like so:
<?php ini_set('session.use-cookies', '1'); ?>
either you are outputting something to the browser before calling session start, or you have cookies disabled.
You don't output the $_SESSION['view'] after the if statement. I think that's why it doesn't change.
Try:
<?php
session_start();
echo SID . "<br><br>";
if(isset($_SESSION['views'])) {
$_SESSION['views'] = $_SESSION['views'] + 1;
} else {
$_SESSION['views'] = 1;
}
echo "views = ". $_SESSION['views'];
?>
So you always output the new $_SESSION['views'] value.
EDIT:
I think the right answer is that the session is not set. But I'm curious, how can the code always outputs "view = 1"? Can I open a new question referencing this question or just discuss it here?
in your code if you cant see session ID you can write
session_id() in place of SID.
ini_set("session.use_cookies",1);
ini_set("session.use_only_cookies",1);
this two parameter must set to gether if you want it work

Categories