I am creating a form builder plugin for wordpress. Within the plugin settings, the user can set the recipient email address - the code for this is in file class-form-builder.php.
I have a file called class-send-form.php that is a php mail handler. I am trying to add the email address that is entered by the user to this file but returning an error.
In class-form-builder.php I have the following code:
class Layers_Form_Builder_Widget extends Layers_Widget {
...
function send_to_email() {
return 'sam#skizzar.com';
}
...
}
At the minute I am using a hardcoded email address to try and get that working before I grab the value inputted by the user.
Then in class-send-form.php I have the following code:
require_once('../../../../wp-load.php');
$layers_email_address = Layers_Form_Builder_Widget::send_email_to();
// if there are any errors in our errors array, return a success boolean of false
if (!empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
parse_str($_REQUEST['formData'], $formFields);
$html='<html><body>';
foreach ($formFields as $key => $value) {
$html .= '<p><label>' . $key . ' :</label> ' . $value . '</p>';
}
$html .='</body></html>';
$to = $layers_email_address;
$subject = "Form Submission";
$txt = $html;
$headers = "From: <".$to.">". "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1"."\r\n";
mail($to,$subject,$txt,$headers);
// if there are no errors process our form, then return a message
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Success!';
}
// return all our data to an AJAX call
echo json_encode($data);
However, when I click send, I just get an error ("there was an error when submitting your form").
How can I get the value of the email address from class-form-builder.php and use it in class-send-form.php?
The function name used in class-send-form.php is send_email_to() and the function name defined in class-form-builder.php is send_to_email().
I think once you fix that, it will work.
Related
I'm having a problem using a mailing function in a php ecomm app I purchased from envato. The developer has a mailer function which is used to send emails from the website.
Function :
/* Send mail with custom templates:$template : E-mail template.$array : Variables for email template. $subject : E-mail Subject.$to : E-mail receiver.*/
function mailing($template,$array,$subject,$to) {
$cfg = DB::select('SELECT * FROM config WHERE id = 1')[0];
$array['url'] = url('');
$array['name'] = $cfg->name;
$array['address'] = nl2br($cfg->address);
$array['phone'] = $cfg->phone;
$array['email'] = $cfg->email;
// Get the template from the database
$message = DB::select("SELECT template FROM templates WHERE code = '".$template."'")[0]->template;
foreach ($array as $ind => $val) {
$message = str_replace("{{$ind}}",$val,$message);
}
$message = preg_replace('/\{\{(.*?)\}\}/is','',$message);
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: '.$cfg->name.' <'.$cfg->email.'>'."\r\n";
mail($to,$subject,$message,$headers);
return true;
}
The email template is pulled from the db.
As part of the checkout process in the API.php file, the mailer function is used to email the order to the user with the follwing code:
// Send an email to customer
mailing(
'order',
array( 'buyer_name'=>$data['name'],
'buyer_email'=>$data['email'],
'buyer_fields'=>$email_fields,
'name'=>$this->cfg->name,
'address'=>$this->cfg->address,
'phone'=>$this->cfg->phone,
'products'=>$email_products,
'total'=>$total
),
'Order Confirmation #'.$order,
$data['email']
);
This is fine, however, I'm trying to get that to also send myself the email of the order as opposed to having to check the admin ux as is currently the way it works. Could anyone point me in the right direction ?
Many Thanks in advance.
The simple answer is to add another call to mail() an replace $to with your email address in the mailing() function.
But as this is probably used in more than one place in the app, it might be nice to add a parameter to this function that tells it to email to you as well as the intended recipient
function mailing($template,$array,$subject,$to, $toMe=false) {
// new parameter ^^^^^^^^^^^
$cfg = DB::select('SELECT * FROM config WHERE id = 1')[0];
$array['url'] = url('');
$array['name'] = $cfg->name;
$array['address'] = nl2br($cfg->address);
$array['phone'] = $cfg->phone;
$array['email'] = $cfg->email;
// Get the template from the database
$message = DB::select("SELECT template FROM templates WHERE code = '".$template."'")[0]->template;
foreach ($array as $ind => $val) {
$message = str_replace("{{$ind}}",$val,$message);
}
$message = preg_replace('/\{\{(.*?)\}\}/is','',$message);
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: '.$cfg->name.' <'.$cfg->email.'>'."\r\n";
mail($to,$subject,$message,$headers);
// now mail yourself if $toMe is true
if ( $toMe !== false ) {
mail($toMe,$subject,$message,$headers);
}
return true;
}
Then anywhere in the app where it sends mail yo can add a request to get a copy of the email. BUT, if you dont add the new parameter, the mailing() function will act just as it did before.
// Send an email to customer
mailing(
'order',
array( 'buyer_name'=>$data['name'],
'buyer_email'=>$data['email'],
'buyer_fields'=>$email_fields,
'name'=>$this->cfg->name,
'address'=>$this->cfg->address,
'phone'=>$this->cfg->phone,
'products'=>$email_products,
'total'=>$total
),
'Order Confirmation #'.$order,
$data['email'],
'me#mymail.com' // new parameter added
);
Now none of the existing calls to mailing will be effected, because you used a default value in the function prototype, unless you add the extra parameter to the call to mailing but any of them you want to alter can be done easily, and as you specify the address when you want to get a copy, you can use any of your email addresses.
Just add another
mail($to,$subject,$message,$headers);
line and replace $to with your email. That's it.
I am trying to parse some HTML from files into a PHP variable to send across HTML email, but I am struggling. It doesn't output anything at all when loaded. Only the submit button is echoed. What am I doing wrong? I know it's probably a lot, but can someone please advise me on how to get this to work?
I will end up using AJAX for the submit button so the page isn't reloaded, but the content (at the moment) isn't even displaying. It's a lot of code, so I decided to break it up into files to make it easier to read and easier to inject.
<?php
// Setting mail options
$to = $_POST["clientemail"];
$subject = $_POST["subject"];
// Are we debugging?
$debug = true;
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: CodexWorld<"postmaster#intel-web.co.uk">' . "\r\n";
$headers .= 'Cc: b.ravetta#gmail.com' . "\r\n";
$headers .= 'Bcc: admin#intel-web.co.uk' . "\r\n";
// Place all HTML content into one big fucking message.
$head = file_get_contents("head.html");
$body = file_get_contents("body.html");
$footnotes = file_get_contents("footer.html");
if($_POST["packageid"] == 1)
{
$content = file_get_contents("fb.html");
}
if($_POST["packageid"] == 2)
{
$content = file_get_contents("aw.html");
}
if($_POST["packageid"] == 3)
{
$content = file_get_contents("mobi.html");
};
$messagecontent =
echo $head;
echo $body;
echo $content;
echo $footnotes;
;
// Where the message content ends.
echo "<form method='POST' action=''>
<input type='submit' name='sendmail' value='Send Email'>
</form>";
if (isset($_POST['sendmail']))
if(mail($to,$subject,$messagecontent,$headers)):
$successMsg = 'Email has sent successfully.';
else:
$errorMsg = 'Email sending fail.';
endif;
// Debug Shit
if ($debug)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting("E_STRICT")
?>
I'm surprised that you even get a submit button at all. Because
$messagecontent =
echo $head;
echo $body;
echo $content;
echo $footnotes;
;
should actually raise a syntax error for an unexpected T_ECHO.
If you want to concatenate a string, that's how you do it:
$messagecontent = $head . $body . $content . $footnotes;
If you fix that, you will still only get the submit button after submitting the form, because while you will send the mail, you do nothing with your success / error message. You might want to do something like
if (isset($_POST['sendmail'])) {
if(mail($to,$subject,$messagecontent,$headers)) {
$successMsg = 'Email has sent successfully.';
echo $successMsg;
} else {
$errorMsg = 'Email sending fail.';
echo $errorMsg;
}
}
(Note: I also changed the syntax of your if statements to an accepted standard. see http://www.php-fig.org/psr/)
Also, you might want to change the error reporting settings in the php.ini and not in the file. Because if you do have a parse error, you won't see it (because the file can't be parsed and so display_errors won't get set to 1.
I have built a form builder plugin. The last step is to get the emails to send to the site admin, however, I can't seem to figure out how to make this work. Here is my php mail handler:
if (!empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
parse_str($_REQUEST['formData'], $formFields);
$html='<html><body>';
foreach ($formFields as $key => $value) {
$html .= '<p><label>' . $key . ' :</label> ' . $value . '</p>';
}
$html .='</body></html>';
$to = get_option('admin_email');
$subject = "Form Submission";
$txt = $html;
$headers = "From: <sam.skirrow#gmail.com>". "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1"."\r\n";
mail($to,$subject,$txt,$headers);
// if there are no errors process our form, then return a message
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Success!';
}
// return all our data to an AJAX call
echo json_encode($data);
You can see in my $to variable I have added get_option('admin_email'); however, doing this breaks my form (as opposed to just writing an email address in.
You need to load WordPress to be able to use their get_option function.
Add this to the top of your PHP script:
require_once('../../../wp-load.php');
I have this simple form to email in php. The nice thing about this form in the send php code is that I do NOT have to write out all the fields name.For example, I do NOT have to write this:
$msg .= "$_POST[ContactName] Contact Name: ContactName\n"
In my code, all I have to write is:
foreach ($_POST as $Field=>$Value) {
$body .= "$Field: $Value\n";
The form is currently working perfectly. It is currently sending this:
ContactName: name here
BusinessName: business name here
EmailAddress: email#email.com
Email_Confirmation:
PhoneNumber: 714-555-5555
However, I wish this to happen: If a field is left empty or the web user does not fill it a certain field box, then the form should NOT send this field. For example: web user decides to NOT fill in ContactName and or BusinessName. So the form should only send this format:
EmailAddress: email#email.com
Email_Confirmation:
PhoneNumber: 714-555-5555
Noticed no mention of ContactName: and BusinessName:
Please help! I would appreciate it. -Michelle Ha.
Here is the php send code:
if the Email_Confirmation field is empty
if(isset($_POST['Email_Confirmation']) && $_POST['Email_Confirmation'] == ''){
// put your email address here
$youremail = 'bomandty#gmail.com';
// prepare a "pretty" version of the message
$body .= "Thank you for your request. We will get back with you soon.";
$body .= "\n";
$body .= "\n";
foreach ($_POST as $Field=>$Value) {
$body .= "$Field: $Value\n";
$body .= "\n";
}
$CCUser = $_POST['EmailAddress'];
// Use the submitters email if they supplied one
// (and it isn't trying to hack your form).
// Otherwise send from your email address.
if( $_POST['EmailAddress'] && !preg_match( "/[\r\n]/", $_POST['EmailAddress']) ) {
$headers = "From: $_POST[EmailAddress]";
} else {
$headers = "From: $youremail";
}
// finally, send the message
mail($youremail, 'subject line here', $body, $headers, $CCUser );
}
// otherwise, let the spammer think that they got their message through
foreach ($_POST as $Field=>$Value) {
if($Value != ''){
$body .= "$Field: $Value\n";
}
}
Add check to you foreach
if(empty($Value)) continue;
And change default falue in your form to placeholders
I have a contact form on my website, and everything works like a charm. I am using a anti-injection validation script, that I suspect is supposed to send a notification when somebody attempts to use header injection. I have tested this thouroghly and cannot determine why it will not notify me on the event of an abuse. The script is below.
<?php
/* Set e-mail recipient */
$myemail = "email#gmail.com";
/* Check all form inputs using check_input function */
$subject = check_input($_POST['subject'], "Please enter your name");
$email = check_input($_POST['email'], "Please enter your email");
$form = check_input($_POST['form'], "Please write your message");
function logbad($value)
{
// Start of validation; this is where the problem is
$report_to = "email#gmail.com";
$name = "Matt";
$mail = "$email";
// replace this with your own get_ip function...
$ip = (empty($_SERVER['REMOTE_ADDR'])) ? 'empty'
: $_SERVER['REMOTE_ADDR'];
$rf = (empty($_SERVER['HTTP_REFERER'])) ? 'empty'
: $_SERVER['HTTP_REFERER'];
$ua = (empty($_SERVER['HTTP_USER_AGENT'])) ? 'empty'
: $_SERVER['HTTP_USER_AGENT'];
$ru = (empty($_SERVER['REQUEST_URI'])) ? 'empty'
: $_SERVER['REQUEST_URI'];
$rm = (empty($_SERVER['REQUEST_METHOD'])) ? 'empty'
: $_SERVER['REQUEST_METHOD'];
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\n";
$headers .= "X-Priority: 1\n";
$headers .= "X-MSMail-Priority: Normal\n";
$headers .= "X-Mailer: php\n";
$headers .= "From: \"".$nama."\" <".$mail.">\r\n\r\n";
#mail
(
$report_to
,"[ABUSE] mailinjection # " .
$_SERVER['HTTP_HOST'] . " by " . $ip
,"Stopped possible mail-injection # " .
$_SERVER['HTTP_HOST'] . " by " . $ip .
" (" . date('d/m/Y H:i:s') . ")\r\n\r\n" .
"*** IP/HOST\r\n" . $ip . "\r\n\r\n" .
"*** USER AGENT\r\n" . $ua . "\r\n\r\n" .
"*** REFERER\r\n" . $rf . "\r\n\r\n" .
"*** REQUEST URI\r\n" . $ru . "\r\n\r\n" .
"*** REQUEST METHOD\r\n" . $rm . "\r\n\r\n" .
"*** SUSPECT\r\n--\r\n" . $value . "\r\n--"
,$headers
);
}
// Check 1
//First, make sure the form was posted from a browser.
// For basic web-forms, we don't care about anything
// other than requests from a browser:
if(!isset($_SERVER['HTTP_USER_AGENT']))
{
die('Forbidden - You are not authorized to view this page (0)');
exit;
}
// Cek 2
// Make sure the form was indeed POST'ed:
// (requires your html form to use: action="post")
if(!$_SERVER['REQUEST_METHOD'] == "POST")
{
die('Forbidden - You are not authorized to view this page (1)');
exit;
}
// Host names from where the form is authorized
// to be posted from:
$authHosts = array("cover.com");
// Where have we been posted from?
$fromArray = parse_url(strtolower($_SERVER['HTTP_REFERER']));
// Test to see if the $fromArray used www to get here.
$wwwUsed = strpos($fromArray['host'], "www.");
// Make sure the form was posted from an approved host name.
if(!in_array(($wwwUsed === false ? $fromArray['host'] : substr(stristr($fromArray['host'], '.'), 1)), $authHosts))
{
logbad("Form was not posted from an approved host name");
die(' Forbidden - You are not authorized to view this page (2)');
exit;
}
// Attempt to defend against header injections:
$badStrings = array("content-type:",
"mime-version:",
"content-transfer-encoding:",
"multipart/mixed",
"charset=",
"bcc:",
"cc:");
// Loop through each POST'ed value and test if it contains
// one of the $badStrings:
foreach($_POST as $k => $v)
{
foreach($badStrings as $v2)
{
if(strpos(strtolower($v), $v2) !== false)
{
logbad($v);
die('<strong>Form processing cancelled:<br /></strong> string
(`'.$v.'`)<strong> contains text portions that
are potentially harmful to this server. <br />Your input
has not been sent! <br />Please use your browser\'s
`back`-button to return to the previous page and try
rephrasing your input.</strong>');
exit;
}
}
}
// Made it past spammer test, free up some memory
// and continuing the rest of script:
unset($k, $v, $v2, $badStrings, $authHosts, $fromArray, $wwwUsed);
/* If e-mail is not valid show error message */
$addr_spec = '([^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'.
'\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+|\\x22([^\\x0d'.
'\\x22\\x5c\\x80-\\xff]|\\x5c[\\x00-\\x7f])*\\x22)'.
'(\\x2e([^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e'.
'\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+|'.
'\\x22([^\\x0d\\x22\\x5c\\x80-\\xff]|\\x5c\\x00'.
'-\\x7f)*\\x22))*\\x40([^\\x00-\\x20\\x22\\x28'.
'\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d'.
'\\x7f-\\xff]+|\\x5b([^\\x0d\\x5b-\\x5d\\x80-\\xff'.
']|\\x5c[\\x00-\\x7f])*\\x5d)(\\x2e([^\\x00-\\x20'.
'\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40'.
'\\x5b-\\x5d\\x7f-\\xff]+|\\x5b([^\\x0d\\x5b-'.
'\\x5d\\x80-\\xff]|\\x5c[\\x00-\\x7f])*\\x5d))*';
if (!preg_match("!^$addr_spec$!", $email))
{
show_error("E-mail address not valid");
}
if (strtolower($_POST['code']) != 'rowingcover') {die('The following error occured: <br />Wrong anti-spam code. <br />
Go back');}
/* Let's prepare the message for the e-mail */
$message = "Cover.com Contact Form
From:
$subject
$email
Message
$form
";
/* Send the message using mail() function */
mail($myemail, $subject, $message, "From: $email");
/* Redirect visitor to the thank you page */
header('Location: contact_received.html');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?><br />
Go back
</body>
</html>
<?php
exit();
}
?>
I am relatively new to php, so any help would be much appreciated.
Thanks,
Matt
Your problem might be that you are using double quotes with # in your variable:
should be: $report_to = 'email#gmail.com'; or $report_to = "email\#gmail.com";
Just posting as answer from my comment since you got it solved by that.
The thing was that using an array inside a variable without scaping it will result in a empty array in your case which would give you a possible wrong email.
You welcome :)
I have found a few things that might contribute to that.
1)
$mail = "$email";
$email isn't defined (you're inside a function), and there is no reason to put quotes around a variable. This means $mail = "";
2)
$headers .= "From: \"".$nama."\" <".$mail.">\r\n\r\n";
You said $nama instead of $name, this means that line is actually:
$headers .= "From: <>\r\n\r\n";
It's a bit difficult to see the reason. Try defining your subject and message before your mail function (makes it much easier to read).
Don't use the "#mail" as that will NOT tell you any errors it runs into. While debugging, you definitely want error messages.
Try sending a normal text email before you send an HTML error (in that function), it might help make things simple. Then slowly implement HTML, see where it breaks.
This following lines looks wrong.
$mail = "$email"; should be $mail = $email;
#mail( should be just mail( This is probably the line preventing your mail being sent!
mail($myemail, $subject, $message, "From: $email"); should be
mail($myemail, $subject, $message, "From:".$email);
Hope that helps.
Thanks to Prix who answered my question in the comments:
$report_to = "email#gmail.com"; either
use single quote or scape the #
$report_to = 'email#gmail.com'; or
$report_to = "email\#gmail.com"; since
the # is treathed as an array it will
not read as email#gmail.com under
double quotes. – Prix 4 mins ago