Help Build A Better Form with PHP

Over the last year I’ve been working on improving my knowledge of PHP. The fact that I’m teaching myself, with the help of a few friends, has made this a slow, but rewarding process. Every day I’m introduced to new concepts and methods for achieving the desired result. I’ve come to a bit of a road block and am looking for some help.

Up until recently I’ve gone about things the long way. Generally writing long bits of code, often times it would be very redundant. Needlessly creating larger pages than needed. That has changed over time.

Now I’m realizing the obvious usefulness of functions. Of couse, the goal with programming is to make the most extensible code, and create and keep a library of that code so it can be reused and often, and easily as possible. Whew, that was a mouthful.

So, that being said, I’m looking to conquer a little function that after a form is submitted will check the required fields and display a warning/error message for each required field that was not filled out correctly. If all the required fields were filled out correctly the form information would be emailed.

With the help of Colin Devroe I’m well on my way to getting where I want to be. The function checks the required fields and outputs the correct warning/error. The problem is with the actual emailing of the form values. After the function is finished and there are no errors the information does not get sent.

The Code

This is the particular bit of code that I’ve been working on. The function doesn’t include the email portion of the code but I will put a snippet of it at the end. (The $sendmail variable is set to true earlier in the code).

function checkRequired()
{
    // Declare variables for later
    $stackKeys 		=	array();
    $stackValues 	=	array();
    $arrErrors		=	array();

    // Loop through $_POST
    // Set up hard variables
    foreach ($_POST as $key => $value)
    {
        // Create an array of the keys and their values
        array_push($stackKeys, $key);
        array_push($stackValues, $value);

    } //end foreach

    $stack = array_combine_emulated($stackKeys, $stackValues);
    extract($stack, EXTR_PREFIX_SAME, "pre");

    // Array of required fields
    $arrRequired	=	explode(',', $required);

    // Loop through required fields
    // Check them for value
    for ($i=0; $i< =count($arrRequired); $i++)
    {
        if ( $stack[$arrRequired[$i]] == "" )
        {
            $arrErrors[$i]	=	$arrRequired[$i];
            if (!is_null($arrRequired[$i]))
            {
                echo "<p class=\"error\">Please note: ".
                $arrRequired[$i]." is a required field.</p>";
            }
        }
    } // end for arrRequired
}

checkRequired();

if ( $sendmail )
{
   //Setting the variables for the email body here.
    foreach ($recipient as $send_to) {
        mail ($send_to, $topic[$subject], $text, $headers);
    }
    echo "<p>Thank you for contacting us.
    We will respond to your email as soon as possible.</p>\n";
} else {
    echo $errmsg;
}

UPDATE: Removed an unnecessary second if ( $sendmail ) conditional and combined it with the previous if ($sendmail) conditional.

This is Where You Come In

If anyone has any thoughts I would love to hear them in the comments. I am also aware that there are code libraries out there but, as I’ve been told, the best way to learn is by doing. And with that I open the comments to you.

Reader comments

  1. Gravatar

    On September 20th, 2005, Justin Lilly said:

    Just as an fyi, Javascript is probably better suited to validating the information before a form is submitted. That way, slow users don’t have to wait for another page refresh. But if you deal with a lot of people with javascript turned off, I suppose, now that I think about it, php would be best. I think I’d still include both, though.

  2. On September 21st, 2005, Mike said:

    Justin, you’re absolutely right, Javascript is a very easy to use way to validate forms. I’ve actually been using one particular script on most of my sites up until now.

    The reason for choosing PHP/Server side scripts for the validation is more along the user experience side of things. I’d rather have the user reload another page but have the error displayed in a more aesthetically appealing way than a JS popup.

    Reason number two is just as you’ve stated. I’d like to make my forms as accessible as possible, even to those with JS turned off. Finally, building forms this way makes it more extensible, especially by expanding the function (or eventual class) to include the dynamic creation of the form itself.

  3. Gravatar

    On September 23rd, 2005, Jem said:

    I just wanted to say “hoorah” for teaching yourself PHP. Nothing like the satisfaction of learning a language from scratch.

    Sorry, I don’t actually have any constructive suggestions. ;)

  4. On September 23rd, 2005, Mike said:

    No worries Jem and thanks for the encouraging words. You’re right, there is nothing like the satisfaction of learning something from scratch. Besides, I’m sure I’ll get this thing licked and when I do I’ll post a nice little breakdown of how it works.

  5. Gravatar

    On September 24th, 2005, Colin D. Devroe said:

    I have some suggestions… but they are BLURRY right now.

  6. Gravatar

    On May 16th, 2006, Morishani said:

    Good function, keep working with functions :)

Leave a comment