Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Store session inside Controller


Reply


4 Posts   416 Views

Avatar
folibis

Community Member, 10 Posts

3 December 2013 at 1:16pm

Edited: 03/12/2013 4:21pm

http://www.sspaste.com/paste/show/529d15c90b2f7

I have a Controller with 2 functions - PostForm() and doPost(), to show form and to handle POST action accordingly. In my form I want to add my own field, something like captcha. I store current time in session and add this value to the form as hidden field.
After posting the form I compare session and POST values. But in my case these values always different. After some logging I found that after posting the form, PostForm() called just before doPost() to obtain form fields, I guess, so my session value rewrited.
And my question - how can I avoid this behavior? To store session in some private place? or to add condition based on URL?
All advices are welcome!

Avatar
Devlin

Community Member, 217 Posts

3 December 2013 at 10:22pm

First, the submit method won't be called unless all fields are validated... So the your goal should be to create a new MyCaptchaField class and add your logic and validation there.

Something like:

class MyCaptchaField extends HiddenField {
   function FieldHolder() {
      $field = parent::FieldHolder();
      // add logic
      return $field;
   }

   function validate($validator) {
      // add logic
      return true;
   }
}

Or to avoid your issue, you'll need to check if the field has a value of your previous form submit first.

$captchaField = new HiddenField("captcha");
if (!$captchaField->Value()) {
   $captcha = time();
   Session::set('captcha',$captcha);
   $captchaField->setValue($captcha);
}

But I've to advise to you, that what you're trying to accomplish is already covered by the security token... which you disabled.

Avatar
folibis

Community Member, 10 Posts

4 December 2013 at 12:26pm

Thank you Devlin for you interest.
In my case security token is not enough just because is it not difficult to parse it by some spam engine. I want to disallow comments posted in 60 sec after page was loaded. so I store time in session and check it on form sibmittion. Hidden field here is not so necessary, just one more verification.
Let's say there is no hidden field, just session.

Avatar
folibis

Community Member, 10 Posts

4 December 2013 at 4:59pm

Edited: 04/12/2013 5:00pm

Ok, I did it with dirty hack:

public function PostForm() {
if(strpos($_SERVER["REQUEST_URI"],"PostForm") === false) {
Session::set("captcha",$captcha);
}
...
}