Email with PHP after conditional statement - php

So, I'm trying to do a very simple thing - send an email using PHP. I've looked through other queries on stack and none of them involve a conditional statement, so I wanted to check and see if I could get some quick advice. See the conditional below that then send a confirmation / thank you email to someone who donated to my organization.
Could it be that I first have the code echoing / printing a statement and then running the mail() function?
if ((isset($_POST['submitted'])) && ($ack!="SUCCESS")) {
$_SESSION['reshash']=$resArray;
$location = "https://globalcitizenyear.org/wp-content/themes/deMar/APIError.php";
header("Location: $location");
} elseif ($ack =="SUCCESS") {
echo ("<h2>Thank You</h2><p>Thank you for your generous donation of $$amount. You will receive an email confirmation with an attached tax receipt.</p>");
$body = "Dear $firstName,
/n/nThank you ...
/n/nAs I travel the country, ...
/n/nPlease accept my deepest gratitude for your contribution.
/n/nSincerely,
/n/nAbigail Falik
/n/nFounder and CEO
/nGlobal Citizen Year";
**$body = wordwrap($body,70);
mail("$email",'Thank you for your donation to Global Citizen Year (Important tax receipt)', $body,"From:donations#globalcitizenyear.org");**
}
else {
// Display Form ?>

Your code looks ok. It's best to send the mail first and check whether the function was successful. Then you can echo out "You will receive an email confirmation..." if successful, and some other message if the mail() call failed. With the mail() function, though, problems are usually later in the mail process. Getting a 'true' return from that function doesn't mean that Everything has worked in the email world.
With other functions, like DB writes, you will get a solid success or failure returned from the function and should act on it appropriately. That means you want to run the function before printing out a message saying everything went fine.

Related

PHP email is sending twice when form is submitted

I set up a custom price quote feature that sends the user an email when they click submit. The issue I'm having is that even if you hit 'Submit' once, it always sends two emails. I'm using this on a a WordPress site and this code is part of the price quote plugin that I wrote.
I set up a variable called $testemail that is set to 1, and is supposed to increment by 1 when the wp_mail function is called, but both emails are still showing just the number 1 so the second email doesn't increment it at all.
Here's my code that is sending the email:
$email_array = array($get_option_array['franchise_email'],
$email_address_sanitize, "info#example.com");
$subject = "Price Quote Submission";
$to = $email_array;
if (isset($_POST['submit-clicked'])) {
if ($check_human_clean != 2) {
echo '<div>';
echo '<p class="error">Human verfication is incorrect. Please try again.</p>';
echo '</div>';
}
else {
if (wp_mail($to, $subject, $message)) {
echo '<div id="dialog" title="Price Quote Submitted">';
echo 'div id="popmake-233">';
echo '<p>Your price quote has been sent successfuly. We\'ll be in touch shortly. If you don\'t hear from us, please give us a call directly at (909) 982-9999. Thank you!</p>';
echo '</div>';
$testemail++;
}
else {
echo '<p class="error">An error occured while processing your price quote. Please contact the franchise owner at ';
echo $get_option_array['franchise_phone'];
echo '</p>';
}
}
}
Everything I've read is that the code must be run twice, but my $testemail variable isn't incrementing so I'm not sure that's the case. Also, I'm using SendGrid but I already tried turning off SendGrid and that didn't solve the issue. Other than that, it's just using the wp_mail default function, which I believe uses PHP Mailer.
I'm a junior developer so I'm sure I'm just overlooking something, but I'm stumped at this point. Any help would be great, thanks.
If $testemail is not being incremented, it's possible that something in WP is running this function twice, separately, and therefore $testemail as a local variable will not increment on the second run.
Here are a few possible workarounds:
1) You could consider making $testemail a global variable.
2) When the email is successfully sent, store that fact in a database. Prior to sending the email, check the database see if the email has been sent. If so, do not send the email again.
3) Look deeper into why WP is calling this function twice.

check_email_exists.php solution?

I am trying to check email which is actually existed or not via php script and I found a solution that can really solve it.
I came across from this article https://gist.github.com/sureshdsk/9c599d757e90b0215e55 .
Please check complete code there, and let me show only my problem pane.
//(Lower-most lines of the project)
$email="asadbksdhskhdksjfhk#gmail.com"; //email to test
$check =verifyEmail($email, 'youremail#gmail.com'); //your email is just used for smtp requests
if($check=="valid"){
echo "success";
}else{
echo "fail";
}
Everything is OK by changing target email and host email, it shows "success".
But I want this php script to be processed by sending data and don't want it to be static.
So I changed ..
$email="asadbksdhskhdksjfhk#gmail.com"; //email to test
to
$email=$_REQUEST['email'];
and try sending email as data like this .
http://www.samplesample.com/check_email_exists.php?email="test#gmail.com"
But not working as the other scripts in my hosting do. By echoing email, it shows blank(null).
Please kindly suggest for my problem. Thank you for reading and thinking about it.I am new to web programming,php .
Use FILTER_VALIDATE_EMAIL to validate email in php.
Try this code,
//http://www.samplesample.com/check_email_exists.php?email=test#gmail.com
$email=$_REQUEST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
There's a plug-in class recommended via another answer which checks if the Email Address is valid using SMTP, that should free up all the complicated parts of developing the logic to test it.

Validate an array of values, output an error and stop script if one value fails?

I have an array of emails. I would like to do some validation on each one to see if it is more or less the proper format. This script is validating emails for the administration side of a website. This particular piece of the administration side is for sending newsletters to particular groups, each containing an array of emails.
I am adding the functionality to add a group with administrator specified recipients. This would become useful if the administrator was getting rid of a particular group of newsletter recipients and wanted to add them to another group before destroying the original group.
I have come up with a way to throw an error if any of the items in the array do not match the validation, however, it seems like there should be a better way to do this in PHP. I have not been able to find an alternative method.
$email_array_data["count"] = count($email_array);
foreach($email_array as $email) {
if (email_validation_function($email) {
$email_array_data["passed_validation"]++;
} else {
$email_array_data["failed_validation"][] = $email;
}
}
if ($email_array_data["count"] == $email_array_data["passed_validation"]) {
Send The Emails
} else {
Echo The Emails That Failed Validation
}
This script works pretty well, but it seems like there would be a better way to do this that checking that every email met the requirements, then comparing the number of emails that passed/failed validation and the count of the emails array.
Is there a better method?
First, you should check out filter_var(). It's a great function for validating tons of data, especially emails (see here).
There are many ways to handle errors. Based on what I can see from your script, you are only considering the array valid if all emails are valid. You could throw an exception.
$is_valid = filter_var($email, FILTER_VALIDATE_EMAIL);
if( ! $email )
throw new Exception('Invalid email address supplied');
If you go this approach, you could catch the exception using a try {} catch {} Just another approach I guess.

Stop user using email verification link more than once. PDO prepared statement not functioning

EDIT: based on first reply I got below,I reworked my code and it now works... first checking the given email address to find the gamer id. Then checking the verfication state based on the gamer id. So if they change their email address in the future it will still know whether it's already been verified.
Below is my final code, (I've changed some name for items, so its not an exact copy/paste of my own code).
function email_not_verified ($email) { //check it's not already verified
include ('../connect.php'); // Include connect to database functions
$findUser= $db->prepare("SELECT game_id FROM players WHERE email=?");
$findUser->execute(array($email));
$user = $findUser->fetch();
if ( $findUser){
$veri= $db->prepare("SELECT sent_verification FROM players WHERE game_id=?");
$veri->execute(array($user["game_id"]));
$results = $veri->fetch();
$final = $results["sent_verification"];
}
if ($final == 1){
return TRUE;
}
else{
return FALSE;
}
}
Thanks again for the help.
Below, is my original question.
I'm trying to figure out a simple setup that stops a user repeatedly verifying their email address. As when they verify their email I'm awarding them a bonus of 300 credits for in store game purchases. I obviously don't want to keep dishing that out each time they follow their emailed verification link.
So I'm trying to run a check first, before the normal verification script is run.
But surprise, surprise: its not working...
I was trying to search my database for the email address with the verification field set to '1', I'd then see how many times it found this result. If it found it '0' times then that's fine to verify, if it found it once then its already been verified before.
function email_not_verified ($email) {
include ('../connect.php'); // connect to database
//check it's not already verified
$checkEmail= $db->prepare("SELECT * FROM players WHERE sent_verification=?, email=?");
$checkEmail->execute(array('1', $email));
$check2 = $checkEmail->rowCount();
if ($check2 = 1){
return TRUE;
}
else{
return FALSE;
}
}
I've been using
file_put_contents('results.txt',$check2);
to see the results of the code regardless of whether its putting out a TRUE or FALSE. But the result comes back as '0', even though I can see from looking at my database it should be '1'.
I'm not sure if there's a whole easier way to approach this, I keep trying to get my head around bind values but it's not yet sinking in... I'll continue to try.
Thanks for any help, guidance, pointing out the obvious... I feel like I've taken the wrong path with my script but can't think how else to approach it...
Cheers
Jon
Your if statement is wrong. You're using the assignment operator instead of comparison. This doesn't matter though because rowCount isn't always reliable, which is probably where the actual problem is. What you need to do is fetch the first row and see if you get a row back.
However, you probably don't want to attach this to e-mail verification. When users change their e-mail address, you will want to verify that new address and you probably don't want to give them 300 more credits each time they do. Otherwise, someone could programmatically change their e-mail address over and over again, creating a lot of credits for themselves.
I would separate out the 300 free credits as a coupon or something that can only be used once per account. On e-mail verification, if that coupon hasn't already been used up for that account, use it and mark it as such in your database. This could be done simply by adding another column for new_account_bonus_credits or something.

How to validate phone numbers and stop injection headers - PHP Secure form

What else is needed to:
make this php script send an auto-response back?
sanitize and check the phone number and email that is not junk as my current formmail from dbmasters I get junk like dasawewdjz89)$%&*_sasa779%7fmsdls in almost every field including the input areas.
It is mentioned to take out the bcc and cc code, yet, I had code to sent to a different recipient based on the state, so is there a way to keep the bcc and cc fields too without compromising security?
Maybe this is 3 questions in 1, but this is essentially building upon the answer here
Replacing deprecated eregi() with stristr(). Is this php mail script secure from header injections? since it is a deprecated form and I get error logs each day now.
I believe I only need validation on input fields NOT select or radio fields, right?
I am an html/css guy so would this actual code go into the php page or as a separate contact.php page.
EDIT: The script I cannot post for some reason here with the code given (like in other forums). so I made a link to it in BOLD
..Validate without Javascript
To answer your questions:
Question 1: Don't quite understand what you mean here. Once you are in your script you can send output to the screen, generate and email, etc. This question is very vague.
Question 2: You can use regular expressions to validate various pieces of information. For example this will check a phone number in the format of XXX-XXX-XXXX and tell you if it is valid.
function validatePhone($number)
{
$test = "/^\d{3}-\d{3}-\d{4}$/";
return (preg_match($test, $number) != 0) ? true : false;
}
var_dump(validatePhone("815-555-1234"));
var_dump(validatePhone("8158791359"));
var_dump(validatePhone("blah blah 209#&$#)(##1;llkajsdf"));
This will produce:
bool(true)
bool(false)
bool(false)
Keep in mind this function is far from robust. Valid phone numbers in different formats will fail (e.g. 815 555-8846), so you will need to adjust the regexp or craft multiple regexps to meet your needs. But that should be enough to illustrate the process.
Question 3: For email, I don't really see how the BCC and CC fields are going to compromise security. What you need to focus on in that area is preventing email header injections.
Spammers have recently been using mail header injection to send spam e-mail from contact forms that have in the past viewed as secure.
If you are a webmaster you can edit your forums to ensure they are secure and safe from spammers
Anyway, I have several websites that all use a common contact form. Every contact form posts to the same script.
This is how I defend against header injections. (I typically use this script as an include file)
This script requires your html form to use action="post". Make sure this is only used on the script that the html form will be posted to. If you use this script on a regular page request, it will die().
More error checking should be done when testing posted values for bad strings. Possibly a regular expression.
<?php
// 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");
exit;
}
// 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");
exit;
}
// Host names from where the form is authorized
// to be posted from:
$authHosts = array("domain.com", "domain2.com", "domain3.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)){
logBadRequest();
header("HTTP/1.0 403 Forbidden");
exit;
}
// Attempt to defend against header injections:
$badStrings = array("Content-Type:",
"MIME-Version:",
"Content-Transfer-Encoding:",
"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($v, $v2) !== false){
logBadRequest();
header("HTTP/1.0 403 Forbidden");
exit;
}
}
}
// Made it past spammer test, free up some memory
// and continue rest of script:
unset($k, $v, $v2, $badStrings, $authHosts, $fromArray, $wwwUsed);
?>

Categories