Logic behind validating form info with PHP - php

Im trying my first form validation with PHP.
I need some guidance with the logic.
I have purchase.php (which has the form) and review-purchase.php(which sets SESSION variables and displays the user data inputted)
If any of the fields fail validation I don't want the user to get to review-purchase.php
Should I be sending the user to the review-purchase.php script, checking validation there and then redirecting back the purchase.php with an error message?
or
should I be using an if/else statement with $_SERVER['php_self'] etc in the form action="" and keep all the validation on the purchase.php page itself and only letting purchase-review run if everything passes validation?
Sorry for the confusing question but i myself am very confused...

That's a question many people ask themselves, and there is probably not one right answer...
What I generally do, in your case, is :
purchase.php displays the form
that form posts on itself (ie, purchase.php)
when data has been submitted, it is dealt with -- still in purchase.php
if there is an error (like something not OK in the input), you can re-display the form really easily, this way : you already have every values that were typed in by the user
if there is no error, you can do whatever you have to with the data ; like set it in session, if that's what you need, or save it to database, for instance.
only when everything was OK (data validation OK and storage OK), you redirect to "confirm.php"
that confirmation page does nothing except display a message saying "thanks for your purchase", or something like that.
It means putting more stuff in your purchase.php, yes :
(re-)displaying of the form
dealing with the input
But, this way, it is really easier to re-display the form, pre-filled with what the use first typed, when there's a validation error.
You can use functions/classes/methods or even some included files, though, to not end up with one big chunk of un-readable / un-maintenable code...
If your form posts to another page, it'll be really harder to re-display the form... If you are using redirections, you'll to pass everything in the URL, and it'll be a mess (And there's a size limit, too)
Here, it means I would totaly remove your review-purchase.php file ; and transform it to a confirmation page, so the user knows everything was OK and his purchase is being take care of.
I suppose it's quite what you meant in your last paragraph, actually :-)
Just beware : you have to think about escaping data before injecting it back into the form (see htmlspecialchars and/or htmlentities) ; that is true for everything you get from the user (And, probably, for PHP_SELF too, I'd say) ;-)

Well, it seems you have a misconception about where and when PHP code is executed. If you want to validate user input on the server side - with PHP (and you should because any JavaScript validation on the client can be worked around by a nefarious user) - the PHP validation can only occur after the user has posted data. That is no matter to which page the user posts the data - be it the original form or a different page.
So, in your situation if you want users to go to a page if validation is successful and to a different page is validation fails yo will need to do a redirect anyway.
In this case you have two paths:
user requests Purchase.php and fills out the form
user posts data to validation page
if data is valid -> display purchase review information
else -> re-display form page and have user re-enter data
So if Purchase.php posts to itself, you can validate there and redirect to review.php only if data is valid. Which means that in the successful case you do 2 redirects and in the failed case you do only 1 post.
On the other hand, if you post directly to review.php and you validate there, you have 1 post in the successful case, and 2 in the failed case.
The above is true no matter how you spin it - unless you use the same URL for the form and the review, in which case you can put logic in the same place to do the form, validation and purchase review in the successful case.
I hope this helps.

The most common way of doing this would be to do all your validation checks in purchase.php. This way, if there are validation errors, it's easier to re-display the form with all of the information that the user has already entered.
If the validation passes, you can do a redirect to review-purchase.php with the necessary purchase information set in a database, or possibly $_SESSION if you're not using a database.
If you can separate the validation code into functions, and the display code into templates to be included, you can achieve a nice separation of logic that would allow you to use them from whichever file you go with. You might be able to avoid a redirect in that way, ie. in purchase.php you could check if there's $_POST input, validate it, and either re-display the form template, or display the purchase review template.

Related

Keeping track of data in multipage form validation through PHP

I am working on a PHP project where the client wants multipage form data submitted. For instance, here is the process the form follows:
Create new entity.
Determine entity type.
Fill in entity-specific fields.
On each page, the form is POSTed to the current page. Validation is performed server-side, and if validation is successful the user is redirected to the next step.
I've determined that, in order to keep track of the user's progress, session data should be used. However, my concern is that, if the user opens two tabs and goes through the form in parallel, how can I keep track of what entity is being processed in each tab? Is this a scenario that can even be handled at all?
There are different 2 approaches.
If a user allowed to fill 2 forms at once, just add an unique identifier to each, and keep track them in the session.
If not - the things become simpler: just keep track of the steps passed and just show a warning in case of the previously passed step submitted.
This is a page flow issue. Do NOT use session to deal with it. You are correct that tabs or new windows would cause you trouble.
I don't really understand the point of this bit:
On each page, the form is POSTed to the current page. Validation is
performed server-side, and if validation is successful the user is
redirected to the next step.
Sounds like a "post-back", but why? POST the data from the page to a controller (or script) that does the necessary ss validation. After validation, deal with the data how you need and determine what the next step should contain. Then send the input form for that next step down in the response. Repeat until you are finished.

How do I organize my code when developing forms to meet the following requirements?

I'm simply trying to figure out the correct way to lay out the architecture for my forms to meet the following requirements:
The form must have server side validation.
If a user is filling out a form on domain.com/register and the form doesn't pass server side validation, they should be brought back to domain.com/register with the errors displaying.
(continued from point #2) If the user is brought back to domain.com/register to fix validation errors, the data they have already entered in to the inputs should automatically display.
If a user clicks back or forward on the form page the browser should not throw the "Confirm Form Resubmission" warning.
I'm a bit confused on where the form submit should be posting to. Should the form on domain.com/register post to a different page that simply handles the validation? If so, how do I pass the validation errors and inputed data back to domain.com/register?
Or, should the form be posting to itself? If so, how do I prevent the browser from throwing the "Confirm Form Resubmission" warning when clicking the back or forward button?
A logical way of approaching this (that attempts to keep all related items as localised as possible), would be to use a single page that has a "mode" switch statement near the top with an "update" case in it that contains your validation code.
Within the form, you'd simply post to the same page that you're on, but you'd add a hidden field in the form called "mode" with a value of "update". As such when the form is submitted execution will flow into the "update" case of your switch statement and you can carry out the required validation.
If the validation succeeds, you'd usually kick forward to another page (via the use of header('Location: ...'); followed by exit();) and if validation fails, execution will simply continue down the page at which point you should output the errors that occurred during the validation.

Does this protect me against page reload and the back button?

Further to my previous question, here's what I decided to implement; it may not be pure P-R-G, but it seems ok. Care to comment?
The form.php has an action; let's call it validate.php.
validate.php is never seen by the user; if validates all $_GET and, if valid writes it to database and generates the HTML of a confirmation page / if not valid, it generates the HTML of an error page explaining what is wrong.
Whichever HTML is generated get stored in a $_SESSION variable and then validate.php does a header('Location: <as appropriate>);
Finally a page called submitted.php of invalid_input.php (in case the user reads the URL) consists only of echo $_SESSION['form_html'];
That seems to me like is proff against both page reload and back button problems.
Or did I goof by trying to reinvent the wheel?
Firstly, you're better off storing the form data, which means you can perform the validation again. It will also be less html. The problem with the method you're employing now is that it doesn't protect against multiple tabs, since $_SESSION is universal to a browser session.
One way I've used to prevent against duplicate submission (without PRG) is to generate a unique id for every page load (where a form is involved). When I generate that unique id, I add it to a $_SESSION['form_unique_ids'] array, and I include it as a hidden field in every form I generate. Then before I take action on a form submission, I check to see if that unique id is in the session. If it is, this is the first time that form has been submitted, and I remove it from the session. That way if I try to resubmit that page, I will know because that id is not in the session not to process the results.
This could be extended so that instead of storing a single id, you use the id as the key in the array, and let the value be the result of the transaction. Then:
If there are errors, you store the $_POST data as well. Then, redirect to original_form.php?id=unique_id and display the validation results. You can either store them or recalculate them there.
If there is success, store the success message and redirect to success_page.php?id=unique_id. Display the success message prominently there. If you like, you can remove it from the page.
You have the option of removing the session data when you display it, but that would mean if they refreshed the edit page they'd lose the validation messages and saved form data. I'd rather find a way to get rid of data that is old enough that they're not likely to need it anymore.
Anyway, some of those ideas might be useful. Then again, maybe it's way too much effort for the problem. Your call :)
As long as you use a php redirect at the end of your validate you cannot reload or back button into the validate.php

How do I control flow of PHP multi-page form?

I am a bit of a PHP newb
I have developed a multi-page form which works fine at the moment - each stage is on another page (I use the session to retain the data).
However I know that users don't always use these forms the way you want!
I want to control the flow of the form.
I would like the user to be able to use the browser back & forward button for ease of use.
They should not be able to skip a part of the form by entering a form stage URL directly into the address bar to get the a later stage in the form (essentially skipping a part of the form).
The form also does not flow the same path every time, it is dependant on the users choices what stage is displayed next.
I was wondering if anyone had any ideas of ways to control the flow of this multi-page form thank you!
store form results in SESSIONS (encrypt them if sensitive)
then just check on each form if the value is set and show it as necessary.
use another session to check the "progress" of the form, to prevent the user from skipping ahead.
for example...
<?php
/* on form 3 */
if(isset($_SESSION['progress'] && $_SESSION['progress']==2)
{
//the second form has been filled out and validates
}
else
{
// the 2nd form hasn't been finished, redirect
}
?>
you could also use like a percentage based system in the session - a value of 90 means that 90% of the form fields have been completed - for displaying "progress" in a visual means to the user.
basically on every form submission, check whats been submitted, if its expected, then set appropiate sessions to redirect to the next stage.
check every set session on every form to determine if the user should be here yet.
Push the data for the non-current fields into a hidden field in the browser (to save time and effort - just serialize an array/object).
I would like the user to be able to use the browser back & forward button
If users are allowed to re-enter previous stages, just let them and rewrite current stage in the session.
If not, make form fields read-only and do not process submitted forms for the previous stages.
That's the only problem I can see here.
You can either use session data to retain the state between multiple pages, or you can transfer all data on each page. Typically you would do the latter with hidden fields or you will create one humonguous form, and use javascript to make it appear as if it was multiple pages, when - in fact - it's not.
There are pros and cons to each solution.

php form submit and the resend information screen

I want to ask a best practice question.
Suppose I have a form in php with 3 fields say name, email and comment.
I submit the form via POST. In PHP I try and insert the date into the database.
Suppose the insertion fails.
I should now show the user an error and display the form filled in with the data he previously inserted so he can correct his error. Showing the form in it's initial state won't do.
So I display the form and the 3 fields are now filled in from PHP with echo or such. Now if I click refresh I get a message saying "Are you sure you want to resend information?".
OK.
Suppose after I insert the data I don't carry on but I redirect to the same page but with the necessary parameters in the query string. This makes the message go away but I have to carry 3 parameters in the query string.
So my question is:
How is it better to do this? I want to not carry around lots of parameters in the query string but also not get that error. How can this be done? Should I use cookies to store the form information.
Your first scenario seems the most valid.
i.e.
User submits the form
Some problem prevents submission, so form is re-displayed
If user "refreshes" they see the usual message about re-sending information (although their most likely path of progression is to re-submit the form that you are kindly re-populating for them).
The "Are you sure you want to resend information?" message is perfectly valid in the event of someone refreshing the page after a form submission, so don't write code to specifically break this behaviour.
I think generally people would temporarily store the submitted data in a session variable, and send the data back to the client.
Maybe it is besides the point but you mentioned "wrong dates", and I think many would say you should arrange things so that the user cannot unintentionally send you wrong dates.

Categories