Laravel4 Validator, Captcha, & Session unable to match - php

I have a helper method that returns a captcha image url & stores a session of the key:
function captcha(){
$builder = new CaptchaBuilder;
$builder->build();
Session::put('phrase', $builder->getPhrase());
return $builder->inline();
}
The user then writes the captcha and submits the form and my controller grabs all and validates it:
'captcha' => 'required|same:'.Session::get('phrase')
The problem is no-matter what it always says they phrase & the textbox submission are not the same...
I can give more information if needed, also if this is not the best way to do it please give me suggestions, I am just learning Laravel4.
Edit for some output info:
If I return the values from the controller:
return "Session:".Session::get('phrase')." - Input:".$input['captcha'];
It returns: Session:5zij5 - Input:5zij5

According to Laravel's docs, same refers to another input.
I'd recommend using a custom validation rule to compare the session and the input.

Related

Validate symfony form without post

I an using the symfony form to create a form and validate it. But i want to pre-validate the form on page loading itself ie. validate the form without post. Is it possible to do it in symfony?.
I have tried to use $form1->isValid(); on the else part of post. But its not working.
Also I tried to use the submit(),
$data = $form1->getData();
$form1->submit($data);
$form1->isValid();
but with no success
*the form fields are dynamic and the validations are also dynamic. So a form that is preloaded can have error fields.
What you can do is for sure manual Entity Validation. I can imagine cases when you can't trust data already saved in database or, you want to pre-fill object with data from other source (external request response) before giving it for user to edit.
Please read docs about validation here: http://symfony.com/doc/current/book/validation.html
Possible code:
$author = new Author();
// ... do something to the $author object
$validator = $this->get('validator');
$errors = $validator->validate($author);
In this case you don't use constraints from FormType but validator constraints (they can be declared in entity - they will be used also by FormType): http://symfony.com/doc/current/book/validation.html#constraints

How to enable query builder for is_unique form validation in CodeIgniter?

I have a question about enabling the is_unique() rule for form validation in CodeIgniter.
In another explanation (link), they don't include the model query builder for standard usage of is_unique()
I need to use the rule is_unique(table.field) for my id field.
What should I do for making this function work on my model file to initiate table.field from my database? Because at documentation, I didn't see an explanation for enabling the is_unique rule.
My current code is still use matching data manually, but I need to know how to use this rules
$this->form_validation->set_rules('siteid', 'Site ID', 'trim|required|max_length[100]|is_unique[site_tower.site_id_tlp]');
I have just gone through the link you posted, There are 2 ways to use such validation. If you have set in your configuration files.
With that you can use the code as is is_unique[TABLE_NAME.FIELD] and it will work automatically. But at times this logic might not necessarily meet your need and you will need something more complex.
For example lets say you have a members registration that requires you to check if the email already exists, you can run is_unique and it will work perfectly. Now let's say you want to edit the same member, running is_unique on an edit function will render the user unable to save the data if no data is edited. WHY? because is_unique would determine that the email is already registered although it belongs to the current user that is being edited.
How do we fix this? We run our own callback in which we specify the logic.
You do it by specifying a method within the controller (or a model -- slightly different) but you prefix the method name with callback_ so that it is detected.
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
This will then look for a method in your controller called 'username_check'
public function username_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
Of course you can use a query within the callback to check against the db rather than check for just a string as it shows in the example.
more information can be found on Ci3 documentation.
LINK
Use CTRL + F and search for callback or is_unique
You might have missed this?
$this->load->library('database');
works instantly after adding database lib.

CakePHP - Controller or No Controller?

I am currently building a web app which has two models, Donor and Donation Models respectively. It has multiple user roles. When the staff user first registers a donor, I want him to be redirected to another form which allows him to fill in the Donation details(the donor is registered once the first donation is successful).
Firs of all, should I create a donation controller, from which I would redirect the user using:
return $this->redirect(array('controller'=>'donations','action'=>'add'));
For the above to work, it requires me to save the newly registered donor's id in a session like so :
$this->Session->write('id', $this->Donor->id);
So the user is redirected to 'donations/add' in the url, and this works fine.. However I think this has some flaws. I was wandering whether I should create another action inside the Donor controller called 'add_donation', which will have its respective 'View'. The idea is to be able to form a url of the sort : 'donors/add_donation/4' (4 being the donor_id ! )
This URL follows this construct: 'controller/action/id'
If anyone could shed some light on best practices, or describe any caveats to my solution(the former, using session etc.) , please do help a brother out! Ill be deeply indebted to you! Thanks in advance!
After you saved the data you can do this in the DonorsController:
$this->redirect(array(
'controller' => 'donations',
'action' => 'add',
$this->Donor->getLastInsertId()
));
There is no need to return a redirect, it's useless because you get redirected. Notice that we pass the last inserted record id as get param in the redirect. The redirect method of the controller calls by default _stop() which calls exit().
CakePHP3: There is a discussion about changing that default behavior in 3.0. Looks like in CakePHP 3.0 the redirect() won't exit() by default any more.
DonationsController:
public function add($donorId = null) {
// Get the donor to display it if you like to
if ($this->request->is('post')) {
$this->request->data['Donation']['donor_id'] = $donorId;
// Save code here
}
}
I would not use the session here, specially not by saving it to a totally meaningless and generic value named "id". If at all I would use always meaningful names and namespaces, for example Donor.lastInsertId as session key.
It's not always clear where to put things if they're related but the rule of thumb goes that things should go into the domain they belong to, which is pretty clear in this case IMHO.
Edit:
Leaving this edit here just if someone else needs it - it does not comply with the usage scenario of the asker.
If you have the user logged in at this stage, modify the add function to check if the userId passed is the same as the one logged in:
DonationsController:
public function add($donorId = null) {
// Get the donor to display it if you like to
if ($this->request->is('post')) {
if ($this->Auth->user('id') != $donorId) {
throw new InvalidArgumentException();
}
$this->request->data['Donation']['donor_id'] = $donorId;
// Save code here
}
}
You can use also the same controller using more models with uses.
Or you can also to ask to another controller with Ajax and morover to get response with Json.

How can I get the form data from the FOSUserBundle registration form?

I am using the FOSUserBundle and have overwritten the RegistrationController. When the form is submitted and valid, I want to get the email address the user entered in the registration form.
But I don't see any way to get it. As taken from the Symfony2 forms documentation, you can get form data like this:
$this->get('request')->request->get('name');
But the RegistrationController does not know the get() method (as it's not inherited from the Symfony2 controller entity). So I could go like this:
// Note the ...->container->...
$this->container->get('request')->request->get('name');
But this returns NULL. Now I try to get it from the $form.
// Does contain a lot of stuff, but not the entered email address
$form->get('email');
// Does also contain a lot of stuff, but not the desired content
$request->get('email');
$request->request('email');
// Throws error message: No method getData()
$request->getData();
Any idea?
It's really, really simple. You create a form with related entity. In FOSUserBundle you should have a RegistrationFormHandler, and in process method you've got:
$user = $this->createUser();
$this->form->setData($user);
if ('POST' === $this->request->getMethod()) {
$this->form->bind($this->request);
if ($this->form->isValid()) /**(...)**/
After the line $this->form->bind($this->request) every value in $user object is overwritten by data from form. So you can use $user->getEmail().
On the other hand you are able to get data directly from request, but not by the property name, but by form name. In FOSUserBundle registration form it is called fos_user_registration - you can find it in FOS/UserBundle/Form/Type/RegistrationFormType.php in getName method.
You get it by:
$registrationArray = $request->get('fos_user_registration');
$email = $registrationArray['email'];
If you were to use Controller as a Service (which should work with this), you could pass the RequestStack (sf >=2.4) in the constructor and do $this->request_stack->getCurrentRequest()->get();
My guess is that you are trying to get the POST data. You are trying to put the data in a form object I presume. I would recommend you to take a look at: http://symfony.com/doc/current/book/forms.html if you have a custom form.
As regarding to your question, the form is probably containing a name. If you want to have direct access to it instead of doing things in your form, you need to fetch it multilevel if directly via the true at $deep, get('registration_form_name[email]', null, true); You can also do $email = $request->get('registration_form_name')['email']; (if you have php 5.4+)

Clean html input in Codeigniter

HI guys,
I building an app using CodeIgniter and I came to a problem. I have a form with a textarea in which the user puts his text using a simple editor powered by jwysiwyg.jquery. The problem is that is need to clean this input of garbage code (link the one that comes with pasting directly from Word).
The form is validated with the form_validation library from CodeIgniter, with this rule:
array(
'field' => 'job[description]',
'label' => 'Description',
'rules' => 'trim|required|callback_clean_html'
),
Then I have a clean_html method that simply does a:
return strip_tags($text,'<a><p><br><strong><em><h3><h4><h5><ul><ol><li>');
The problem is that this is simply ignored and the original text gets inserted in the database. The method runs (I've tested). I asume it's because a callback should return TRUE or FALSE, but then xss_clean doesn't return a BOOL. The documentation isn't much help.
Any thoughs?
Thanks in advance.
I think form_validation callbacks do need to return a bool. I find that form_validation is most useful when you need to display an error message to a user usually to resubmit the form. Although the prepping functions can be convenient, they don't need to be there to validate. Why not pass the submitted string through the strip_tags function after the form is submitted but before you send it to your db?
Have you tried removing callback_ in the rule? You can do regular PHP functions like trim so this should work.
Something aI always do just to be double safe, after setting the rules for the input I also run them through this
`$string = filter_var($string, FILTER_SANITIZE_STRING);`
That will strip out the html
I too have run into situations lately where the input totally ignores the rules that have been set.
xss_clean and other CI validation functions return non-bool values. I just tested the following callback function in CI version 1.7.2:
function test_string_change($str)
{
return "$str **";
}
The string was changed successfully using callback_test_string_change. I know there were some issues with the callback functions in 1.7.0, are you using the latest version?
From what you posted, it should work. Both the "callback_" prefix and the return are correct. Validation methods can return non-bools, which will replace the value. Check the form_validation documentation, it explicitly says that.
So your problem must be in some place of the code that you didn't post.

Categories