Update a cookie with a new one when visiting different pages - php

I have a website that has multiple locations and each location has their own set of information. When a user visits the main corp page, the location information will not display. When the user then goes to a location page I have a cookie being set.
$location_address = get_field('location_address','options');
$location_city = get_field('location_city','options');
$location_state = get_field('location_state','options');
$location_zip_code = get_field('location_zip_code','options');
$location_phone_number = get_field('location_phone_number','options');
// cookie will expire when the browser close
setcookie("locationAddress",$location_address);
setcookie("locationCity",$location_city);
setcookie("locationState",$location_state);
setcookie("locationZipcode",$location_zip_code);
setcookie("locationPhone",$location_phone_number);
The cookie is showing my location information in the firebug console. However, what is happening is when I go to another location, its grabbing both sets of cookies. I need it to replace the cookie previously set with the new one.
This is my code as well to output the cookie, which seems to be breaking as well:
<div class="top_contact">
<p><?php if(!isset($_COOKIE[$location_address])) { echo "" . $location_address . "";} ?>, <?php if(!isset($_COOKIE[$location_city])) { echo "" . $location_city . "";} ?> <?php if(!isset($_COOKIE[$location_state])) { echo "" . $location_state . "";} ?> <?php if(!isset($_COOKIE[$location_zip_code])) { echo "" . $location_zip_code . "";} ?> | <span class="top_phone"><?php if(!isset($_COOKIE[$location_phone_number])) { echo "" . $location_phone_number . "";} ?></span> </p>
</div>

You should set "path" argument in setcookie.
setcookie("locationAddress",$location_address, 0, "/");
setcookie("locationCity",$location_city, 0, "/");
setcookie("locationState",$location_state, 0, "/");
setcookie("locationZipcode",$location_zip_code, 0, "/");
setcookie("locationPhone",$location_phone_number, 0, "/");

If I were you I would probably try and set the path for the cookies.
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
also, I spotted a few commas in your code and I fixed the spaghetti code.
<?php
echo '<div class="top_contact"><p>';
if(!isset($_COOKIE[$location_address]))
{
echo $location_address;
}
if(!isset($_COOKIE[$location_city]))
{
echo $location_city;
}
if(!isset($_COOKIE[$location_state]))
{
echo $location_state;
}
if(!isset($_COOKIE[$location_zip_code]))
{
echo $location_zip_code;
}
echo '<span class="top_phone">';
if(!isset($_COOKIE[$location_phone_number]))
{
echo $location_phone_number;
}
echo '</span> </p> </div>';
?>

Related

PHP show all cookies relevant to some string

Let’s suppose I‘ve set cookie in PHP, like so:
cookie_name = "USER_PRODUCT".rand(0,9999);
$cookie_value = $name;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
echo "Successs";
And I display those cookie data like this:
<?php foreach ($_COOKIE as $key=>$val) { ?>
<div class="row col-sm-4 productDiv" data-id="myProduct_<?=$i?>" style="margin: 0px;">
<div class="alert alert-info mydiv"><?=$val?></div>
</div>
<?php } ?>
Now on another page I need to display all cookies whose name starts with USER_PRODUCT. Is it possible in PHP or is there another way?
This is a solution without the explode.
<?php
foreach ($_COOKIE as $key=>$val) {
if (substr($key, 0, 12) == "USER_PRODUCT") {
echo $key . " - " . $val . "<br>";
}
}
Assuming your page 1 code is as follow
$name="topupStackoverflow";
$cookie_name = "USER_PRODUCT".rand(0,9999);
$cookie_value = $name;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
echo "Successs";
you can do this for page 2 (or any other application where the user_product can be located at any position)
$stringn="USER_PRODUCT";
foreach($_COOKIE as $cookie => $taste){
if(stristr($cookie,$stringn)!=false){
echo $cookie." = = >>".$taste."<br>";
}
}

Cookie value not incrementing in PHP

For some reason I'm trying to have my "else" statement increment the amount of times the person has been to my website and it's not incrementing correctly. When I run my php, all it does it increment it once, after that, there are no more refreshes and the $cookieValue just keep echoing 2 instead of 3,4,5,6... What am I missing here?
<?php
date_default_timezone_set('EST');
if (!isset($_COOKIE["time"])) {
$cookieValue = 1;
setcookie("time", $cookieValue, time()+(86400*365));
}
$cookieLastVisit = date(DATE_RFC1036);
setcookie("lastVisit", $cookieLastVisit, time()+(86400*365));
?>
<html>
<head>
<title>Question 2</title>
</head>
<body>
<?php
if ($cookieValue == 1){
echo ("Welcome to my webpage! It is the first time that you are here.");
} else {
$cookieValue = ++$_COOKIE["time"];
echo("Hello, this is the " . $_COOKIE["time"] . " time that you are visiting my webpage. Last time you visited my webpage on: " . $cookieLastVisit . " EST");
$visit = date(DATE_RFC1036);
setcookie("lastVisit", $visit);
}
?>
</body>
</html>
Move the setting of the cookie time var to the same place as the declaration.
<?php
date_default_timezone_set('EST');
if (!isset($_COOKIE["time"])) {
$cookieValue = 1;
} else {
$cookieValue = ++$_COOKIE["time"];
}
setcookie("time", $cookieValue, time()+(86400*365));
$cookieLastVisit = date(DATE_RFC1036);
setcookie("lastVisit", $cookieLastVisit, time()+(86400*365));
?>
<html>
<head>
<title>Question 2</title>
</head>
<body>
<?php
if ($cookieValue == 1){
echo ("Welcome to my webpage! It is the first time that you are here.");
} else {
echo("Hello, this is the " . $_COOKIE["time"] . " time that you are visiting my webpage. Last time you visited my webpage on: " . $cookieLastVisit . " EST");
// you can't set cookie after you've output to the browser :/
//$visit = date(DATE_RFC1036);
//setcookie("lastVisit", $visit);
}
?>
</body>
</html>
You need to set the value of the cookie. The change to the $_COOKIE variable doesn't save the value of the cookie in "the next" page
else {
$cookieValue = ++$_COOKIE["time"];
setcookie("time", $cookieValue, time()+(86400*365));
...
}

PHP cookie visit counter not working

Hey I'm trying to make a counter of how many times someone is visiting my webpage and when it was the last time he visited. The last time visited is working fine.
I'm having a problem to display how many times he has been on the page however.
There's a bad display and it seems like I may be missing and incrementation somewhere but I can't seem to figure it out:
<?php
$Month = 3600 + time();
date_default_timezone_set('EST');
setcookie('AboutVisit', date("D M j G:i:s T Y"), $Month);
?>
<?php
if(isset($_COOKIE['AboutVisit']))
{
$last = $_COOKIE['AboutVisit'];
echo "Welcome back! <br> You last visited on ". $last . "<br>";
$cookie = ++$_COOKIE['AboutVisit'];
echo ("You have viewed this page" . $cookie . "times.");
}
else
{
echo "It's your first time on the server!";
}
?>
EDIT: NEW CODE
<?php
$Month = 3600 + time();
date_default_timezone_set('EST');
setcookie('AboutVisit1', date("D M j G:i:s T Y"), $Month);
?>
<?php
if(isset($_COOKIE['AboutVisit1']))
{
$last = $_COOKIE['AboutVisit1'];
echo "Welcome back! <br> You last visited on ". $last . "<br>";
}
if(isset($_COOKIE['visitCount1'])){
$cookie = ++$_COOKIE['visitCount1'];
echo ("You have viewed this page" . $cookie . "times.");
}
else
{
echo "It's your first time on the server!";
setcookie('visitCount1');
}
?>
You will need 2 cookies, one for the date and one for the counter.
Also remember that cookies must be sent before any other output is sent to the browser, or they will be lost (and an error generated), so it would be better to store your messages in variables and output them once you have completed ALL cookie processing.
It would also be simpler to save the time() in the date cookie and format its output only for viewing on the page.
<?php
if(isset($_COOKIE['LastVisitDate']))
{
$msg1 = 'Welcome back! <br> You last visited on ' . date('d/m/Y H:i:s', $_COOKIE['LastVisitDate']) . '<br>';
} else {
$msg1 = "It's your first time on the server!";
}
setcookie('LastVisitDate', time(), time()+3600); // reset to now
if ( isset($_COOKIE['VisitCount']) ) {
$msg2 = "You have viewed this page {$_COOKIE['VisitCount']} times.";
setcookie('VisitCount', (int)$_COOKIE['VisitCount']+1, time()+3600 );
} else {
setcookie('VisitCount',1, time()+3600 );
$msg2 = 'Thanks for visiting, I hope you enjoy your first visit';
}
echo $msg1;
echo $msg2;
?>
Also note that cookies can be blocked, by the browser, so this is not a completely reliable method of tracking users.
You forgot to call setcookie(). Take a look at http://www.w3schools.com/php/func_http_setcookie.asp
Try This
<?php
if(isset($_COOKIE['AboutVisit']))
{
$last = $_COOKIE['AboutVisit'];
echo "Welcome back! <br> You last visited on ". $last . "<br>";
$value= $_COOKIE['AboutVisit']+1; //or whatever you wnt
setcookie("AboutVisit", $value);
echo ("You have viewed this page" . $cookie . "times.");
}
else
{
echo "It's your first time on the server!";
}
?>

php code allways runs else and not if

I Cant login for some reazon, every time i open with
the testing file password exist, i have put an echo-test and mark it, but the code allways runs the else and not the if.
the kernel-login-logout.php is this:
<?php
$formusername = $_GET["username"];
$formpasswd = $_GET["passwd"];
$passwdget = file_get_contents( "users/$formusername/passwd/thepasswd.txt" );
if ($formpasswd == $passwdget)
{
setcookie("libusername", $formusername,time() + (86400 * 7));
setcookie("libpasswd", $formpasswd,time() + (86400 * 7));
}
else
{
echo ("Password not found<br>");
}
?>
<?php echo ($passwdget); ?><br>
<?php echo ($formpasswd); ?>
the url:
kernel-login-logout.php?username=userdokimi&passwd=testpasswd&login=Login
the output:
Password not found
testpasswd
testpasswd
You have code like this:
if A
if B
else C
That else applies to the if B, NOT the if A.
I think you meant this:
if A
elseif B
else C
Try this:
<?php echo "'$passwdget'",strlen($passwdget); ?><br>
<?php echo "'$formpasswd'",strlen($formpasswd); ?>
to confirm that one or both of those variables don't have some invisible characters glued on to them, making them not equal.
You have a password stored in plain text (and visible in a Query String) -- that's very insecure, but we'll let that pass for the moment.
Don't assume the keys "logout", "passwd" and "username" will always be set.
You are also missing an else there.
if (isset($_GET['passwd']) && $_GET["passwd"] == $passwdget)
{
setcookie("libusername", $username,time() + (86400 * 7));
setcookie("libpasswd", $passwd,time() + (86400 * 7));
}
else if (isset($_GET['logout']) && $_GET["logout"] == "Logout")
{
setcookie("libusername", null,time() + (86400 * 7));
setcookie("libpasswd", null,time() + (86400 * 7));
}
else
{
echo ("<br>Password not found");
}

php setcookie fails under php5

I created this simple script which will either set a cookie with three values or retrieve the cookies values if they are already set. On my server running PHP4, everything works. On my server with PHP 5 (5.2.11), the script fails to set the cookie in the browser. I already checked if output buffering is enabled in my php.ini and it is. Does anyone have any ideas as to why this fails to work?
<?php
echo "<!DOCTYPE html>";
echo "<body>";
if (!isset($_COOKIE['taeinv'])) {
echo "No cookie set... Attempting to set a new cookie.";
$user = "testuser";
$role = "admin";
$expire = "true";
$halfHour = 1800;
setcookie("websitename[Expire]", $expire, time()+$halfHour);
setcookie("websitename[User]", $user, time()+$halfHour);
setcookie("websitename[Role]", $role, time()+$halfHour);
}
if (isset($_COOKIE['websitename'])) {
echo "Cookie Values:";
echo "<br />";
foreach ($_COOKIE['websitename'] as $name => $value) {
echo "<b>$name</b> : $value <br />\n";
}
}
echo "<br />";
echo "<a href=logout.php>Logout</a>";
echo "</body>";
echo "</html>";
?>
You have to set the cookie before any output to the browser. Try moving all echo lines somewhere below the setcookie call. You could do something like this:
<?php
$set = false;
if (!isset($_COOKIE['taeinv'])) {
$set = true;
$user = "testuser";
$role = "admin";
$expire = "true";
$halfHour = 1800;
setcookie("websitename[Expire]", $expire, time()+$halfHour);
setcookie("websitename[User]", $user, time()+$halfHour);
setcookie("websitename[Role]", $role, time()+$halfHour);
}
echo "<!DOCTYPE html>";
echo "<body>";
if ($set) {
echo "No cookie set... Attempted to set a new cookie.";
}
if (isset($_COOKIE['websitename'])) {
echo "Cookie Values:";
echo "<br />";
foreach ($_COOKIE['websitename'] as $name => $value) {
echo "<b>$name</b> : $value <br />\n";
}
}
echo "<br />";
echo "<a href=logout.php>Logout</a>";
echo "</body>";
echo "</html>";
?>
That worked on my old PHP4 server, but not on PHP5.
Use output buffering – ob_start() and ob_end_flush().
Example:
<?php
ob_start();
echo '<p>Initializing…</p>';
setcookie('myLanguage', 'PHP');
ob_end_flush();
// you can continue your PHP code here…
?>
I had a similar problem but it was only in Chrome that the cookies disappeared. Firefox was fine.
Setting all the parameters in the setcookie function fixed it.
This sets the cookie but Chrome drops the cookie within a click:
setcookie('uname', 'Joe', time()+3600*24);
This sets the cookie and the browser retains it:
setcookie('uname', 'Joe', time()+3600*24, '/', 'www.domain.com', false, false);

Categories