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"];
}
?>
Related
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.
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, "/");
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.
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>";
So i'm writing this code so that you either get forwarded to a certain page if you're the first one to hit the link, or you are sent back to the original page after being displayed a message if you're not what beginner mistake am i making?
<?php
$count = file_get_contents('counter.txt');
$count = trim($count);
if ($count="0")
{
$count = $count + 1;
$fl = fopen("counter.txt","w+");
fwrite($fl,$count);
fclose($fl);
header("Location: newpage.html");
}
else
{
fclose($fl);
echo "Sorry but the item has already been sold out";
header("Location: oldpage.html");
}
?>
As for the delay, you can accomplish it two different ways. The first is to use PHP header (like you are currently doing), but change it to look like this:
<?php
header("refresh:5;url=oldpage.html");
echo "Sorry but the item has already been sold out";
?>
The other way is to echo out a piece of HTML code, the meta-refresh:
<?php
echo '<meta http-equiv="refresh" content="2;url=oldpage.html">';
echo "Sorry but the item has already been sold out";
?>
In both examples, 5 is the amount of seconds until the refresh. Experiment with each one to see if it will fit your needs.
This might be some sort of syntax that I'm not familiar with, but none of my scripts have ever had the
<? code
I simply use
<?
Also since you did not delay our header tag the user will not see the previously echoed statement above it. It will automatically redirect before the page has time to output fully.