Form::file: How to repopulate with Input::old After Validation Errors and/or on Update? - php

In my PhotosController, I am trying to modify the edit action so that it shows the existing value in the Form::file() input field (and, so that it repopulates the field if validation fails).
if ($validation->passes())
{
// saves the image on the FS and updates the db entry
}
return Redirect::route('photos.edit')
->withInput(Input::all())
->withErrors($validation)
->with('message', 'There were validation errors.');
The uploading process works fine, but when I view an existing record, or if validation fails upon creation, the Form::file doesn't show the value. I looked up the method in the api, and it only accepts the name and optional options arrays. Whereas, the other methods in the FormBuilder class allow us to set the value using Input::old().
I've tried passing in the following values to withInput, but they've been to no avail:
* Input::all()
* Input::old()
* Input::except('photo_path')
* Input::get('photo_path')
How can I update this so that if validation fails, or if a user views an existing record, the Form::file() method will show the existing value?
I'm sure that I'm overlooking something incredibly simple because I haven't found other threads of people asking this...

Apparently you can't.
Browsers don't allow you to set a value on a file input for security reasons.
There are two silimar questions, not laravel related but i think answers could help you:
Can you re-populate file inputs after failed form submission with PHP or JavaScript?
Restoring the value of a input type=file after failed validation

Maybe your best shot would be to make the validation client-side (javascript/jquery).
Of course there has to be (ALWAYS) server-side validation. (remember javascript can be disabled on client-side).
But I believe that, this way 99.99% of the cases, the form submission will be successful!
Basically, when is indeed submit, it is already validated with sames rules as the servers, so it will not submit until it is not "as the server likes" :)
Cheers

For complex form submits I would recommend to use AJAX:
You may do a first AJAX form send that does the server side validation.
Then, if it's all fine you should launch via Javascript the form POST with file input.
I've answered a similar question for Laravel there but I hope it will be helpful for a general approach: Laravel 5.1: keep uploaded file as old input

Remove the redirect, your validation and input values should show on the same page, only redirect upon success.

Related

Ensure that PHP form process file is only used with specific web form page?

I am a little new to PHP, and I have gotten in the habit of creating a specific file that handles all the form processing.
For example, I have one PHP file that displays the actual form, let's called it "registration.php" for example, and it specifies as its action "registration-process.php". A user fills out the registration form on registration.php, hits submit, and the data is POSTed to registration-process.php because it was specified as the action file by the form.
Now my question is this: Can't someone who knows what they are doing POST data to registration-process.php without going through registration.php? This would have the potential to lead unexpected consequences.
Is there any way to ensure that registration-process.php will ONLY accept POSTed data from registration.php? Like maybe a hidden field with a value that gets encrypted via some PHP code, and that value gets checked by the registration-process.php file? I wouldn't know how to do that, however, or if that's even the best solution.
Yes, using a hidden "security token" field is a common way to verify a forms integriy. Many public forums are using this method.
Try Google for php form security token or check out this site:
http://css-tricks.com/serious-form-security/
Can you only accept POST data from one location, probably. It is worth it, probably not.
As long as you are validating your form fields correctly (make sure what you're getting is within the realm of what you're expecting) there won't be any negative consequences of leaving it so anything can POST to it.
Also, technically you can send POST data to any file on the web, it just depends on what the file does with it whether or not it means anything.
Also, what Mario Werner is talking about is CSRF tokens. That won't stop other things from posting to your site, it just adds a level of security that makes sure the request came from the right place. For a detailed explanation, you can read this: http://en.wikipedia.org/wiki/Cross-site_request_forgery

How can I validate two models in one Form separately via ajax

I need to implement the following work flow.
User types in an url
User clicks "validate"-button
url is validated (not empty and existent) via ajax.
If the url is valid, some informations should be parsed automatically from the given site and fill some form fields on the same page.
Those form fields also needs to be validated (some fields are required) via ajax.
If all required fields are filled the user can hit a save button. Elsewise he is prompted to fill out all remaining required fields.
What is the best way to achieve this?
The url field and the form fields are two diffrent models in one form, cause for saving I need both.
Most of the work flow I already implemented, but I`am not sure if this is the correct way. I enabled the ajax validation for my form. The url field is validated correctly, but the other fields not eveny trigger the validation. Maybe cause those fileds are packed in an bootstrap active form?
After clicking the "validate"-button I trigger an own ajax request, where I validate the url manually. If its valid I parse the page and return all found informations, elsewise I return the errors. The success method than shows the errors or fill the other form fields.
Is there a way to trigger the yii ajax validation programmatically before send my own ajax request.
Now I´am stucked with the ajax validation of the other form fields. Submit, validate and save on success works well. But I want a validation without submitting.
Do I have to implement my own ajax request and response handling or is there a way to use some yii built-in functionality?
Let's say you have a form with some fields:
Make the save button be disabled.
Have a listener that listens for changes in the fields.
Have a unique function that can validate each field and make it return a boolean.
Enable the save button if the boolean values for all the validations are true.
It's also a good practise to
have a div that you can load messages into, so that the user is aware of his mistakes / non-valid fillouts.
And note that
You don't need Ajax unless you're performing some database functions in the backend.
You can have a validate button instead of the listeners if you want.
Am I misunderstanding you?

Saving form data when POST submission is not validated

I need to validate a form in php and display some error messages in the view if there are validation errors. The problem is that once the form is submitted, sending the user back to the page will clear all the of the completed form fields. Is there a simple way to not lose the unvalidated form data?
The only solution I can come up with is reverse engineering the $_POST variable, but I'd like a more elegant way to do it.
Don't send the user anywhere, but re-render the form right where you are, pre-populating the form with the entered values. That would be the most common method.
The second way would be storing the values in session variables, but that should be the last resort if the project structure doesn't allow for the first approach.
Validate on the client side.
If you must validate on the server side, made an ajax call (so you won't have to refresh the page) to the server with the elements you want to validate. Make the validations you need and return an answer back to the page (is valid or not).
If answer is valid, you can proceed (Note: you may not need to return to the page after the validation, if all the elements you need to proceed are also the ones validated).
If it's not valid, the answer should return the invalid elements (and possibly a error message for each) so that you can display the error messages you want.
If in php code that you use to prepare the form you always set field values to whatever exists in $_POST array, then in validation code you can simply conditionally include that form file and it will render itself with user values. When you render the form the first time (empty form) $_POST will not have elements with field names, and the form will be empty.

i want to add captcha with ajax

well i have a form in which email and captcha validation was there but now i want to do some thing like if captcha is incorrect or left empty than my form must not reload the page i.e all those field which are already been filled out must not get blank.
You can either
A) Submit the form as you are doing right now, and fill the fields with the existing field data
B) Use a CAPTCHA library that supports AJAX submission, e.g. reCAPTCHA http://wiki.recaptcha.net/index.php/Overview#AJAX_API
I believe that (A) is a lot better because it allows you to deal seamlessly with all other kinds of validation. But depending on what you already have (B) might be trivial to implement. So YMMV.

Trying to validate captcha with javascript before sending to php form validation

Hi I'm a relative newbie.
Have a mail contact form set up with a captcha image generator.
When the captcha is verified, on submitting the form, a php page is actioned which further validates the input data (checking against spam).
Challenge: would like to retain form data in case of error in enterred capthca code and needing to return to form.
If I use a sticky form with the form sticks okay but I cannot see how I then direct http to the php script for form data validation.
So I figure the answer is a javascript function to validate the captcha and stay within the same page where the form appears, ideally just having a pop up message (alert ...) if the enterred code is wrong, before sending the http to the php script page.
I have seen that this can be done but I cannot adapt the code to the captcha I use (i.e. webspamprotect.com) Could any body suggest a generic js function useable with any captcha ?
Would be most grateful for any input.
MANY THANKS
Steve
It doesn't make sense to be able to validate the CAPTCHA with javascript on the client. If you made it possible to validate with Javascript a scammer could use the validation function to test their guesses before they sent them to the server, so they would always be able to get the answer right.
You could implement an AJAX call requesting the server to validate the attempt instead of requiring a full page refresh, but the validation must still be done on the server.
When the captcha is generated the written word is usually stored inside the session or written into a hidden input field, so it can be validated against the user supplied word, when the form is submitted back to the PHP script.
You could pass the session variable holding this to your JavaScript (or read it from the hidden input if present) when rendering the page holding the form and captcha. Then, when the user clicks submit, intercept the call and check if the entered word matches the expected word.
As for retaining the values: just add the values to your HTML form value attribute. Make sure you escape the output in case users supply malicious code.
EDIT: agreeing with everyone who says you still have to validate the input on the server side as well. Client Side validation can easily be tinkered with and is nothing but a convenience feature for users, so they can fix their input before submitting.
simply check the value of "g-recaptcha-response"
if($('#g-recaptcha-response').val()==''){
alert('captcha not ticked');
}else{
alert('captcha ticked');
}

Categories