I am implementing a php page counter that will keep track of each time the user visits this page until the browser is closed. I am checking to see if the cookie is set, if it is. Then I am increment it and reset its value. But the problem I am having is that the counter is always at two, why is this?
<html>
<head>
<title>Count Page Access</title>
</head>
<body>
<?php
if (!isset($_COOKIE['count']))
{
?>
Welcome! This is the first time you have viewed this page.
<?php
$cookie = 1;
setcookie("count", $cookie);
}
else
{
$cookie = $_COOKIE['count']++;
setcookie("count", $cookie);
?>
You have viewed this page <?= $_COOKIE['count'] ?> times.
<?php }// end else ?>
</body>
</html>
Edit: Thanks everyone, I did the pre increment thing and got it to work
This is happening because of the ++ being used as a post-increment instead of a pre-increment. Essentially what is happening is you're saying, "set $cookie to the value of $_COOKIE['count'], and then increment $_COOKIE['count']. This means that each time you set it you're only actually making $cookie equal 1, and even though $_COOKIE['count'] is showing it as 2, the actual cookie you send will only equal 1. If you do $cookie = ++$_COOKIE['count']; you should get the correct result.
This line is the problem:
$cookie = $_COOKIE['count']++;
It doesn't increment the way you expect; the variable $cookie is set to the value of $_COOKIE, and then $_COOKIE is incremented. It's the postincrement operator.
Use the preincrement operator instead, which increments and then returns:
$cookie = ++$_COOKIE['count'];
the _COOKIE array is populated ONCE when the script first starts up (before any code is actually executed), and then is NOT touched again by PHP. Even if you do a setcookie() call to change one of the cookies, that change will NOT take effect until the next page load.
As well, the ++ operator is working in "post-increment" mode. Doing
$cookie = $_COOKIE['count']++;
boils down to this:
$cookie = $_COOKIE['count'];
$_COOKIE['count'] = $_COOKIE['count'] + 1;
What you want is the PRE-increment version:
$cookie = ++$_COOKIE['count'];
which increments the cookie value and THEN assigns it to the cookie var.
You only need to do this
setcookie('count', isset($_COOKIE['count']) ? $_COOKIE['count']++ : 1);
Like so:
<?php
setcookie('count', isset($_COOKIE['count']) ? $_COOKIE['count']++ : 1);
$visitCount = $_COOKIE['count'];
?>
<html>
<head>
<title>Count Page Access</title>
</head>
<body>
<?if ($visitCount == 1): ?>
Welcome! This is the first time you have viewed this page.
<?else:?>
You have viewed this page <?= $_COOKIE['count'] ?> times.
<?endif;?>
</body>
</html>
Related
How to access the incremented value of session on the same page where we have defined the initial value of session, I am using this method for incrementation of value but on another page
<?php
$_SESSION['indexValue'] = 1;
?>
This is my test.php page where i have decrelaed the inital value of session.
<?php
$Incrementvalue = $_SESSION['indexValue'];
$counter = (int)$Incrementvalue;
if ($counter=$counter) {
$counter++;
$_SESSION['indexValue'] = $counter;
}
echo "$_SESSION['indexValue']";
?>
This is my getdata.php page where I have implmented the increment value function. Now i have to pass this increment value of Session again on test.php page . How can I perform this?
your code seems not to be thought off
first of all, you need to call session_start() at beginning
then you can access everyewhere your $_SESSION variable (if you call session_start() before)
if ($counter=$counter) {
$counter++;
$_SESSION['indexValue'] = $counter;
}
this seems useless
$_SESSION['indexValue']++;
is enough
First of all there are few errors in code like
if ($counter=$counter) should be if ($counter == $counter)
And
echo "$_SESSION['indexValue']" should be echo $_SESSION['indexValue'].
Now answer to your question is that session is accessible anywhere throughout the project/application. So you need not to pass it , just access it as $_SESSION['indexValue'].
I'm trying to get a session variable to alternate between 0 and 1 on each page load.
So first time page loads
$_SESSION['turn'] = 0;
Second time
$_SESSION['turn'] = 1;
Third time
`$_SESSION['turn'] = 0;`
and so on.
Then I can call that variable later in the page.
I can't work out how to do this. I've tried a simple IF function but can't get it to work.
First the session must be started on any page wishing to make use of the session array. session_start()
Next you have to remember that initially the session variable you are using will not exist the first time you attempt to use it
So
<?php
session_start();
if ( !isset($_SESSION['turn']) ) {
// does not exist yet, so create with 0
// you may want to initialize it to 1, thats up to you
$_SESSION['turn'] = 0;
} else {
$_SESSION['turn'] = $_SESSION['turn'] == 0 ? 1 : 0;
}
Try this where the page is loaded.
$_SESSION['turn']=1-$_SESSION['turn'];
code:
<?php
session_start();
echo $_SESSION['turn'];
$_SESSION['turn']=1-$_SESSION['turn'];
?>
Edit : RiggsFolly !isset() is correct. mine misses it and it will give errors in log. and the first value is not 0
I have a session variable that is updated when a link is clicked which adds GET variables to the current URL:
<?php
$_SESSION['test'] = 0;
if (isset($_GET['do'] && $_GET['do'] == 'this')) {
$_SESSION['test'] = $_SESSION['test'] + 1;
}
echo $_SESSION['test'];
?>
Click me
When the link is clicked, the new session value that is echoed is still 0.
Why? How do I get this to echo the updated value? (1)
EDIT: Yes, session_start() is included at the top of the page.
change it to be like this:
<?php
session_start();
if(!array_key_exists('test', $_SESSION)){
$_SESSION['test'] = 0;
}
if(array_key_exists('do', $_GET) && $_GET['do'] === 'this') {
$_SESSION['test']++;
}
echo $_SESSION['test'];
?>
Click me
I like array_key_exists() more than isset because the key can exist being null and still pass the test:
From the php docs: "isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does."
You also were using isset incorrectly to test the contents of $_GET['do']. To top things off, you didn't start the session on each page load.
session_start() will initialize the $_SESSION variable and fill it with the appropriate contents. Since this was not in your code, the $_SESSION variable never had your 'do' key.
The second-to-last problem you had was the very first line, you were always setting the 'test' key to 0 causing the outcome to always be 1 after clicking Click me
and finally, you didn't close the php tag prior to outputting raw HTML which should have given you an error
Maybe you have not paste the whole code but here is how it should have been done.
<?php
session_start();
$_SESSION['test'] = 0;
if (isset($_GET['do']) && $_GET['do'] == 'this') {
$_SESSION['test'] += 1;
}
echo $_SESSION['test'];
?>
Click me
You need to start with session_start() Google to learn more about it.
You have put everything in the isset() Google isset() to learn more about it.
you need to close php tags before you can insert raw HTML. Inside HTML you can execute php with <?php ?> tags.
Hope this helps.
As mentioned before, you have everything wrapped in isset() should be
isset($_GET['do'])
not
isset($_GET['do']
Also, you're session is always being set to 0 on each page refresh. You need to only set $_SESSION['test'] = 0 if $_SESSION['test'] has not been set yet.
if (!isset($_SESSION['test'])) {
$_SESSION['test'] = 0;
}
You are missing session_start() at the top of your script. You're also not assigning the session if it doesn't previously exist, you're continuously setting it to 0 before incrementing.
can someone please how what hell this
cookie stops at 2 ?
<?php
if (isset($_COOKIE["count"]))
{
$cookie = ++$_COOKIE['count'];
}
else {
echo "Welcome guest!<br>";
setcookie("count", 1, time()+3600);
}
ECHO $cookie;
?>
thank you all
$cookie = ++$_COOKIE['count']; is only called once. If $_COOKIE[count] has a numerical value, $cookie will store that value plus 1.
Also, the following is not strictly correct:
echo "Welcome guest!<br>";
setcookie("count", 1, time()+3600);
You cannot call an echo before a header. I recommend you change it to this:
setcookie("count", 1, time()+3600);
echo "Welcome guest!<br>";
You cannot change cookie value by incrementing $_COOKIE[xxx], you have to use setcookie() function for that. This will work:
<?php
$cookie = isset($_COOKIE["count"]) ? $_COOKIE["count"] : 0;
setcookie('count', $cookie + 1, time()+3600);
ECHO $cookie;
You cannot update a cookie that way. However you can overwrite it.
See setcookie for more info.
If you set a cookie, it won't retrieved until the next request and so the data won't be present in $_COOKIE.
So setting a cookie and accessing it cannot be in same instance. You need to redirect or refresh after setting it.
Simply use setcookie() to increment.
to increment you place the ++ after the string, not before it.
I'm trying to do a simple test php script for sessions. Basically it increments a counter (stored in $_SESSION) every time you refresh that page. That works, but I'm trying to have a link to destroy the session which reloads the page with the ?destroy=1 parameter. I've tried a couple of if statements to see if that parameter is set and if so to destroy the session but it doesn't seem to work.
I've even put an if statement in the main body to pop-up a message if the parameter is set - but it doesn't seem to be picked up.
I know I'm doing something silly (I'm a PHP newbie) but I can't seem to find what it is...
See code here:
<?php
if ($_POST['destroy']) {
session_destroy();
} else {
session_start();
}
?>
<html>
<head>
<title>Session test</title>
</head>
<body>
<?php
if (isset($_POST['destroy'])) {
echo "Destroy set";
}
$_SESSION['counter']++;
echo "You have visited this page " . $_SESSION['counter'] . " times" . "<BR>";
echo "I am tracking you using the session id " . session_id() . "<BR>";
echo "Click here to destroy the session.";
?>
I think you put
$_POST['destroy']
Instead of
$_GET['destroy']
You need to use a form if you'd like to use a $_POST variable. $_GET variables are stored in the URL.
By the way you can use
$_REQUEST['destroy']
which would work regardless if the data is passed in a POST or a GET request.
In the PHP Manual it has code snippet for destroying a session.
session_start();
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();
Yeah, you're going to want to do
if( $_GET['destroy'] == 1 )
or
if( isset($_GET['destroy']) )
I know I'm doing something silly (I'm a php newbie) but I can't seem to find what it is...
that is how you are going to learn a lot ;) enjoy it ...