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.
Related
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*/
}
I was hoping somebody could help me out with how I would implement a 'Remember me' function in Parse.
When the ParseUser is first created, a ParseSession is also created with them, however this has an expiry date of 1 year. The problem is, the expiryDate is read-only, so I'm not able to change this. Even then, I am confused as to how these ParseSession's work, as they don't actually store any cookies.
Should I just delete the ParseSession's that are automatically created on registration, and make my own cookie and session to deal with this, or does Parse provide an easier way?
Edit with code I have tried so far:
So far I have tried to do this without Parse, using PHP's own cookie functions:
$user = ParseUser::logIn($email, $password);
$_SESSION['mySession'] = serialize($user);
$_SESSION['start'] = time(); // Taking now logged in time.
if ($rememberMe) {
// End session in 1 month.
$_SESSION['expire'] = $_SESSION['start'] + (31 * 24 * 60 * 60);
} else {
// End session in 1 hour.
$_SESSION['expire'] = $_SESSION['start'] + (5);
}
$parseSession = $user->getSessionToken();
// Note I got stuck here as I realised the expiryDate is readOnly in the docs.
Note that this code right now isn't working as expected since the session I am creating using
session_start();
ParseClient::setStorage(new ParseSessionStorage());
seems to be creating a session that lasts only the browser session - but I will look into this and I believe/hope it's something to do with PHP storing the sessions (I checked the .ini and it said on Windows I need to configure it manually which I have not done yet).
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
On my website people earn points by seeing a page. They get 1 point for each second they keep the page open (the page keeps rotating Advertisements).
Some people have started exploiting this by opening that page multiple times all together and hence are earning more points! for example if the user open the page 10 times then he is earning 10 points for each second. I don't want them to earn more than 1 point per second.
How can I prevent the users from opening that page more than once at the same time?
Thanks in advance.
note : My website is php based.
I have on easy but not reliable way in mind:
Set a Sessionvar like
$_SESSION['user_already_on_page'] = true;
Now you can check for this variable and return an error page or something like that.
if($_SESSION['user_already_on_page'])
{
//maybe the user has left unexpected. to workaround this we have to check
//for the last db entry. Examplecode:
$query = mysql_query($_db,'SELECT LastUpdated FROM Pointstable WHERE U_Id = $uid');
$row = mysql_fetch_array($query);
if((time()-$row['LastUpdated']) < 5)
{
die("You are already on this page!");
}
//$_SESSION['user_already_on_page'] is set but the last update is older than 5 sec
//it seems, that he unexpectedly lost connection or something like that.
}
To unset this variable you could fire an AJAX-Script on pageclose that unsets this variable.
So your unsetonpage.ajax.php could look like this:
<?php $_SESSION['user_already_on_page'] = false;?>
And your JS-Part (using jquery):
$(window).bind('beforeunload', function(eventObject) {
$.ajax({url:'./ajax/unsetonpage.ajax.php',type:'GET'});
});
This should work.
Add the time when the page is opened to the database. Whenever the page is opened check if the difference b/w that time and current time is less than xx seconds then redirect the user. If the difference is more than xx seconds then update that time.
//--- You make session in startup called (my_form)
if (!empty($_SESSION['my_form']))
{
if ($_SESSION['my_form']== basename($_SERVER['PHP_SELF']))
{
header("Location:index.php");
exit();
} else {
$_SESSION['my_form']= basename($_SERVER['PHP_SELF']);
}
} else {
$_SESSION['my_form']= basename($_SERVER['PHP_SELF']);
}
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.