Quick PHP advice for a newbie who (almost) has it


I have a PHP sendmail script (working) and I want to say:

  • IF a checkbox is checked
  • Then check for additional empty fields
  • IF those additional fields are empty = redirect to an error page
  • IF they are not empty = continue to submit and process the form as normal

The code i’ve managed to write myself does redirect if the additional fields are empty, but when they are populated (which is the aim) for some reason it doesn’t continue to process the form. Any idea why!?

This is my PHP code snippet:

// If checkbox is checked
if($checkbox == '1'){
    // Then check is field1 and field 2 are empty
	if (empty($field1) || empty($field2)) {
        // If field 1 or 2 are empty, redirect user to the errorURL
	   header( "Location: $errorurl" );
	   exit ;

…scrap that.

I’ve just tried removing the second “exit()” after the inner IF statement, and it seems to be working now.

I’ll leave this open til morning incase anyone has anything to add.

Cant believe I didnt see or think of that before posting (but I did say I was a newbie!) lol.

Just an observation really …

When preparing to code a condition such as that get into the habit of var_dump() ing all of the variables involved, and in you condition check not only that the values match but that also the type matches too, use " === " (type and value are the same ie Identical) instead of “==” (value only is the same ie Equal).

Also, stub out the actions with simple echo rather that writing redirects etc straight away.

  echo 'show form here';
  echo 'exit and redirect to home page';

Its only simple stuff, but might save you some heartache when starting out. You can always comment those lines out for debugging/sanity checks later, then remove them before going live.

Given that PHP is a loosely typed language (string “1” is evaluated as being int 1, and 1 is evaluated as Boolean true) really appreciating the diffs between “==” and “===” is a critical piece of information.