Symfony: temporarily storing a count - php

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*/
}

Related

Issue setting cookies

I'm trying to set cookies for the first time. I've been following the documentation on W3 schools but it doesn't seem to be working for me.
Here is my code (some naming omitted for this example):
$namenospace = 'thisnameexample';
function someSetup($somename){
$nameofcookie = $somename . '_some_value';
if(!isset($_COOKIE[$nameofcookie])) {
$someValue = rand(1, getrandmax());
$cookielastsfor = time() + (86400 * 30);
setcookie($nameofcookie, $someValue, $cookielastsfor, "/");
}
else {
$someValue = $_COOKIE[$nameofcookie];
};
return $someValue;
};
$setSomeValue = someSetup($namenospace);
As you can see, I'm trying to check if a cookie is set, if it is, grab the value and use it, otherwise, set the cookie, then return the value anyway.
For some reason this setcookie() function isn't working. Does anyone have any insight on this?
Possibly worth noting this is a wordpress site if that's relevant?
Thanks!
Edit: have updated as per scope issues highlighted in comments and still not working as intended.
Edit again: definitely not a duplicate. My team and I discovered the issue and would like this unmarked as duplicate so an answer can be given please!
Make sure you are setting your cookies before output. Where are you calling your function?
As an alternative, you could use JS to set a cookie on client side.

Implementing a 'Remember me' function

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).

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.

Drupal 7 temporary cache item won't expire

I have a fairly expensive server call that I need to cache for 30 seconds. It seems however that I can not get the cache to expire.
In the code below, after the first time it caches, it will never get past $return->cache_data, even after the time() + 30 seconds.
Note, I can even print $cache->expire and it is definitely set to a time past 30 seconds ago and never updates.
I've manually cleared cache many times to confirm I get the same results.
Does anything look wrong with this?
function mymodule_get_something($id) {
// set the unique cache id
$cid = 'id-'. $id;
// return data if there's an un-expired cache entry
// *** $cache ALWAYS gets populated with my expired data
if ($cache = cache_get($cid, 'cache_mymodule')) {
return $cache->data;
}
// set my super expensive data call here
$something = array('Double Decker Taco', 'Burrito Supreme');
// set the cache to expire in 30 seconds
cache_set($cid, $something, 'cache_mymodule', time() + 30);
// return my data
return $something;
}
There's nothing wrong with your code as such, I think the problem is in how cache_set behaves. From the docs page, passing a UNIX timestamp:
Indicates that the item should be kept at least until the given time, after which it behaves like CACHE_TEMPORARY.
CACHE_TEMPORARY behaves like this:
Indicates that the item should be removed at the next general cache wipe.
My best guess is that because you're not implicitly forcing that general cache wipe (using cache_clear_all()) the cache object will persist.
I think a simple way around it would just be to manually test the expiry time after your cache check, and let it fall through to re-setting that cache object if it has expired:
if ($cache = cache_get($cid, 'cache_mymodule')) {
if ($cache->expire > REQUEST_TIME) {
return $cache->data;
}
}

Resin Session in Google App Engine

I'm developing on GAE using Resin, it seems that my PHP session on the production site is short lived and doesn't get updated (i.e., making requests doesn't seem to increase it's expiry period). Local is fine, as long as I don't close the tab, the session persists.
Any pointer on this? My users are getting frustrated as they are kicked very frequently :(
I think the code is the best tutorial :)
// global mem cache service handle
$MEM_CACHE_SERVICE = NULL;
// table to store session like information
$MY_SESSION_TABLE = array();
function load_mcache($key) {
global $MEM_CACHE_SERVICE;
if (!$MEM_CACHE_SERVICE) {
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.memcache.Expiration;
$MEM_CACHE_SERVICE = MemcacheServiceFactory::getMemcacheService();
}
return $MEM_CACHE_SERVICE->get($key);
}
function save_mcache($key, $value, $cache_time) {
global $MEM_CACHE_SERVICE;
if (!$MEM_CACHE_SERVICE) {
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.memcache.Expiration;
$MEM_CACHE_SERVICE = MemcacheServiceFactory::getMemcacheService();
}
$expiration = Expiration::byDeltaSeconds($cache_time);
return $MEM_CACHE_SERVICE->put($key, $value, $expiration);
}
// unserializing array from mem cache
// if nothing found like first time and after a minute, then add key to the table
if (!($MY_SESSION_TABLE = unserialize(load_mcache($_REQUEST['JSESSIONID'])))) {
// save something to cache on first page load because we didnt have anything
$MY_SESSION_TABLE['key1'] = date('m/d/Y H:i:s');
// using jsessionid as a mem cache key, serializing array and setting cache time to one minute
save_mcache($_REQUEST['JSESSIONID'], serialize($MY_SESSION_TABLE), 60);
}
// now my session table is available for a minute until its initialized again
print_r($MY_SESSION_TABLE);
Now for proper session functionality you need to add set and get methods or even better a small class for handling it. Little abstraction to the classes and you could choose what kind of session mechanism to use with same library on different web app scenarios.

Categories