Incrementing a Cookie's Value With PHP - php

I'm just looking to create a cookie which stores the number of correct answers someone gives in a quiz and then increment it for every correct answer.
if(isset($_GET['first'])){setcookie("answers", 0, time()+900);}
elseif($_POST['1']){
if($_POST['1']=='y'){
$_COOKIE['answers']++;
}
The first part just sets the cookie initially if they are starting the quiz. After they answer, they will move to the next page (which is the same page but with different HTML) which also has a question named "1".
The problem is, the cookie keeps getting reset to 0 at the start of every page. However, I'm positive I'm not setting it again. Any help would be much appreciated! Also, I know this isn't a very robust way to create a quiz but it's an exercise.

<?php
if(!isset($_COOKIE['answers']) || isset($_GET['first'])) {
setcookie("answers",0,time() + 900);
} else if (isset($_POST['1']) && $_POST['1'] === 'y') {
setcookie("answers", $_COOKIE['answers'] + 1 , time() + 900);
}
NOTE : each time you change the cookie value its expiration is also changed

You should set the vale for the cookie and example would be
<?php
$value = 'something from somewhere';
setcookie("TestCookie", $value); ?>

Related

Symfony: temporarily storing a count

We have a system where you can enter your email address. Now, we want that if you request 3 times in a row (without success) that a special value is reported back.
Everything is working, except how to store the count of tries. We're working with Api-Platform.
This means that a Symfony Session should not do the trick. It will probably restart and create a new session after every request.
So, how can we store a count? Here is an example of what we try to achieve with the usage of Symfony Sessions. Any ideas how to store the count? Sessions weren't possible (Maybe wrong implementation) and a database table seems to be a bit excessive.
if(!$session->has('c_tries')) {
$captchaTries = $session->set('c_tries', 0);
}
$captchaTries = $session->get('c_tries');
$new = $captchaTries + 1;
$session->set('c_tries', $new);
if($captchaTries > 2 ) {
....
It is best to solve this on the client side. You can use cookies.
if (!isset($_COOKIE('trakcer']))) {
setcookie ("TryCount", $captchaTries, time() + 3600); /*expires in 1 hour*/
}

Setting a cookie before page is refreshed/closed

I'm once again asking for the SO community for a little help.
I'm modifying a Joomla "quiz" component to make it behave the way I need it to.
What I'm trying to do now is to change the "refresh" behavior of the component. Basically, every quiz has a timeout, i.e., a time when the quiz is no longer accessible to the user so when the timer gets to 0, the quiz is submitted and so on, but the default behavior of this component makes it that whenever the page is refreshed the timer will reset to the initial set time (let's say, 10 minutes)
The thing is I want to be able to have the timer continue from where it left of in case of a refresh.
I haven't used PHP since 3 or 4 years ago so I'm kinda lost.
To be able to achieve the desired behavior I'm setting up a cookie that will store (via implode) the initial time (when the quiz was opened) and the "now" time (on load it's set to 0 but upon refresh I want to "update" the cookie to store the reload time).
With the initial time and the now time, I'll be able to calculate how much time has passed and place the timer from where it left off.
The thing is, I'm trying to "update" the cookie with a javascript 'onbeforeunload' so that I can manage to get the refresh time into the cookie. But for some reason, it's not doing anything at all. When I go to see the cookie contents everything is still the same from when the cookie was set.
I know that in order to update the cookie I'll have to delete it and then set it again, but I'm being unsuccessful.
Heres the sample code:
//This is responsible for setting the cookie (via PHP):
<?php
$name = "progress";
$now = 0;
$time_diff = 0;
$expire = time() + 3600;
$data = array(time(), $now, $time_diff, $this->quiz->time_limit);
//$var = implode(',', $data);
if(isset($_COOKIE[$name])) {
/* If defined, update the timer */
} else {
setcookie($name, implode(',',$data), $expire);
}
echo $_COOKIE[$name];
echo "<br />";
echo $this->quiz->time_limit;
?>
And this is to detect the "refresh" event (with Javascript that will run PHP):
window.onbeforeunload = function() {
<?php
$name = "progress";
$list = explode($_COOKIE[$name]);
//delete cookie
setcookie($name, "", time() - 3600);
//Update the fields
$list['1'] = time(); //now - refresh time
$list['2'] = $list['1'] - $list['0']; //time_diff
//Set the cookie again
setcookie($name, implode(',', $list), time() + 3600);
?>
}
Can anyone point out what is wrong with this code?
As has been said in the comments, JavaScript cannot run PHP code like that... but if you use AJAX then you can. Now with the code you posted for us to see, if you load up your page in the browser and view the code your function will look like this:
window.onbeforeunload(){
}
So it's no surprise that nothing is happening with your cookies when you are closing your browser. Now, without seeing your other functions it's hard to tell exactly what is happening but you can use PHP and JavaScript intertwined but in a different fashion. Let me explain this with an example.
window.onbeforeunload(){
var name = <?php $name='Steve'; echo($name); ?>;
console.log(name);
}
If you had this code and loaded the page in the browser you would no longer see the PHP code, but instead would see this:
window.onbeforeunload(){
var name = 'Steve';
console.log(name);
}
With that being said, here are a few links you might find helpful.
JavaScript Cookies
Set/Get Cookie using PHP and JavaScript
Simple AJAX - PHP and JavaScript

If statement, sessions variables

The following code is within an ajax call. I'm trying to make sure people don't vote on questions with a certain id too often using sessions.
So they click a button, which executes the following php code:
$id=$_GET["id"];
if ((isset($_SESSION["$id"]) && ((time() - $_SESSION["$id"]) > 180)) || (!isset($_SESSION["$id"]))) {
// last vote was more than 3 minutes ago
$_SESSION["$id"] = time(); // update/create vote time stamp
//there is code here to add the vote to the database
}
else{
echo "sorry, you've already voted recently";
}
So I'm creating a session variable for each question id which holds the time() of their last vote. I would do this with cookies, but they can be disabled.
Currently, there is a bug somewhere with my logic, because it allows the user to keep clicking the button and adding as many votes as they want.
Can anyone see an error that I have made?
using sessions to prevent multiple voting makes very little sense.
sessions do use cookies with the same drawbacks
unlike strings, variables in PHP should be addressed without quotes. such a false usage WILL cause an error someday.
I see no point in checking for isset($_SESSION[$id]) twice.
There was a bug in PHP which disallowed numerical indices for the $_SESSION array. Dunno if it was corrected nowadays.
As it was pointed out by Sajid, you have to call session_start() before using $_SESSION array.
now to the logic.
to me, it seems the code won't let anyone to vote at all. as it won't pass isset($_SESSION[$id]) condition for the first time and won't let $_SESSION[$id] to be set and so on.
it seems correct condition would be
if ( (!isset($_SESSION['vote'][$id]) OR (time() - $_SESSION['vote'][$id]) > 180) )
You need to call session_start() to start the session before any headers are sent. Otherwise, sessions will not be enabled unless the ini setting to autostart sessions is on. Also, your server must be correctly configured to be able to store session files (usually a writable tmp dir is needed). See more about sessions here: http://www.php.net/manual/en/ref.session.php
There might be a problem with the if statement. Try the following
$id=$_GET["id"];
if (((isset($_SESSION[$id]) && ((time() - $_SESSION[$id]) > 180))) || (!isset($_SESSION[$id]))) {
// last vote was more than 3 minutes ago
$_SESSION[$id] = time(); // update/create vote time stamp
//there is code here to add the vote to the database
}
else{
echo "sorry, you've already voted recently";
}
Perhaps time() returns milliseconds and you should compare to 180000 instead of 180.

PHP - consecutive page visits

my question is simple : How can I count how many consecutive days visitor have visited my site (php), any ideas are welcome.
Simple:
Just have some concept of either logging in, or a persistent cookie (logging in is more reliable since they can clear cookies). Then in your database have a field for "last logged in". If the last logged in field matches yesterday's date, increment your consecutive visit count, otherwise reset it.
EDIT: it's probably obvious, but make sure you update the "last logged in" field after you check it to be today, otherwise every time they load the page it'll increment the count!
EDIT: a quick example may look something like this (psuedo code):
// first you need to set $last seen from the DB..
// first you need to set consecutive from the DB too..
// once you have, you can do something like this.
if(strtotime('-1 day', date('Y-m-d')) == $last_seen) {
$consecutive = $consecutive + 1;
mysql_query(sprintf('UPDATE user SET last_seen=NOW(),consecutive=%d WHERE id=%d', $consecutive + 1, $id));
} else if(date('Y-m-d') == $last_seen) {
// ok, they logged in today again, do nothing.
} else {
$consecutive = 0; // only really needed if you plan on displaying it to the user
// later in this script
mysql_query(sprintf('UPDATE user SET last_seen=NOW(),consecutive=0 WHERE id=%d',$id));
}
cookies
if(isset($_COOKIE["identifier"])){
// log as existing user
}else{
setcookie('identifier', $id_value, ...
}
It wont work if people clear there cookies, which is why they clear cookies.
You can use pluggable traffic analitic tools, commercial or less like Google Analitics.

setcookie does not work

I have a simple file called index.php. I need to pass it a querystring that will be stored inside a never-expiring cookie. The file looks exactly like this :
<?php
if (isset($_GET['referrer_id']))
{
$querystringWithJunk = $_GET['referrer_id'];
$querystringArray = explode('/', $querystringWithJunk);
setcookie("referrer_id", $querystringArray[0], time() + 60*60*24*365*100);
}?>
However, no cookie is set. What is inside referrer_id is a simple integer (in the tests I made, it's 1). Function setCoookie return true and everything seems to works fine but no cookie is set. Am I doing something wrong?
Time is bigger than int, so I think result is negative, and then cookie is set into past, what means, it is deleted. Set time to 3 years instead of 100.

Categories