Implementing a 'Remember me' function - php

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

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

how to check when the session was set

hello i would like to know at what time any particular session was set or started ?? is this possible by php
i know session set or not can be checked by
if(isset($_SESSION['name'])){
/////////////
}
but here i want when the sessoin was started so that
if($_SESSION['name'] // started on date is greater then last 5 minutes
){
// do this
}
When you start the session you could save when it was started in the sesson.
session_start();
$_SESSION['startDate'] = date();
The code will change on how you want to store the date but that the crux of it. If you want to know when you set exactly $session['name'] you could use an array to store the name data with the date.

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.

Keeping users logged in without cookie

I was wondering if there was any other way to keep users logged in when they revisit my website even though the session has expired.
I currently use a cookie based method, but I was wondering if there were other methods people are using.
No, there are no [reliable] methods beside a cookie.
There are other methods, but you should refrain from using them because they in no way are as reliable as cookies.
You can use a IP based login system. If using this, you will see issues with multiple users from same IP.
You can generate a special link for users that is uniquely generated and make a login based on that
Instead of worrying about doing it another way, you should work on making your cookie-using system more secure.
This is a very old question, but for the sake of future visitors, I would like to supply an answer.
You SHOULD use cookies. Like the other answers have noted, they are the most reliable method out there. If you want to make sure the user isn't visiting with an expired cookie, write the time at which it expires as a cookie with a checksum.
Here's an example using PHP:
$expireTime = time() + (60*60*24*3); // 3 days ( 60 seconds * 60 minutes * 24 hours * 3 days )
$rawPepper = openssl_random_pseudo_bytes(16);
$hexPepper = bin2hex($rawPepper);
setCookie($cookieKey, $cookieValue, $expireTime);
setCookie("expiresWhen", $expireTime, $expireTime);
setCookie("rand", $hexPepper, $expireTime);
$hash_1 = hash('sha512', "Your_Super_Secret_Salt" . $cookieValue . "Another_Super_Secret_Salt!" . $expireTime);
$hash_2 = hash('sha512', "Yet_Another_Salt!" . $hash_1. $hexPepper);
setCookie("checksum", $hash_2, $expireTime);
Then in your other PHP form for validation you say:
$expires = $_COOKIE['expiresWhen'];
$pepper = $_COOKIE['rand'];
$cookieVal = $_COOKIE[$cookieKey];
$givenCheckSum = $_COOKIE['checksum'];
$hash_1 = hash('sha512', "Your_Super_Secret_Salt" . $cookieVal . "Another_Super_Secret_Salt!" . $expires);
$correctCheckSum = hash('sha512', "Yet_Another_Salt!" . $hash_1. $pepper)
if($givenCheckSum != $correctCheckSum){
/* user's cookie has expired. Handle as you please */
}else{
/* Cookie is still valid */
}
Anyone care to make corrections to this or supply suggestions?

Categories