简体   繁体   中英

Use dynamically created form values to set variables as POST requests in php

I have a form where one can dynamically add rows using javascript, thus also incrementing the name tag by the next following number (ie name1 , name2 , name3 , etc).

How can I check if a given value exists and then assign it to a variable, in order to send the contained form information to an email address?

This is what I'm working with so far:

<?php
// My modifications to mailer script from:
// http://blog.teamtreehouse.com/create-ajax-contact-form
// Added input sanitizing to prevent injection

// Only process POST requests.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form fields and remove whitespace.
    $Firma = strip_tags(trim($_POST["Firma"]));
    $Firma = str_replace(array("\r","\n"),array(" "," "),$Firma);
    $Vorname = strip_tags(trim($_POST["Vorname"]));
    $Vorname = str_replace(array("\r","\n"),array(" "," "),$Vorname);
    $Name = strip_tags(trim($_POST["Name"]));
    $Name = str_replace(array("\r","\n"),array(" "," "),$Name);
    $Strasse = strip_tags(trim($_POST["Strasse"]));
    $Strasse = str_replace(array("\r","\n"),array(" "," "),$Strasse);
    $PLZ = strip_tags(trim($_POST["PLZ"]));
    $PLZ = str_replace(array("\r","\n"),array(" "," "),$PLZ);
    $Ort = strip_tags(trim($_POST["Ort"]));
    $Ort = str_replace(array("\r","\n"),array(" "," "),$Ort);
    $Telefon = strip_tags(trim($_POST["Telefon"]));
    $Telefon = str_replace(array("\r","\n"),array(" "," "),$Telefon);
    $Email = filter_var(trim($_POST["E-Mail"]), FILTER_SANITIZE_EMAIL);
    $Abholadresse = strip_tags(trim($_POST["Abholadresse"]));
    $Abholadresse = str_replace(array("\r","\n"),array(" "," "),$Abholadresse);
    $PLZ_Abholadresse = strip_tags(trim($_POST["PLZ_Abholadresse"]));
    $PLZ_Abholadresse = str_replace(array("\r","\n"),array(" "," "),$PLZ_Abholadresse);
    $Ort_Abholadresse = strip_tags(trim($_POST["Ort_Abholadresse"]));
    $Ort_Abholadresse = str_replace(array("\r","\n"),array(" "," "),$Ort_Abholadresse);
    $Bemerkungen = trim($_POST["Bemerkungen"]);

    $Materialien = trim($_POST["materialien0"]);
    $Anzahl = trim($_POST["anzahl0"]);
    $Gebinde = trim($_POST["einheit0"]);
    $Austausch = trim($_POST["austausch0"]);
    $Additional = trim($_POST["additional0"]);

    $Materialien_1 = trim($_POST["materialien1"]);
    $Anzahl_1 = trim($_POST["anzahl1"]);
    $Gebinde_1 = trim($_POST["einheit1"]);
    $Austausch_1 = trim($_POST["austausch1"]);
    $Additional_1 = trim($_POST["additional1"]);

    // Check that data was sent to the mailer.
    if ( empty($Name) OR empty($Strasse) OR empty($PLZ) OR empty($Ort)
        OR empty($Telefon) OR !filter_var($Email, FILTER_VALIDATE_EMAIL)) {
        // Set a 400 (bad request) response code and exit.
        http_response_code(400);
        echo "Ups! Leider ist ein Fehler aufgetreten. Bitte stellen Sie sicher, dass Sie alle Felder korrekt eingesetzt haben.";
        exit;
    }

    // Set the recipient email address.
    // FIXME: Update this to your desired email address.
    $recipient = "asymmetrisch@gmail.com";

    // Set the email subject.
    $subject = "Kontaktanfrage von unserer Webseite: $Name";

    // Build the email content.
    $email_content = "Firma: $Firma\n";
    $email_content .= "Vorname: $Vorname\n";
    $email_content .= "Name: $Name\n";
    $email_content .= "Strasse: $Strasse\n";
    $email_content .= "PLZ: $PLZ\n";
    $email_content .= "Ort: $Ort\n";
    $email_content .= "Telefon: $Telefon\n";
    $email_content .= "Email: $Email\n\n";
    $email_content .= "Abholadresse: $Abholadresse\n";
    $email_content .= "PLZ_Abholadresse: $PLZ_Abholadresse\n";
    $email_content .= "Ort_Abholadresse: $Ort_Abholadresse\n";
    $email_content .= "Bemerkungen:\n$Bemerkungen\n\n";

    $email_content .= "Material: $Materialien\n";
    $email_content .= "Anzahl: $Anzahl\n";
    $email_content .= "Einheit: $Gebinde\n";
    $email_content .= "Austausch: $Austausch\n";
    $email_content .= "Zusaetzliche Gebinde: $Additional\n\n";

    $email_content .= "Material: $Materialien_1\n";
    $email_content .= "Anzahl: $Anzahl_1\n";
    $email_content .= "Einheit: $Gebinde_1\n";
    $email_content .= "Austausch: $Austausch_1\n";
    $email_content .= "Zusaetzliche Gebinde: $Additional_1\n";



    // Build the email headers.
    $email_headers = "From: $Vorname $Name $Firma <$Email>";

    // Send the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        // Set a 200 (okay) response code.
        http_response_code(200);
        echo "Danke Ihnen, wir haben Ihre Nachricht erhalten und werden uns bei Ihnen melden.";
    } else {
        // Set a 500 (internal server error) response code.
        http_response_code(500);
        echo "Ups! Etwas ist falsch gelaufen; leider konnte Ihre Nachricht nicht versendet werden.";
    }

} else {
    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo "Es ist ein Problem aufgetreten. Ihre Nachricht konnte leider nicht versendet werden.";
}
?>

It's worth mentioning that only some of the fields are dynamic, starting at $Materialien . As you can see I also declared a variable $Materialien_1 and could go on like that (ie $Materialien_2 , 3, etc), just hardcoding a bunch of variables to make sure that I'm able to get all the information in an email no matter what. But of course that would be just pointless. I'd love to get a solution and learn something out of it.

You can use cycle and checking presence of post attribute at each iteration:

for($n = 0; isset($_POST["materialien$n"]); $n++) {
    $Materialien = trim($_POST["materialien$n"]);
    $Anzahl = trim($_POST["anzahl$n"]);
    $Gebinde = trim($_POST["einheit$n"]);
    $Austausch = trim($_POST["austausch$n"]);
    $Additional = trim($_POST["additional$n"]);

    $email_content .= "\nMaterial: $Materialien\n";
    $email_content .= "Anzahl: $Anzahl\n";
    $email_content .= "Einheit: $Gebinde\n";
    $email_content .= "Austausch: $Austausch\n";
    $email_content .= "Zusaetzliche Gebinde: $Additional\n";
}

You can use foreach loop to get dynamic added fields value
You can try::

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    foreach($_POST as $key=>$value)
    {
         $email_content .= "$key: $value\n";
    }
}

As your concern seems to be checking a random number of properties sharing an identical label, you could simply pass an array through $_POST for the dynamic fields.

This is done by using form inputs like these:

<input type="text" name="label[]" />
<input type="text" name="label[]" />
<input type="text" name="label[]" />

Submitting these inputs to PHP will convert them to an array. In this example:

$_POST['label'][0]
$_POST['label'][1]
$_POST['label'][2]

This allows you to iterate over them easily:

foreach($_POST['label'] as $value) {
    // validate your value here using $value
}

You can force the indexes like this:

<input type="text" name="label[3]" />
<input type="text" name="label[4]" />
<input type="text" name="label[5]" />

Or you can group your related fields directly by changing the structure:

<input type="text" name="group[3][name]" />
<input type="text" name="group[3][materialien]" />
<input type="text" name="group[3][anzahl]" />

This last structure would return an array when iterating over group :

foreach($_POST['group'] as $arr) {
    // you can use the following indexes:
    // $arr['name']
    // $arr['materialien']
    // $arr['anzahl']
}

No issue i am just posting the code structure.
You can use and Try to keep variable name in lower case letter for good coding practice. Also no need to use

$Firma = str_replace(array("\r","\n"),array(" "," "),$Firma);

PHP trim function will trim the "\\r" and "\\n"
Best of luck for your future.
So you can use foreach loop like this:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form fields and remove whitespace.
    $Firma = strip_tags(trim($_POST["Firma"]));
    $Firma = str_replace(array("\r","\n"),array(" "," "),$Firma);
    $Vorname = strip_tags(trim($_POST["Vorname"]));
    $Vorname = str_replace(array("\r","\n"),array(" "," "),$Vorname);
    $Name = strip_tags(trim($_POST["Name"]));
    $Name = str_replace(array("\r","\n"),array(" "," "),$Name);
    $Strasse = strip_tags(trim($_POST["Strasse"]));
    $Strasse = str_replace(array("\r","\n"),array(" "," "),$Strasse);
    $PLZ = strip_tags(trim($_POST["PLZ"]));
    $PLZ = str_replace(array("\r","\n"),array(" "," "),$PLZ);
    $Ort = strip_tags(trim($_POST["Ort"]));
    $Ort = str_replace(array("\r","\n"),array(" "," "),$Ort);
    $Telefon = strip_tags(trim($_POST["Telefon"]));
    $Telefon = str_replace(array("\r","\n"),array(" "," "),$Telefon);
    $Email = filter_var(trim($_POST["E-Mail"]), FILTER_SANITIZE_EMAIL);


    // Check that data was sent to the mailer.
    if ( empty($Name) OR empty($Strasse) OR empty($PLZ) OR empty($Ort)
        OR empty($Telefon) OR !filter_var($Email, FILTER_VALIDATE_EMAIL)) {
        // Set a 400 (bad request) response code and exit.
        http_response_code(400);
        echo "Ups! Leider ist ein Fehler aufgetreten. Bitte stellen Sie sicher,           dass Sie alle Felder korrekt eingesetzt haben.";
        exit;
      }

    // Set the recipient email address.
    // FIXME: Update this to your desired email address.
    $recipient = "asymmetrisch@gmail.com";

    // Set the email subject.
    $subject = "Kontaktanfrage von unserer Webseite: $Name";
    $email_content='';
    if(!empty($_POST))
    {
        foreach($_POST as $field_name=>$field_value)
        { 
             $field_value = strip_tags(trim($field_value)); 
             $email_content .= "$field_name: $field_value\n";
        } 
    }



    // Build the email headers.
    $email_headers = "From: $Vorname $Name $Firma <$Email>";

    // Send the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        // Set a 200 (okay) response code.
        http_response_code(200);
        echo "Danke Ihnen, wir haben Ihre Nachricht erhalten und werden uns bei Ihnen melden.";
    }
    else 
   {
        // Set a 500 (internal server error) response code.
        http_response_code(500);
        echo "Ups! Etwas ist falsch gelaufen; leider konnte Ihre Nachricht nicht versendet werden.";
    }

} 
else
{
    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo "Es ist ein Problem aufgetreten. Ihre Nachricht konnte leider nicht    versendet werden.";
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM