PHP Tip: Handling Form Data

One of the most common tasks of a Web Dev, has down, is handling form data. As a web developer you'll create hundreds of forms and in turn, write hundreds of pieces of code to handle your form data.

Early on this became the worse part of my job. So I've create a super quick way to handle post data:

<?php

$valid = true; //innocent until proven guilty
$errors = array(); // errors array
$clean = array();

foreach($_POST as $key => $val)
{
	switch($key)
	{
		case 'first_name':
			// do validation
			if(validateString($val) == false)
			{
				$valid = false; // we're no longer valid.
				$errors[] = "You're missing your first name!"; // prime up an error message for our user
			}
			else
			{
				$clean[$key] = $val;
			}
			break;
		case 'last_name':
			// do validation
			break;
	}
}

if($valid == false)
{
	// show the form again, but with the error message
}
else
{
	// handle our clean array anyway we want (usually a DB insert)
}
?>
Saturday, January 30th, 2010 PHP, Web Development

3 Comments to PHP Tip: Handling Form Data

  1. Hey David,
    I’m looking for PHP Developers like yourself. It seems as though you might not be looking, but I would love any referral help you can give me.

    I’m working with two social gaming companies, an ad network start-up and a stealth mode start-up that is Founded and funded by an BEA Founder. Please let me know when you are available to chat.

    Thanks,
    Colin Peterson – Sr. Recruiter
    Venator Ventures
    650-260-3030

  2. Colin Peterson on February 22nd, 2010
  3. Y not use jquery plugins ?It makes life much easier!

  4. Kiran on April 30th, 2010
  5. Using a jQuery plugin to ‘validate’ form data would mean that you are depending upon the client side to validate itself. Which is hardly secure at all.

    You should think of it this way:

    Client side validation, like a jQuery plug in, is a nice to have
    Server side validation, like with PHP, is a must have.

    If you just assume that everyone will be sending you valid data you are opening yourself up to possible cross site scripting and SQL injection attacks.

    -dschreck

  6. dschreck on May 7th, 2010

Leave a comment

*