Page 1 of 1

Redirect with predefined user errors

Posted: Mon Dec 24, 2012 2:17 pm
by nbasso713
So I'm currently finishing up an upload area on my site that uses both JS and PHP validation. While validating the user info server side, if an input was entered incorrectly I would like to send my user back to the upload page with the respective error(s).

If there's an error:
upload.php -> process_upload.php -> upload.php w/ errors

What's the best method to achieve this?

Re: Redirect with predefined user errors

Posted: Mon Dec 24, 2012 7:01 pm
by requinix
It's easier when the upload form and the processing code are on the same page. The two most common options:
1a. Move the processing into upload.php, with appropriate logic so that the form isn't processed on the first page view. If there's an error then abort the processing and fall back to displaying the form (with messages).
1b. Keep the files separate but make upload.php include process_upload.php. Form goes to upload.php, process_upload.php defines a function or simply executes code to handle the form.
2. Dedicate a special place in the $_SESSION for errors regarding this form. upload.php displays them if present, process_upload.php sets them on error and redirects to upload.php.

If you're wondering, you can't do "sticky forms" with file uploads. Either the user has to reselect the file or you do some clever handling by sticking the uploaded file someplace temporary and giving the user the option to reuse that file.

Re: Redirect with predefined user errors

Posted: Mon Dec 24, 2012 10:45 pm
by Christopher
I agree with requinix ... good description. In general, forms of all kinds should submit to themselves. If there is an error then an error message is displayed. If they succeed, then redirect to a success page. This also solves the refresh/resubmit problem.

Re: Redirect with predefined user errors

Posted: Tue Dec 25, 2012 12:12 am
by nbasso713
Thanks guys, this helps a lot. Merry Christmas!

Re: Redirect with predefined user errors

Posted: Fri Dec 28, 2012 9:41 pm
by twinedev
Down and dirty self submitting form with validation.

Note: DO NOT submit form to $_SERVER['PHP_SELF'] as this can open you to XSS issues, either specify the URL, or leave blank (action="")

Code: Select all

<?php

$aryData = array('Name'=>'','Email'=>'','Comments'=>''); //array of form data (default to empty values for the form inputs)
$aryErr = array(); //array of form errors

$bPosted = (count($_POST)>0);

if ($bPosted) {
  //form was submitted
  foreach($_POST as $key=>$val) {
    if (preg_match('/^(txt|drp|hid|chk|rad)([A-Z][a-zA-Z0-9-_]+)$/',$key,$regs) && array_key_exists($regs[2],$aryData)) {
      $aryData[$regs[2]] = (is_string($val)) ? trim($val) : $val;
    }
  }

  // Begin validation
  if ($aryData['Name']=='') {
    $aryErr['Name'] = 'Name is required';
  elseif (strlen($aryData['Name'])<4) {
    $aryErr['Name'] = 'Name must be at least 4 characers';
  }
  if (!preg_match('/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i',$aryData['Email'])) {
    $aryErr['Email'] = 'Invalid E-Mail address';
  }
}

$bHasErrors = (count($aryErr)>0);

if ($bPosted && !$bHasErrors) {
  // Form pass validation.

  /*** send mail or save to database ***/
  /* Be sure to use mysql_real_escape_string() for mysql_ functions or else use PDO */
}

function echoError($key,$prefix='<span class="error">',$suffix='</span>') {
  global $aryErr;
  if(isset($aryErr[$key])) { echo $prefix,$aryErr[$key],$suffix; }
}

function echoHSC ($text) {
  echo htmlspecialchars($text,ENT_QUOTES); 
}

?><html>
<head><title>Test Form</title></head>
<body>
<h1>Test Form</h1>
<?php if ($bPosted && !$bHasErrors): ?>
  <p>Thank you for submitting your info. Something will be done with it at some point.</p>
<?php else: ?>
  <form action="/test-form.php" method="post" id="frmTest">
    <ul>
      <li>
        <?php echoError('Name'); ?>
        <label for="txtName">Name</label>
        <input type="text" name="txtName" id="txtName" value="<?php echoHSC($aryData['Name']); ?>" > 
      </lI>
      <li>
        <?php echoError('Email'); ?>
        <label for="txtEmail">E-Mail</label>
        <input type="text" name="txtEmail" id="txtEmail" value="<?php echoHSC($aryData['Email']); ?>" > 
      </lI>
      <li>
        <!-- Was no validation on Comments -->
        <label for="txtComments">Comments</label>
        <textarea name="txtComments" id="txtComments"><?php echoHSC($aryData['Comments']); ?></textarea>
      </lI>
      <li>
        <input type="submit" name="submit" value="Send Comments">
      </li>
    </ul>
  </form>
<?php endif; ?>
</body>
</html>
An alternative to listing the errors inline with the inputs would be to get rid of the echoError function and use this right after the <form> tag:

Code: Select all

<?php if ($bPosted && $bHasErrors): ?>
  <div id="errors">
    <p>Please check the following issue(s):</p>
    <ul><li><?php echo implode('</li><li>',$aryErr); ?></li></ul>
  </div>
<?php endif; ?>