I'm trying to do a foreach loop inside a foreach loop.
I have a form where the user type in some text and hit send. On the server site I loop through an array with email addresses and send out the text message.
Now I also want the user to be able to use variables in the textarea, like $name.
So my loop should first loop through the emails, and then str_replace the userinput $name variable, with the names in my array.
The loop works fine with the email part ($tlf), but not the replace $name part.
Could some spot what I am doing wrong?
$message = stripslashes(strip_tags($_POST['message2']));
$tlf=array("name1","name2");
$test=array("mname1", "mname2");
$subject = "Hello world";
$from = "me#gmail.com";
$headers = "From: $from";
foreach($tlf as $name){
$to = $name. "#gmail.com";
foreach($test as $navn){
$message = str_replace('$navn', $navn, $message);}
mail($to,$subject,$message,$headers);
}
Thanks a lot.
EDIT:
The output is an email sent. Say the user type in "hello $name".
I want it to first loop through the $tlf array, in this case creating 2 emails. This goes in as $to in the first loop. This works.
Now the next loop should recognize the user input "hello $name" and loop through the $test array replacing the user $name variable.
The output would be 2 emails send.
Mail output:
to: name1#gmail.com
message: hello mname1
Mail output:
to: name1#gmail.com
message: hello mname2
Let me know if I need to explain better, its hard for me to explain sorry.
When you do the following:
str_replace('$navn', $navn, $message)
Then all literal occurences of $navn will be replaced (the first, the second, the third, ...). So running through that loop a second time can't possibly replace anything more.
You will need to define two placeholders, or make some distinction, or use preg_replace_callback if you want to declare in which order (or other logic) the possible replacement strings are applied.
If you had told us (but you haven't) you only wanted to replace the first occurence in each iteration, then a normal preg_replace(.., .., .., 1) would work.
Is this what you want?
$message = stripslashes(strip_tags($_POST['message2']));
$tlf=array(
array("email" => "name1", "name" => "mname1"),
array("email" => "name2", "name" => "mname2")
);
$subject = "Hello world";
$from = "me#gmail.com";
$headers = "From: $from";
foreach($tlf as $contact){
$to = $contact["email"] "#gmail.com";
$replacedMessage = str_replace('$navn', $contact["name"], $message);
mail($to,$subject,$replacedMessage,$headers);
}
Related
I am trying to send a message with one list with PHP, here is my code:
$packs = $db->QueryFetchArrayAll("SELECT * FROM configmoreg");
foreach($packs as $pack) {
echo '<a>'.$pack['setting_id'].'</a>
<a>'.$pack['config_name'].'</a>
<a>'.$pack['config_value'].'</a>
<br>';
}
mail('example#something.com',"My List",$msg);
How do I make it send only one message with list on it?
For example:
id 00000001
My_name game_over_new
NR_Job 11
type_secure MD5
5 etc...
Build up a string in the for-loop, and send that. Consider:
$msg = '';
foreach($packs as $pack)
$msg .= "<a>${pack['some_key']}</a>";
$subject = "My List";
mail('null#example.com', $subject, $msg);
Meanwhile, I gather you're still learning PHP, so hold on to this next piece of advice until you're ready: don't use PHP's builtin mail() function, use PHPMailer.
Try adding all the variables to an array; then send the array containing the variables.
As you don't know how to use arrays I suggest reading:
https://www.w3schools.com/php/php_arrays.asp
However to get what you want, you'll want something along these lines:
$infoToSend = array($pack['setting_id'], $pack['config_name'], $pack['config_value']);
mail('example#something.com',"My List", $infoToSend);
I'm looping a multidimensional array with a for loop and triggering and email for every item in the loop. I want change {{fname}} to the real name from the key.
foreach($customermarketingarray as $key => $value){
$customeremail = $value['email'];
$fname = $value['first_name'];
$body = str_replace("{{fname}}",$fname,$body);
}
For some reason everything is coming out unique except the {{fname}} is using the first name in the first loop for every fname in the loop. If the first person is Joe, it's making every fname Joe
Because you are using one $body over and over again, and once the replacement has been made there is nothing more to replace. Use a fresh version of $body on every iteration.
foreach($customermarketingarray as $key => $value){
$customeremail = $value['email'];
$fname = $value['first_name'];
$tempBody = str_replace("{{fname}}",$fname,$body);
// now use this $tempBody for display
}
This way on every iteration of your loop you get a new template from $body again and you can make replacements to it and then use it.
First time you are using str_replace it replaces occurrences of {{fname}} in entire body. There is nothing to replace in further loop iterations.
Use preg_replace which has additional parameter (limit) which states how many replacements will be made at most. In your example if there is only one {{fname}} per each name using 1 as count parameter will do.
Read the documentation. It's pretty self explanatory.
http://php.net/manual/en/function.preg-replace.php
Another thing is problem with construction of your data. You cannot distinguish, without additional rules, which {{fname}} goes to which replacement.
It is not clear whether you want to use $body as template (I've assumed as no, because you are not using $body for anything except replacement in loop iterations). My answer is valid if there are multiple occurrences of {{fname}} in body and you want to replace them one by one with names from loop iterations.
You are replacing the variable $body in each loop. Just use a new variable to store the result. See my example below.
<?php
$customermarketingarray=array(
0=>array("email"=>"1#test.com","first_name"=>"Joe1"),
1=>array("email"=>"2#test.com","first_name"=>"Joe2"),
2=>array("email"=>"3#test.com","first_name"=>"Joe3"),
3=>array("email"=>"4#test.com","first_name"=>"Joe4")
);
$body="First Name: {{fname}}<br>Email: {{email}}<br><br>";
foreach($customermarketingarray as $key => $value){
$customeremail = $value['email'];
$fname = $value['first_name'];
$email = $value['email'];
$res_body .= str_replace(array("{{fname}}","{{email}}"),array($fname,$email),$body);
}
echo $res_body;
?>
The result for the above code is
First Name: Joe1
Email: 1#test.com
First Name: Joe2
Email: 2#test.com
First Name: Joe3
Email: 3#test.com
First Name: Joe4
Email: 4#test.com
Using preg_replace
It can be done using preg_replace instead str_replace
Answer: PHP variables and loops in HTML format
go through and check deprecated, http://php.net/manual/en/function.preg-replace.php
$body_message = $body;
foreach($customermarketingarray as $key => $value){
$customeremail = $value['email'];
$fname = $value['first_name'];
// $body = str_replace("{{fname}}",$fname,$body);
$body_message = preg_replace("/{{(.*?)}}/e","#$$1", $body);
}
Using str_replace
$body_message = $body;
foreach($customermarketingarray as $key => $value){
$customeremail = $value['email'];
$fname = $value['first_name'];
$body_message = str_replace("{{fname}}",$fname,$body);
}
I have a form with more than 20 input fields. The PHP mail function is not working since it can only accept 5 parameters. How can I send these values to my email address?
$to = 'myemail#mydomain.com';
$subject = 'form values';
$message = '';
foreach( $_POST as $key => $ value ) {
$message .= $key . ' => ' . $value . '<br>';
}
mail( $to, $subject, $message);
The parameters in the PHP mail() function have different meaning. They are not the data, sent to the user. Try using the following script and if it works - format the $message to match your requirements.
$email = 'rec#example.com';
$subject = 'Subject';
$message = print_r($_POST,true);
mail($email,$subject,$message);
More information can be found # http://php.net/manual/en/function.mail.php
Well I don't know what kind of input fields you have, but they could all be passed in the "subject" field. However, if you have a sufficiently complex email to send, and you really need to write everything yourself, you should look into PEAR.
So either add the 20 input fields onto the subject $subject .= 20things or use a tool that is inherently secure without having to remember to escape input and validate using regex.
I have a form with inputs for 'name' and 'email'. And another for 'data-1'. The user can click on add button and jQuery will dynamically add a input for 'data-2', 'data-3' etc..as needed.
The form is posted to a PHP emailer script which validates fields and places data into a template for mailing.
How can i add inputs 'data-2', 'data-3' etc.. if they are created? And if they are not how can i avoid gaps in my email template?
(is there a way to write it so if the post is received add this and if not do nothing?)
Here is an example of the code i am using:
$name = $_POST['name'];
$email = $_POST['email'];
$data-1 = $_POST['data-1'];
(do i need to add: $data-2 = $_POST['data-2'] and $data-3....up to a set value of say 10?)
$e_body = "You were contacted by $name today.\r\n\n";
$e_data = "Data Set 1: $data-1.\r\n\n";
Here is where i would like to show "Data Set 2/3/4....etc" if they exist
$e_reply = "You can contact $name via email, $email";
$msg = $e_body . $e_data . $e_reply;
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n")) {
I hope that is clear and thank you for any help or guidance
thom
You should be using input arrays for this purpose.
In your HTML, set the name of the form element to conform to this naming scheme: data[].
Then, when the form is submitted you can simply loop through this array and add fields to the email within the loop:
$name = $_POST['name'];
$email = $_POST['email'];
$data = $_POST['data'];
$e_data = '';
foreach($data as $i => $d) {
if((int) $i != $i) continue; //thanks Alex
$e_data .= "Data Set {$i}: " . $d . "\r\n\n";
}
//...
On the client side, your code should be something like this:
<input type="hidden" name="data[]"/>
As a general point form processing is trick and has many traps for the unwary. It's worth having a look at this post on best practice form processing
The crux of your problem is that you do not know how many "data" values you will get in your $_POST array. The answer is simply to iterate over the $_POST array to find your data values.
$rawData = array();
foreach ($_POST as $index => $value) {
// Test for a "data-n" index
if ((preg_match('#^data-\d+#i', $index, $matches))) {
$rawData[] = $value;
}
}
The above code will copy all the $_POST values with keys of the form 'data-0', 'data-1', etc. You can then filter and validate these values.
All we do is iterate over $_POST to get each key and value. We then test the key using preg_match to see if it starts with the string 'data-' and is followed by one or more digits. If so, we add it to our raw (unfiltered, non validated) data.
In this example, we could replace the preg_match with the strpos function -
if ( strpos ($index, 'data-') === 0) {
The use of the preg_match gives us more flexibility. For example, if you wanted to capture the numeric portion of your 'data-n' keys - 'data-23', 'data-999', 'data-5', etc. Then change the if statement to
if ((preg_match('#^data-(\d+)#i', $index, $matches))) {
$rawData[$matches[1]] = $value;
}
The variable $matches is an array that captures the results of the search. The complete matching string is is $matches[0]. However, we have enclosed the digit matching pattern in parenthesis and hence the captured digits are placed into $matches1 which we then use to key the $rawData array. In this case $rawData would have the keys = 23, 999 and 5.
Use something like this:
if(isset($_POST['data-1']))
{
// $_POST['data-1'] exists, include it.
}
else
{
// $_POST['data-1'] doesn't exists, don't include it.
}
okay, here is the code
while (!feof($text)) {
$name = fgets($text);
$number = fgets($text);
$carrier = fgets($text);
$date = fgets($text);
$line = fgets($text);
$content = $_POST['message'];
$message .= $content;
$message .= "\n";
$number = $number;
mail("$number#vtext.com", "Event Alert", $message, "SGA");
Header("Location: mailconf.php");
}
I am trying to get a message sent to a phone, I have 'message' coming in from a text area, and then I assign it to "$content" then I put "$content" into "$message" and then as you can see, in my mail line, I want the address to be the variable "number"#vtext.com I have the while loop because there are many people in these files I wish to send a message to...
When I change the "$number#vtext.com" to my email address, it sends everything fine, I just cannot seem to get it to send to a phone number, please help!
thanks!
The problem is that fgets includes the newline character as part of the return. So you are effectively sending an email to:
1234567890
#vtext.com
Which of course is invalid. Change your line that reads $number = $number to:
$number = trim($number);
And the rest of your code should function as expected, with the email being received on your phone.
Part of my original answer
I would highly recommend using a (probably paid) service to send SMS messages to phones if you need anything remotely reliable. A quick search yielded a few results:
PHP/SMS Tutorial
A list of 5 ways to Text for free <-- This link is dated, but might still be helpful
You need to append the number variable and the "#vtext.com" literal string together:
mail($number . "#vtext.com", "Event Alert", $message, "SGA");