views:

32

answers:

4

Hi everyone,

I have an HTML form that takes inputted data and sends it via the mail() function. I also have some validation techniques that validate the inputs, and I created an array variable $errors to log all of the errors; for example,

if the name was left empty, $errors[]="Name empty"; If the email was left empty, $errors[]="email empty";

and so on..

I was able to report the errors using the following technique:

print '<div id="formfeedback"><h3>Error!</h3><p>The following error(s) has occurred:<br />';
    foreach ($errors as $msg) { //prints each error
            print " - $msg<br />\n";
        } // end of foreach

However, what I want is the following. I want the page to be redirected back to the original form that was used to input the information (I know the exact link location, so i can use a header() or even a <meta=http-equiv=refresh> to bring me back to the form page.

Also, on the form, I want to be able to post the errors above the form in some div (call it div=errors)

Would I be able to do the following?

    <div id="errors">
<?php    
print 'The following error(s) has occurred:<br />';
            foreach ($_REQUEST[$errors] as $msg) { //prints each error
                    print " - $msg<br />\n";
                } // end of foreach
?>   
 </div>

Thanks a lot!

Amit

A: 

Typically I would have the same page process the input and the submission. If the data was valid, the mail would be sent and the page would notify them of that (or redirect them elsewhere)... if the data was not valid, then the form would appear again and the errors could be displayed, without any fancy redirection.

Fosco
Redirecting the users helps avoid the problem where refreshing the page submits the data again. Plus, you can separate the form display into controller A and the form parsing into controller B. And it's also useful if your user submits a form after being logged out (redirect user to login : user logs in, returns to form, form is filled because the data was in $_SESSION).
Victor Nicollet
+1  A: 

The simplest way to do this is to:

// Start the session
session_start();

// Store the errors in the session
$_SESSION['errors'] = $errors;

// Redirect to correct page
header('HTTP/1.1 303 See Other');
header('Location: http://original/page');
exit;

Then, on the form page:

// Start the session
session_start();

// extract the errors
$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : array();

// Display the form with errors
foreach ($errors as $msg) ... ;
Victor Nicollet
This looks good. I was wondering, what does the following header do?header('HTTP/1.1 303 See Other');I have had times when the header() did not actually redirect me, could it be because I was missing that line?
Amit
By default, header('Location: ...') uses a 302 HTTP status which, under some interpretations of HTTP, would cause the browser to submit the same request to the new location (in this situation, a POST with the same variables). Using 303 causes it to perform a GET, discarding any POST arguments.
Victor Nicollet
@Nillocet: Though this will work well, Butthis will make the $_SESSION heavier, so its not a good practice.
Sadat
@Saadt: True. Usually, the form data would be removed from the session when it is displayed, so the memory would only "leak" when the user does not follow the redirect.
Victor Nicollet
Is it possible to make this run with a wordpress page?
Amit
A: 

make sure your session is started at the top of your application

include this basic class

class FormErrors
{
    var $handler;
    function __construct($fname)
    {
        $this->handler &= isset($_SESSION[$fname]) $_SESSION[$fname] : ($_SESSION[$fname] = array());
    }

    public function add($name, $value)
    {
        $this->handler[$name] = $value;
    }

    public function remove($name)
    {
        unset($this->handler[$name]);
    }

    public function getErrors()
    {
        return $this->handler;
    }
}

so when your processing the errors you can go

if(isset($_POST))
{
    $FormErrors = new FormErrors("registration");

    if(strlen($_POST['username']) == 0)
    {
       $FormErrors->add('Username','Please enter a valid username');
    }

    //And for the rest of your checks
}

then within side your html do

foreach($FormErrors ->getErrors() as $name => $error)
{
    echo sprintf("<p title=\"%s\">%s</p>",$name,$error);
}

Should work, and if you want to remove all known errors do

$FormErrors = new FormErrors("registration");
unset($FormErrors->handler,$FormErrors);
RobertPitt
+1  A: 

I agree with @Fosco. I want to explain a little bit more-

There may be two cases- 1. You are doing raw php 2. You are coding on any php framework like CI or your own.

and this will help to identify error field and change style to make better user response. Also last input data remain as it was.

  1. You are doing raw php In this case you can receive the input data in same file/page. I will do a common example later.

  2. You are coding on any php framework like CI or your own. In this case you load a view file to show the form page and you can pass data to view page/file when you load it.

For both of above case you can do some coding like-

/* 
your input validation and verification goes here. where $error is generated too
In addition add some error status in above section, 
you can do it in your $error array too. Also you store received data into $data here. index of $data should be similar as (corresponding) HTML input name. 
You can do it like below
*/
$error_stat = array();
//if the input field name is "email" and email input data raises any error then

$error_stat['email'] = true;
// same for name
$error_stat['name'] = true;
// and so on

// now decide whether you will back to the form page or send the email and do other tasks
if(count($error_stat)<= 0){
  // send email
  // do aditional tasks
}
else{
  // load the form again if its aframework or the form is in seperate file
  // off course send $error,$data and $error_stat to the form page/file
}

// now here is a code segment of form page
<?php if(isset($error) && count($error)>0):?>
<div id="error-msg">
<?php
//display errors here
?>
</div>
<?php endif;?>

<form .... >
<input type="text" name="email" class="<?php echo (isset($error_stat['email'])?'error':'else'); ?>" value="<?php echo $data['email'];?>" />\
<!-- and so on ... -->
Sadat