Server Side Code Firing

A Typical PHP application works in the following way :

  • Creation of a Form
  • Creating an extra hidden field in the form
  • on Submit validate the form
  • At the end of the validation if everything is fine then set that hidden field as true
  • and then submit the form
  • on the Top of the php page check if that hidden variable is true
  • if True then fire php code otherwise normal load the form

This approach is a bit difficult to use in case of large and complex applications as it will end of with several if conditions if in case you have a common top.php file.

SO what is the other solution

Validation is split into two areas - Client-Side validation and Server-Side.

Server-side validation is required, client-side validation isn’t required - a user can simply turn off JavaScript or bypass the functions through the address bar using javascript commands.

So, rather than the hidden field, simply have the client-side validation on the onsubmit:

<form method="..." action="..." onsubmit="return validateForm();" />

If the client-side validation fails, that validateForm() function only needs to tell the user and then return false and the form won’t be sent.

It’s important to state (again) that client-side validation can be bypassed, whereas server-side cannot.

So the flow would, in fact, be:

  • On submit:
    [LIST]
  • If JavaScript is enabled:
    [LIST]
  • Validate fields.
  • Return true if validation passes, false otherwise and exit the flow
    [/LIST]
    [/LIST]
  • Form is submitted to PHP
  • PHP validates the form and redirects to a success page on success. If it fails, show the form again with the given errors.

my question is not about validation - my question is about when to fire php code.

Is this a good technique of checking if condition on the top of the page and then redirecting to a php function

I was just making sure you do have server-side validation in place, and clarifying my point :slight_smile: The hidden variable idea isn’t at all required.

But yes, that is a valid technique. My forms generally submit to the same request (e.g. a form at /members/register/ submits to /members/register). It also allows you to show the form with errors if it fails validation.