Note: E-Mail address removed for privacy purposes.
Whenever the form executes this script, it returns the success JSON array at the end, however, the e-mail is never received at the e-mail address specified.
<?php
if(empty($_POST['fullname']) || empty($_POST['phonenumber']) || empty($_POST['emailaddress']))
{
$response = array('status' => 0, 'txt' => 'Please verify all required fields are complete.');
echo json_encode($response);
die();
}
if(!(preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['emailaddress'])))
{
$response = array('status' => 0, 'txt' => 'Please Provide a Valid E-Mail Address.');
echo json_encode($response);
die();
}
$name = mysql_real_escape_string($_POST['fullname']);
$phonenumber = mysql_real_escape_string($_POST['phonenumber']);
$email = mysql_real_escape_string($_POST['emailaddress']);
$comments = mysql_real_escape_string($_POST['comments']);
$emailbody = 'Name: ' . $name . '
Phone Number: ' . $phonenumber . '
E-Mail Address: ' . $email . '
Comments: ' . $comments . ' ';
mail("example#example.com","New Consultation Request",$emailbody,"From: noreply#example.com");
$response = array('status' => 1, 'txt' => 'consultation-request-successful');
echo json_encode($response);
?>
You've never bothered connecting to the database, so mysql_real_escape_string() is going to be turning a boolean FALSE for failure - it REQUIRES an active connection to the DB to do its work.
That means your $name, $phonenumber, $email, $comments are all going to be boolean FALSE, and translated into an empty string when you build your mail text.
As well, using mysql escaping for a simple email is beyond utterly pointless. Email is not vulnerable to SQL injection attacks.
Related
<?php
var_dump($_POST);
if(isset($_POST['email'])
&& isset($_POST['name'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
}
else {
$name = $_POST["name"];
var_dump($name);
// check if name only contains letters and whitespace for first name
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space
allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
}
else {
$email = $_POST["email"];
var_dump($email);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if($data = $_POST['name'] . "\n" .
$_POST['email'] . "\n" .
$_POST['phone'] . "\n" .
$_POST['county'] . "\n" .
$_POST['floor'] . "\n" .
$_POST['descr'] . "\n"){
echo "Thank you for your inquery!" . "<br/>" .
"an estimator will be with you shortly.";
mail('myemail#gmail.com', 'Estimation Request',
$data);
}
}
else {
die('no post data to process');
}
?>
The output:
array(5) { ["name"]=> string(12) "Nicholas Cox" ["email"]=> string(6)
"######" ["phone"]=> string(10) "0000000000" ["county"]=> string(8)
"Pinellas" ["descr"]=> string(15) "Thesh " }
string(12) "Nicholas Cox" string(6) "######"
Thank you for your inquery!
an estimator will be with you shortly.\n\nInvalid email format\n
Note: if i missed taking out some of my troubleshooting steps like the random echos or die functions please let me know so i can edit to
help you be able to read it easier
I have not added validation on the other fields. I'm just trying to get the email and name to work before i add to the others.
Right now, when i add random stuff it will still prompt me with my error message but it still allows anything to be put in the text field AND sends the email. I've watched a few tutorials on youtube and i still can't get it right.
Example what you can do with validation with your code.
<?php
var_dump($_POST);
$errorArr = array(); //Error Messages in array
if(isset($_POST['email'])
&& isset($_POST['name'])) {
if (empty($_POST["name"])) {
$errorArr['nameErr'] = "Name is required"; //Error Messages in array
}
else {
$name = $_POST["name"];
var_dump($name); // This should be commented
// check if name only contains letters and whitespace for first name
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$errorArr['nameErr'] = "Only letters and white space
allowed";//Error Messages in array
}
}
if (empty($_POST["email"])) {
$errorArr['emailErr'] = "Email is required";
}
else {
$email = $_POST["email"];
var_dump($email); // This should be commented
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errorArr['emailErr'] = "Invalid email format";
}
}
//Check Condition for any error
if(empty($errorArr)){
$data = $_POST['name'] . "\n" .
$_POST['email'] . "\n" .
$_POST['phone'] . "\n" .
$_POST['county'] . "\n" .
$_POST['floor'] . "\n" .
$_POST['descr'] . "\n"
echo "Thank you for your inquery!" . "<br/>" .
"an estimator will be with you shortly.";
mail('theshadowcallsu#gmail.com', 'Estimation Request',
$data);
} else {
var_dump($errorArr); //Show Error Message
}
}
else {
die('no post data to process');
}
?>
While there are other issues, the problem that made you ask here lies within this condition:
if ($data = $_POST['name'] . "\n" .
$_POST['email'] . "\n" .
$_POST['phone'] . "\n" .
$_POST['county'] . "\n" .
$_POST['floor'] . "\n" .
$_POST['descr'] . "\n")
I really don't know what your intention behind it is, but let's take it apart:
$_POST contains strings
. concatenates strings
\n is a line break
Hence, the whole thing, simplified, boils down to:
if ($data = $someLongStringFromMyPostValues)
Now, $data = $something is an assignment and an expression. In PHP (and many other languages), such an assignment evaluates (returns) the value that was assigned. In other words, this sets your $data variable to the long string, but regarding the condition, this is pretty much equivalent to:
if ($someLongStringFromMyPostValues)
Due to type juggling in PHP, a string with something (other than 0) in it will be true. Seeing how you add line breaks to the string, this means that, no matter what is in your $_POST values, this will always evaluate to (again, ignoring $data for now):
if (true)
You are, in no way, regarding the $nameErr or $emailErr variables that you set before that. So, whatever your intention, you need to fix this condition and incorporate your error variables into it.
I have been trying to solve this in all ways I can figure out, but have surely missed something. I've tried to access the fields using for-loops, just calling it, arrays, objects etc. I just can't get it to work.
What I'm talking about is to check if a provided email in a form already is subscribing to my maillist at MailGun. I don't know how to check this and I've been searching the web for answer for about 1-2 hours now and I'm finally asking here aswell.
My code so far:
<?php
session_start();
ini_set('display_errors', 1);
require_once 'init.php';
if (!isset($_POST['email']) && isset($_POST['name'])) {
echo 'You have to provide an email!';
} else if (!isset($_POST['name']) && isset($_POST['email'])) {
echo 'You have to provide a name!';
} else if (isset($_POST['name'], $_POST['email'])) {
$name = $_POST['name'];
$email = $_POST['email'];
// This is temporary to test and only works if an email existing is provided.
// If an invalid email is provided, an error is cast
// See below for the error
if (!$mailgun->get('lists/' . MAILGUN_LIST . '/members' . $email)) {
echo "Email doesnt exist";
die();
$validate = $mailgunValidate->get('address/validate', [
'address' => $email
])->http_response_body;
if ($validate->is_valid) {
$hash = $mailgunOptIn->generateHash(MAILGUN_LIST, MAILGUN_SECRET, $email);
$mailgun->sendMessage(MAILGUN_DOMAIN, [
'from' => 'noreply#adamastmar.se',
'to' => $email,
'subject' => 'Please confirm your subscription to the mailing list',
'html' => "
Hello {$name},<br><br>
You signed up to our mailing list. Please confirm your subscription below.<br><br>
<a href='http://www.adamastmar.se/confirm.php?hash={$hash}'>Click here to confirm</a>"
]);
$mailgun->post('lists/' . MAILGUN_LIST . '/members', [
'name' => $name,
'address' => $email,
'subscribed' => 'no'
]);
$_SESSION['joined'] = "A message has been sent to the provided email. Please confirm the subscription by clicking the link in the mail.";
header('Location: ./');
}
} else {
$_SESSION['alreadysub'] = "You are already a subscriber to this list!";
header('Location: ./');
}
}
?>
The error I get if I use the code above:
Uncaught exception 'Mailgun\Connection\Exceptions\MissingEndpoint' with message 'The endpoint you've tried to access does not exist.
Check your URL.' in /home/jivusmc/domains/adamastmar.se/public_html/vendor/mailgun/mailgun-php/src/Mailgun/Connection/RestClient.php:258
Stack trace: #0 /home/jivusmc/domains/adamastmar.se/public_html/vendor/mailgun/mailgun-php/src/Mailgun/Connection/RestClient.php(110):
Mailgun\Connection\RestClient->responseHandler(Object(GuzzleHttp\Psr7\Response))
#1 /home/jivusmc/domains/adamastmar.se/public_html/vendor/mailgun/mailgun-php/src/Mailgun/Connection/RestClient.php(195):
Mailgun\Connection\RestClient->send('GET', 'lists/news#mail...') #2 /home/jivusmc/domains/adamastmar.se/public_html/vendor/mailgun/mailgun-php/src/Mailgun/Mailgun.php(215):
Mailgun\Connection\RestClient->get('lists/news#mail...', Array) #3 /home/jivusmc/domains/adamastmar.se/public_html/mailinglist.php(16):
Mailgun\Mailgun->get('lists/news#mail...') #4 {main} thrown in /home/jivusmc/domains/adamastmar.se/public_html/vendor/mailgun/mailgun-php/src/Mailgun/Connection/RestClient.php on line 258
Any help & tips/tricks is appreciated!
I found a solution to the issue I had. Instead of doing everything in an if-statement, I instead surrounded it in a try-catch. I try to check if the email can be fetched from the mailgun list and if it fails, it catches the error and instead adds the mail to the list. (I'm posting it here since it's nearly impossible to find a solution to this in a better way)
$name = $_POST['name'];
$email = $_POST['email'];
try {
$mailgun->get('lists/' . MAILGUN_LIST . '/members/' . $email);
$_SESSION['alreadysub'] = "You are already a subscriber to this list!";
header('Location: ./');
} catch (Exception $e) {
$validate = $mailgunValidate->get('address/validate', [
'address' => $email
])->http_response_body;
if ($validate->is_valid) {
$hash = $mailgunOptIn->generateHash(MAILGUN_LIST, MAILGUN_SECRET, $email);
$mailgun->sendMessage(MAILGUN_DOMAIN, [
'from' => 'noreply#adamastmar.se',
'to' => $email,
'subject' => 'Please confirm your subscription to the mailing list',
'html' => "
Hello {$name},<br><br>
You signed up to our mailing list. Please confirm your subscription below.<br><br>
<a href='http://www.adamastmar.se/confirm.php?hash={$hash}'>Click here to confirm</a>"
]);
$mailgun->post('lists/' . MAILGUN_LIST . '/members', [
'name' => $name,
'address' => $email,
'subscribed' => 'no'
]);
$_SESSION['joined'] = "A message has been sent to the provided email. Please confirm the subscription by clicking the link in the mail.";
header('Location: ./');
}
}
I know this problem and the answer are in PHP. But I just figured out a way in NodeJS and wish I've found a solution for it earlier. Maybe it helps someone.
FYI: I'm checking if an email exists in mailing list from Mailgun.
var DOMAIN = 'YOUR_DOMAIN_NAME';
var mailgun = require('mailgun-js')({ apiKey: "YOUR_API_KEY", domain: DOMAIN});
const array = await mailgun.getList().catch(console.error);
if(checkIfEmailExcistInMailinglist(array.items, dbUser.email)){
// if then do something
}
checkIfEmailExcistInMailinglist(array, email) {
for (var i = 0; i < array.length; i++) {
if (array[i].address === email) {
return true;
}
}
return false;
}
I'm working on adding a script to my site for a MailChimp subscribe form. I think I have everything setup right but when I hit the subscribe button I'm getting a blank page.
Here is the script I have currently
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require_once 'Mailchimp.php';
$apikey = "XXXXXXXXXXXXXXX";
$Mailchimp = new Mailchimp($apikey);
if (!empty($_POST)) {
$id = "XXXXXXXXXX";
$email = array(
'email' => trim($_POST['email'])
);
$result = $Mailchimp->$lists->subscribe($id, $email, $double_optin=false, $replace_interests=false);
var_dump($result);
}
echo "TESTING";
So I'm not getting the $result variable or "TESTING echo'd right now, so I assume I must be doing something simple wrong. Anyone see anything obvious? I believe I'm using the correct default JSON format. (keys have been X'd out, but the one's I'm using are correct)
Any help is much appreciated.
Thanks!!
EDIT: I have updated the code to something I believe to be more correct, but it still isn't working. I could really use some help on this.
Here's how I've handled AJAX email submissions in the past for MailChimp's API (MCAPI):
define("MC_API_KEY", "Your mailchimp API key");
define("MC_API_LIST", "The list ID to subscribe user to");
define("EMAIL_TO", "email address in case subscription fails");
require "MailChimp.API.class.php";
function json($error = true, $message = "Unknown error") {
die(json_encode(array("error" => $error, "message" => $message)));
}
if(!empty($_POST)) {
$email = !empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ? $_POST['email'] : false;
if($email !== false) {
$api = new MCAPI(MC_API_KEY);
$result = $api->listSubscribe(MC_API_LIST, $email);
if($api->errorCode || !$result) {
if(isset($api->errorCode) && $api->errorCode == 214) { // already subscribed
json(true, "You are already subscribed!");
} else {
$error = "Unable to save user email via MailChimp API!\n\tCode=".$api->errorCode."\n\tMsg=".$api->errorMessage."\n\n";
$headers = "From: your#email.com\r\nReply-to: <{$email}>\r\nX-Mailer: PHP/".phpversion();
mail(EMAIL_TO, "Newsletter Submission FAIL [MC API ERROR]", "{$error}Saved info:\nFrom: {$email}\n\nSent from {$_SERVER['REMOTE_ADDR']} on ".date("F jS, Y \# g:iA e"), $headers);
json(false, "Thank you - your email will be subscribed shortly!");
}
} else {
json(false, "Thanks - A confirmation link has been sent to your email!");
}
} else {
json(true, "Please enter your valid email address");
}
} else json();
SOLVED:
Here is the correct code - hopefully this will help others looking to use the new api -
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require_once 'Mailchimp.php';
$apikey = "XXXXXXXXXXXXXXXXXXX";
$Mailchimp = new Mailchimp($apikey);
if (!empty($_POST)) {
$id = "XXXXXXXXXX";
$email = array(
'email' => trim($_POST['email'])
);
$result = $Mailchimp->lists->subscribe($id, $email, $merge_vars=null, $double_optin=false, $replace_interests=false);
}
Using various tutorials namely here and here I've managed to put together the following PHP script which performs server side validation on the form being submitted. (I already have script which is dealing with the 'client side' validation.
<?php
//email signup ajax call
if($_GET['action'] == 'signup'){
//sanitize data
$email = mysql_real_escape_string($_POST['signup-email']);
//validate email address - check if input was empty
if(empty($email)){
$status = "error";
$message = "You did not enter an email address!";
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
$status = "error";
$message = "You have entered an invalid email address!";
}
else {
$insertSignup = mysql_query("INSERT INTO signups (signup_email_address) VALUES ('$email')");
if($insertSignup){ //if insert is successful
$status = "success";
$message = "You have been signed up!";
}
else { //if insert fails
$status = "error";
$message = "Ooops, Theres been a technical error!";
}
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
}
?>
What I'm now trying to do is to add another field, in this case 'name' which I'd like to also validate.
The problem I'm having is that I'm not sure how to add another field into the above code. Again, I've been trying to find an example which I could use to study from, but I haven't found any that I can use.
I just wondered whether someone could possibly look at this please, and perhaps point me in the right direction.
Many thanks and kind regards
PHP has a Filter extension to validate and sanitize input.
The function you are looking for is
filter_var_array — Gets multiple variables and optionally filters them
There is also filter_input_array but since there is no easy way to unit-test that properly, it is easier to use the above one instead and pass it the superglobals as needed.
Example:
$userInput = array(
'signup-email' => 'foo at example.com',
'name' => 'ArthurDent42'
);
$validatedInput = filter_var_array(
$userInput,
array(
'signup-email' => FILTER_VALIDATE_EMAIL,
'name' => array(
'filter' => FILTER_VALIDATE_REGEXP,
'options' => array(
'regexp' => "/^[a-z ]{5,10}$/i"
)
)
)
);
var_dump($validatedInput);
Output (demo):
array(2) {
["signup-email"]=> bool(false)
["name"]=> bool(false)
}
Once you have the input validated and sanitized put some guard clauses for each of the values in the array and return early when they are false:
if (!$validatedInput['signup-email']) {
return json_encode(array(
'status' => 'error',
'message' => 'The eMail was invalid'
));
}
if (!$validatedInput['name']) {
return json_encode(array(
'status' => 'error',
'message' => 'Name must be 5 to 10 letters from A to Z only'
));
}
// everything's validated at this point. Insert stuff to database now.
Note that you want to use either PDO or mysqli instead of ext/mysql.
In your HTML add a field:
<input type="text" name="name" value="" />
In your PHP:
$name = trim($_POST['name']);
To validate:
if ($name === '') {
$status = 'error';
$message = 'need a name!';
}
Now add name to your insert statement (it would be better to use PDO prepared statements):
$nameSql = mysql_real_escape_string($name);
$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, name) VALUES ('$email', '$nameSql')");
$rule['email']= '/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$`/'
$rule['name']= 'bla bla';
$rule['address']= 'bla bla';
$data = sanitize($_POST,$rule);
function sanitize($input_array,$rule){
$message = array();
foreach($input_array as $key=> $value){
$input_array[$key]= mysql_real_escape_string($value);
if(isset($rule[$key])){
if(!preg_match($rule[$key],$input_array[$key]){
$message[$key] = 'error';
unset($input_array[$key]);//optional
}
}
}
return array('data'=>$input_array,'message'=>$message);
}
I got the following code and before sending i check the fields are populated or not...when sending the email i get the message 'We have received your email .' but i cannot see the email in my inbox, tried it with two different emails but same results... cannot figure out why can you help me please. here is the code:
if($badinput == NULL){ ?>
<h2>We have received your email .</h2>
</div>
<?php
require_once("libs/inc.email_form.php");
$email_fields = array(
"Name" => $_POST['name'],
"E-Mail Address" => $_POST['email'],
"Telephone Number" => $_POST['telephone'],
"Callback" => $_POST['callback'],
"Enquiry" => $_POST['enquiry']
);
contact_form( "myemail#yahoo.co.uk", $_POST['email'], " Enquiry", "test", $email_fields);
}
else
{
echo $badinput . "</div>";
}
?>
here is the function in libs/inc.email_form.php:
function contact_form($to, $from, $subject, $message, $fields){
if(!$to || !$from || !$subject || !$message || !$fields){
print form function is missing a variable";
return false;
}
$msg_body = $message."\n\nSubmitted ".date("l, F j, Y, g:i a")." [EST]\n\nSUBMISSION DETAILS:\n";
// clean up all the variables
foreach($fields as $k => $v){
$msg_body .= "\n".$k.": ".clean_var($v);
}
// add additional info
$referer = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : "could not determine" ;
$user_agent = (isset($_SERVER['HTTP_USER_AGENT'])) ? $_SERVER['HTTP_USER_AGENT'] : "could not determine" ;
$msg_body .= "\n\nAdditional Info:\nIP = ".$_SERVER['REMOTE_ADDR']."Browser Info: ".$user_agent."Referral: ".$referer." \r";
// send it
$emailer = new emailer;
if(is_array($to)){
foreach($to as $t){
$emailer->send_email($from, $subject, $msg_body, $to);
}
}else{
$emailer->send_email($from, $subject, $msg_body, $to);
}
return true;
}
I see no reason for using a class if it's just probably still using the standard PHP mail() function.
Please try using this code to test if mail actually get sent:
if (mail('you#domain.ext', 'subject', 'test email'))
echo 'Mail was sent';
else
echo 'Mail could not be sent';
Also please check the Spam folder as many emails send through PHP mail() get flagged as spam due to incorrect or incomplete headers or because of abuse and bad IP reputation (especially if you're using shared hosting).
It doesn't seem that your actually checking the return value from the $emailer class, so the function telling you your email is sent really is just a false positive.
I would change:
$emailer->send_email($from, $subject, $msg_body, $to);
to:
$result = $emailer->send_email($from, $subject, $msg_body, $to);
print_r($result);
and check what the $emailer class is returning. more then likely it's going to be a "0" for failed or "1" for success.
Is that a 100% accurate representation of your script?
There appears to be a major syntax error, which if it somehow doesn't error out on you, will at least totally change the script's functionality.
if(!$to || !$from || !$subject || !$message || !$fields){
print form function is missing a variable";
Surely, it should be:
if(!$to || !$from || !$subject || !$message || !$fields){
print "form function is missing a variable";