I've been writing PHP for about two years now, nothing complex, mostly just HTML form processing scripts.

My latest project for a customer has over 40 items in the form. It's a dynamic form using some JavaScript and PHP that displays certain parts of the form based on other options selected.

My question is, due to the varying numbers of $_POST results that I may get, is there a more efficient way of getting the $_POST values?

I've done a lot of searching here and on Google, but so far I've come up short. This is the closest thing that I've found:

foreach($_POST as $name => $value) {
    print "$name : $value<br>";
}

Now, I wouldn't be printing the name and value, but would modifying this actually work? Does anyone know of a more efficient way?

Recommended Answers

All 6 Replies

That would be the best way. You'd do something like this:

foreach($_POST as $name => $value) {
  switch ($name) {
    case "colour":
    // logic here to handle the colour
    break;
    case "size":
    // logic here to handle the type
    break;
    case "type":
    // logic here to handle the type
    break;
  }
}

foreach is the best way of stepping through an array (such as $_POST) to find all the values and keys

So just to make sure that I'm understanding you, using the following code:

foreach($_POST as $name => $value) {
  switch ($name) {
    case "colour":
    // logic here to handle the colour
    break;
    case "size":
    // logic here to handle the type
    break;
    case "type":
    // logic here to handle the type
    break;
  }
}

The whole processing form would be a big loop, then at the end I would add the mail function that sent the email. Something like this:

<?php
foreach($_POST as $name => $value) {
    switch ($name) {
        case "FirstName":
            // logic here to handle the FirstName
            break;
        case "LastName":
            // logic here to handle the LastName
            break;
        case "Email":
            // logic here to handle the Email
            break;
        case "EmailConfirm":
            // logic here to handle the EmailConfirm
            break;
// add remaining 30 or so $_POST entries here
    }
}

// Done processing all form values, send email

$mime_boundary = "----BOUNDARY HEADER----".md5(time());

$headers = "From: $fromName <$fromEmail>" . "\r\n" .
           "Reply-To: $fromName <$fromEmail>" . "\r\n" .
           "Return-Path: from@domain.com" . "\r\n" .
           "Content-Type: text/plain; charset=ISO-8859-1; format=flowed; boundary=\"$mime_boundary\"" . "\r\n" .
           "MIME-Version: 1.0" . "\r\n" .
           "X-Mailer: PHP/" . phpversion() . "\r\n" .
           "Organization: My Org Name";

$subject = mb_encode_mimeheader($subject, "UTF-8", "B", "\n");

if ( mail($sendto, $subject, $body, $headers) ) {
    $err = FALSE;
}
else {
    $err = TRUE;
    $msg .= " <font color=red><strong>Error #85</strong></font>";
    $status .= $msg;
}

if ( $err ) {
    echo $status;
}

exit();
?>

Ideally speaking, would the above work?

Your could should work but I don't see the link between processing the form variables at the beginning and the mailing code.

You might need to provide more information as to what you are wanting to do. The nature of your logic will determine the logic required in your code.

Just to clarify: If you know what the names of the POST variables will be you don't need the foreach loop. But (if I've understood you correctly) your form is dynamic and you don't know what the names of the variables will be, in which case the best thing to do is to use a foreach() loop.

If you DO know all the possible variable names, just that some might not be present, you can do it differently, like this:

$use_name = "";
if (isset($_POST["FirstName"])) {
  $use_name = $_POST["FirstName"];
  if (isset($_POST["LastName"])) {
    $use_name .= " ".$_POST["LastName"];
    }
  }
elseif (isset($_POST["Title"]) || isset($_POST["LastName"])) {
  $use_name = $_POST["Title"]." ".$_POST["LastName"];
  }
else {
  $use_name = "Customer";
  }

and later in your code when you send the email:

$email_message = "Dear ".$use_uame.",\nThank you for signing up to our newsletter....";
// more code to determine the rest of $email_message
if (!mail($email_to,$email_subject,$email_message,$email_headers)) {
  echo "An error occurred!";
  }
else {
  echo "We have sent you a welcome email.";
  }

The two pieces of code determine how to write the greeting line of an email. It will produce:
Dear John Smith (if both names are available)
Dear John (if only the first name is available)
Dear Mr Smith (if the title and last name are both available)
Dear Subscriber (in other cases)

This example doesn't need foreach() because we know all the possible variable names, even though not all variables might be present.

But if you have no idea what the variable names will be (or can be) then you'll need foreach().

For example, suppose (for some strange reason) your form sends variables beginning with "productID_", for example "productID_00382", "productID_01882", "productID_00724", etc. You have no idea what the variables will be because you have so many product IDs and they can change as you add new products to your catalogue then you'd have to do something like this:

foreach($_POST as $name => $value) {
  if (substr($name,0,10) == "productID_" {
    // code to handle the many productID_xxx variables
    }
  }

Having said that, there's a better way to pass such variables, but I was just trying to think of an example where you'd have completely dynamic variable names.

As mentioned before, you should give us more detail because we're kind of guessing the situation and what you want to do.

As mentioned before, you should give us more detail because we're kind of guessing the situation and what you want to do.

Thanks! This has been informative to say the least and I apologize about the lack of details.

I DO know the names of all the variables, it's the values and the combination that I won't know.

The form is an order processing script, where the user selects one of the known products, selects if it's going to be Net30 or Credit Card, then submits information depending on Net30 or CC chosen as the payment method.

Since I know the variables, I usually use:

<?php
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
// rest of post items...

And so on. The problem that I have with this is that I'm declaring all of the variables one-by-one and I feel that it's being far more tedious than it should be. I also feel that calling "$_POST" everytime I need it is excessive, but I may be incorrect on this one.

Again, I've been writing PHP for about two years, but the most I've ever done was a calculator to calculate the time for a given process or process an HTML form that had about 12 actual $_POST values, so it wasn't as bad do write each one out. In this form, however, the number of actual $_POST values may be only 15 for one customer, but 24 for the next customer.

Hopefully that clarifies things a bit.

Thanks! This has been informative to say the least and I apologize about the lack of details.

I DO know the names of all the variables, it's the values and the combination that I won't know.

The form is an order processing script, where the user selects one of the known products, selects if it's going to be Net30 or Credit Card, then submits information depending on Net30 or CC chosen as the payment method.

In that case you just build the logic by checking whether certain information has been submitted, e.g.

if (isset($_POST["FirstName"))

or whether it's empty:

if ($_POST["FirstName"] == "")

and other such logic.

Since I know the variables, I usually use:

<?php
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
// rest of post items...

And so on. The problem that I have with this is that I'm declaring all of the variables one-by-one and I feel that it's being far more tedious than it should be. I also feel that calling "$_POST" everytime I need it is excessive, but I may be incorrect on this one.

There are two approaches:

1. You can turn on Register Globals (see http://php.net/manual/en/security.globals.php) but I advise against it because of its security implications, and it's also just not a very clean method. Register Globals allows you to reference $_POST["abc"] as just $abc. You can probably guess the dangers of this. Also worth noting is that Register Globals is deprecated as of version 5.3.0 and removed in PHP 6.0.0, so even more reason not to go down that route :)

2. You can assign normal variables the values in the $_POST array. You'd have to do them individually, but that's a good opportunity to validate your input variables. So like this:

$FirstName = $_POST["FirstName"];
if ($FirstName == "") {
  // error if mandatory
  }
// more code....
// .. and then later you just refer to $FirstName instead of $_POST["FirstName"]

Again, I've been writing PHP for about two years, but the most I've ever done was a calculator to calculate the time for a given process or process an HTML form that had about 12 actual $_POST values, so it wasn't as bad do write each one out. In this form, however, the number of actual $_POST values may be only 15 for one customer, but 24 for the next customer.

I don't think there's any other shortcuts. If you have a lot of variables, you have a lot of validating and processing, there's just really no way around it.

You'll just need to use a lot of if or switch statements for things you need to take into consideration, kind of like my example above of doing a greeting when you're not sure whether a First Name, a Surname, both or neither are supplied.

You may find moving to Object Oriented code easier and simpler, and (depending on how your app is designed) you may find some savings in terms of re-using code.

Thank you for the info. That pretty much answers my questions and as you stated before, if I have a lot of variables, then I have a lot of validation. I was just making sure that I wasn't making things harder on myself.

Oh, and as a quick note, I don't like using Register Globals and it is turned off on the system.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.