Jump to content

Passing Array value to Function


wstran

Recommended Posts

Greetings,

 

Please help me to improve my script. Basically my following script works if I hard-coded the email (employee1@test.com) into the variable $to of function processingForm() . However I would like to use the URL parameter (http://www.mywebsite.com/email.php?employee=1) which is passed into an array value $email and then transfer into the variable $to of function processingForm(). In other words, if URL parameter ?employee=1 then $to="employee1@test.com; if ?employee=2 then $to="employee2@test.com" and so on:

 

<?php

// Create an array

$BROemployee = array

    (

          "1" => array("Aemail" => "employee1@test.com"),

          "2" => array("Aemail" => "employee2@test.com"),

          "3" => array("Aemail" => "employee3@test.com"),

    );

$employee = $_GET['employee'];                            //get URL parameter employee

$email = $BROemployee[$employee]["Aemail"];      //define variable $email

//

//Select the function to call

//

if (!isset($_REQUEST['submit'])) {

                generatingForm();     

  } else {

                processingForm($email);     

  }

//Get the sender's  input from the form

function generatingForm() {

            print("<html><head><title>Contact Web Form</title></head><form action=email.php method=post>");

            print("<body><font face=Arial size=2>");

            print("<table bgcolor=#ffffcc align=center><tr><td colspan=2><strong>Please contact us using this"

                        ." form:</strong></td></tr>\n");

            print("<tr><td><font color=red>*</font>Your Name:</td>"

                        ."<td><input type=text size=25 name=fName></td></tr>\n");

            print("<tr><td><font color=red>*</font>Your Email:</td>"

                      ."<td><input type=text size=25 name=fEmail></td></tr>\n");

          print("<tr><td>Your Company:</td>"

                      ."<td><input type=text size=25 name=fCompany></td></tr>\n");

          print("<tr><td>Your Phone:</td>"

                    ."<td><input type=text size=25 name=fPhone></td></tr>\n");

          print("<tr><td colspan=2>Message:</td></tr>");

          print("<tr><td colspan=2 align=center><textarea name=fMessage rows=15 cols=35></textarea></td></tr>");

          print("<tr><td colspan=2 align=center><small>A <font color=red>*</font> indicates a field is required</small></td></tr>");

          print("<tr><td colspan=2>"

                    .'<input type=submit name=submit value="Send Mail">'

                    ."<td></tr></table>\n");

          print("</form></body></html>\n");

}

//

// Send the email

function processingForm($email) {

          $to =$email;

          $from = $_REQUEST['fEmail'] ;

          $name = $_REQUEST['fName'] ;

          $headers = "From: $from";

          $subject = "Web Contact Form";

// Create an array for the inputs

        $fields = array();

        $fields{"fName"} = "Name";

        $fields{"fCompany"} = "Company";

        $fields{"fEmail"} = "Email";

        $fields{"fPhone"} = "Phone";

        $fields{"fMessage"} = "Message";

//

        $body = "We have received the following information:\n\n";

                  foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }

//  Send email to sender to confirm the action

        $headers2 = "From: webmaster@test.com";

        $subject2 = "Thank you for contacting us";

        $autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usually within 48 hours.";

// Verify that the sender has entered the required his/her email and name

        if($from == '') {print "Sorry! You have not entered your email, please go back and try again";}

                else {

        if($name == '') {print "Sorry! You have not entered your name, please go back and try again";}

                else {

                        $send = mail($to, $subject, $body, $headers);

                        $send2 = mail($from, $subject2, $autoreply, $headers2);

        if($send)

                        {header( "Location: http://www.mywebsite.com" );}

              else

                      {print "We encountered an error sending your mail, please notify webmaster@test.com"; }

              }

              }

        }

?>

 

Link to comment
Share on other sites

Never, ever use user submitted data (POST, GET, COOKIE, etc.) in your code without validating it. I assume the email addresses of employee1, employee2, etc. were just for illustrative puposes and that they do not necessarily directly correspond to the email username. Which would break the method proposed by mikesta707. And, even if they did, you should still validate the email address.

 

I would go with using an array as you posted. However, I would take a slightly different approach.

$BROemployee = array
     (
           "1" => array("Aemail" => "employee1@test.com"),
           "2" => array("Aemail" => "employee2@test.com"),
           "3" => array("Aemail" => "employee3@test.com"),
     );

$employee = $_GET['employee']; //get URL parameter employee
if (isset($BROemployee[$employee]['Aemail']))
{
    //define variable $email
    $email $BROemployee[$employee]['Aemail'];
}
else
{
    //Use a default email address or trigger error condition
}

 

After a cursory look at your code, however, I don't see any reason why it would not work. If it is not working you should put in some code for debugging purposes.

1) Echo out the value of $employee. Does it contain the number you expect? If so, check the value of $email that you define from the array. If not, do a print_r($_GET) to see all the values passed on the query string.

Link to comment
Share on other sites

Thanks mikesta707 and mjdamato for your quick advices. I applied your recommendations but it still did not work. I think when the variable $email was passed to the function processingForm($email) somehow it did not keep its value. Please advise, thanks.

Link to comment
Share on other sites

I think when the variable $email was passed to the function processingForm($email) somehow it did not keep its value. Please advise, thanks.

 

I already did advise you on what you need to do - add some code to debug the problem. YOU should know what the values of all the variables should be at each step. Just echo them to the page to validate.

 

I don't see in your page how you are passing the employee id in the URL.The form action is simply "email.php". If you want to give the user the option to choose who to send the email to then put a select list. Otherwise, use a hidden field and determine how you will populate it.

Link to comment
Share on other sites

Here is a complete rewrite of your code in a more logical fasion. I made the TO email addresses a select list in the form. If you don't want the user to choose, then make it a hidden field and decide how you will populate it.

 

<?php

// Create an array of valid emails
$emails = array
(
    "1" => "employee1@test.com",
    "2" => "employee2@test.com",
    "3" => "employee3@test.com"
);
  
//Create select list options for To email address
$emailOptions = '';
foreach($emails as $id => $email)
{
    $selected = ($email==$_POST['employee']) ? ' selected="selected"': '';
    $emailOptions .= "<option value=\"{$id}\">{$email}</option>\n";
}

//Process the form submission
if (isset($_POST['employee']))
{
    //Define To email address
    $e_id = trim($_POST['employee']); //get URL parameter employee
    $mssg_toEmail = (isset($emails[$e_id])) ? $emails[$e_id] : $emails[1];

    //Prepare the submitted data
    $fName    = trim($_POST['fName']);
    $fEmail   = trim($_POST['fEmail']);
    $fCompany = trim($_POST['fCompany']);
    $fPhone   = trim($_POST['fPhone']);
    $fMessage = trim($_POST['fMessage']);

    //Validate data
    $errors = array();
    if(empty($fName)) { $errors[] = "Name is required"; }
    if(empty($fEmail)) { $errors[] = "Email is required"; }

    if(count($errors)>0)
    {
        $error_msg = "The following errors occured:";
        $error_msg .= "<ul>";
        $error_msg .= "<li>" . implode("</li>\n<li>", $errors) . "</li>\n";
        $error_msg .= "<ul><br />\n";
    }
    else
    {
        //No errors, construct emails
        $mssg_subject = "Web Contact Form";
        $mssg_body    = "We have received the following information:\n\n";
          $mssg_body .= "Name: $fName\n";
          $mssg_body .= "Email: $fEmail\n";
          $mssg_body .= "Company: $fCompany\n";
          $mssg_body .= "Phone: $fPhone\n";
          $mssg_body .= "Message: $fMessage\n";
        $mssg_headers = "From: $fName";
        
        $reply_toEmail = $fEmail;
        $reply_subject = "Thank you for contacting us";
        $reply_body = "Thank you for contacting us. Somebody will get back to you as soon as possible, usually within 48 hours.";
        $reply_headers = "From: webmaster@test.com";
  
        //Send the email
        $mssg  = mail($mssg_toEmail,  $mssg_subject,  $mssg_body,  $mssg_headers);
     
        //Check if email sent OK
        if(!$mssg)
        {
            $error_msg = "There was a problem sending yur message. Please try again.<br />\n";
        }
        else
        {
            mail($reply_toEmail, $reply_subject, $reply_body, $reply_headers);
            header( "Location: http://www.mywebsite.com");
            exit();
        }
    }
}

?>
<html>
<head>
<title>Contact Web Form</title>
</head>
<body>

<form action="" method="post">
<table bgcolor="#ffffcc" align="center">
  <tr>
    <td colspan="2"><?php echo $error_msg; ?></td>
  </tr>
  <tr>
    <td colspan="2"><strong>Please contact us using this form:</strong></td>
  </tr>
  <tr>
    <td>Send to:</td>
    <td><select name="employee"><?php echo $emailOptions; ?></select></td>
  </tr>
  <tr>
    <td><font color="red">*</font>Your Name:</td>
    <td><input type="text" size="25" name="fName" value="<?php echo $fName; ?>" /></td>
  </tr>
  <tr>
    <td><font color="red">*</font>Your Email:</td>
    <td><input type="text" size="25" name="fEmail" value="<?php echo $fEmail; ?>" /></td>
  </tr>
  <tr>
    <td>Your Company:</td>
    <td><input type="text" size="25" name="fCompany" value="<?php echo $fCompany; ?>" /></td>
  </tr>
  <tr>
    <td>Your Phone:</td>
    <td><input type="text" size="25" name="fPhone" value="<?php echo $fPhone; ?>" /></td>
  </tr>
  <tr>
    <td colspan="2">Message:</td>
  </tr>
  <tr>
    <td colspan="2" align="center"><textarea name="fMessage" rows="15" cols="35"><?php echo $fMessage; ?></textarea></td>
  </tr>
  <tr>
    <td colspan="2" align="center"><small>A <font color="red">*</font> indicates a field is required</small></td>
  </tr>
  <tr>
    <td colspan=""2><input type="submit" name="submit" value="Send Mail"></td>
  </tr>
</table>
</form>
</body>
</html>

Link to comment
Share on other sites

Thanks mjdamato for rewriting my code. The reason I use http://www.mywebsite.com/email.php?employee=1 to embed the link into our webpages so the sender won't know the email address of the receiver. My original code works well when I hard-code the email address into variable $to in function processingForm(). My only problem is when the variable value is passed into the second function, it's equal NULL.

 

As your advice, I've added the "echo" into the following code to debug and it showed the variable $email still kept its value in IF condition but was equal NULL in ELSE condition: 

 

<?php

// Create an array

$BROemployee = array

    (

          "1" => array("Aemail" => "employee1@test.com"),

          "2" => array("Aemail" => "employee2@test.com"),

          "3" => array("Aemail" => "employee3@test.com"),

    );

$employee = $_GET['employee'];                            //get URL parameter employee

$email = $BROemployee[$employee]["Aemail"];      //define variable $email

//

//Select the function to call

//

if (!isset($_REQUEST['submit'])) {

                echo "IF-BROemail=". $email."<br>";

                generatingForm();

  } else {

                echo "ELSE-BROemail=". $email."<br>";

                processingForm($email);

  }

//Get the sender's  input from the form

function generatingForm() {

            print("<html><head><title>Contact Web Form</title></head><form action=email.php method=post>");

            print("<body><font face=Arial size=2>");

            print("<table bgcolor=#ffffcc align=center><tr><td colspan=2><strong>Please contact us using this"

                        ." form:</strong></td></tr>\n");

            print("<tr><td><font color=red>*</font>Your Name:</td>"

                        ."<td><input type=text size=25 name=fName></td></tr>\n");

            print("<tr><td><font color=red>*</font>Your Email:</td>"

                      ."<td><input type=text size=25 name=fEmail></td></tr>\n");

          print("<tr><td>Your Company:</td>"

                      ."<td><input type=text size=25 name=fCompany></td></tr>\n");

          print("<tr><td>Your Phone:</td>"

                    ."<td><input type=text size=25 name=fPhone></td></tr>\n");

          print("<tr><td colspan=2>Message:</td></tr>");

          print("<tr><td colspan=2 align=center><textarea name=fMessage rows=15 cols=35></textarea></td></tr>");

          print("<tr><td colspan=2 align=center><small>A <font color=red>*</font> indicates a field is required</small></td></tr>");

          print("<tr><td colspan=2>"

                    .'<input type=submit name=submit value="Send Mail">'

                    ."<td></tr></table>\n");// Send the email

function processingForm($email) {

          $to = $email;

          $from = $_REQUEST['fEmail'] ;

          $name = $_REQUEST['fName'] ;

          $headers = "From: $from";

          $subject = "Web Contact Form";

// Create an array for the inputs

        $fields = array();

        $fields{"fName"} = "Name";

        $fields{"fCompany"} = "Company";

        $fields{"fEmail"} = "Email";

        $fields{"fPhone"} = "Phone";

        $fields{"fMessage"} = "Message";

//

        $body = "We have received the following information:\n\n";

                  foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }

//  Send email to sender to confirm the action

        $headers2 = "From: webmaster@test.com";

        $subject2 = "Thank you for contacting us";

        $autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usually within 48 hours.";

// Verify that the sender has entered the required his/her email and name

        if($from == '') {print "Sorry! You have not entered your email, please go back and try again";}

                else {

        if($name == '') {print "Sorry! You have not entered your name, please go back and try again";}

                else {

                        $send = mail($to, $subject, $body, $headers);

                        $send2 = mail($from, $subject2, $autoreply, $headers2);                     

 

        if($send)

                        {header( "Location: http://www.mywebsite.com" );}

              else

                      {print "We encountered an error sending your mail, please notify webmaster@test.com"; }

              }

              }

        }

?>

 

Link to comment
Share on other sites

Well, of course it isn't working. If you walk through the process it is obvious what is happening. [And please use [ CODE ] tags when posting]

 

So, when submit is not set (i.e. when the user first acess the page) the employee id IS set. But, when the user submits the form, it IS NOT set.

 if (!isset($_REQUEST['submit'])) {
                 echo "IF-BROemail=". $email."<br>";
                 generatingForm();
  } else {
                echo "ELSE-BROemail=". $email."<br>";
                processingForm($email);
  }

 

You apparently have different links to initally access this page that use the "?employee=1" parameter. So, when the user first accesses the page that value is set. But, when the user first accesses the page you are only displaying the form to the user.

 

THEN, when the user submits the page the form posts to just "email.php" without the employee paramter.

<form action=email.php method=post>

 

So, when you process the form to actually send the email you do not have the employee id parameter!

 

Since I had no idea how you were using this I couldn't anticipate this problem, but if you had read my earlier responses you should have identified it yourself

I don't see in your page how you are passing the employee id in the URL.The form action is simply "email.php". If you want to give the user the option to choose who to send the email to then put a select list. Otherwise, use a hidden field and determine how you will populate it.

 

So, you have some different options:

 

1. You could use the code I posted which is much cleaner than what you have anyway. I assumed that the page would post to itself, so in my code I left the action parameter of the form empty. By doing that, the form will post to the same URL (including the employee parameter). If you had even tried the code I posted, I'm betting it would have worked. So, I don't know why I even bother.

 

2. You could follow the previous advise I gave you and use teh employee parameter on initial form load to populate a hidden field on the form. Then use that when you process the form to determine the email.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.