I have a small web app where people can send a message via email to a group. Because of spam I will have to make an approval procedure.
The messages are being sent via PHP. How am I doing so I have to accept the message before its send to an email that forward it to the group?
My PHP:
<?php
$errors = '';
$myemail = 'whatever#gmail.com';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n FEJL: Alle felter skal udfyldes";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
$email_subject = "Form request";
$times = $_POST["timeslots"];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n FEJL: Ugyldig email adresse";
}
$strTimes = implode($times);
if( empty($errors))
{
$to = $myemail;
$email_subject = "$message \n ";
$email_body = "\n Code: $strTimes \n Navn: $name \n Email: $email_address \n";
$headers = "From: $email_address\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: thx.html');
}
?>
ok so this is a fair size project in itself if you want to use a data queue.
ASSUMING you want to use a database you will need to know the basics of setting one up, how to use and setup tables etc. (as long as you have access to a database anyway).
Here is some connection code:
change peter and abc123 to whatever username and password your database has associated with it.
$con = mysql_connect("localhost","peter","abc123");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db");
I will give you some sample code for inserting rows to the database, selecting rows from the database, acting on that info and deleting rows from the database.
Ok lets start with the mail submission:
This section near the bottom of your code is the data we need to manipulate
$to = $myemail;
$email_subject = "$message \n ";
$email_body = "\n Code: $strTimes \n Navn: $name \n Email: $email_address \n";
$headers = "From: $email_address\n";
$headers .= "Reply-To: $email_address";
So assuming you have a mysql database connection with a table setup in the database this is how you would insert it: (please note this is a basic insert query)
$query = "INSERT INTO queuemails (to, subject, body, headers) VALUES ('" . $to . "', '" . $email_subject . "', '" . $email_body . "', '" . $headers . "')";
mysql_query($query);
Ok so those 2 lines would be added BELOW your set variables.
You then need to provide a method of approval page.
This can be done on the same page but you have to seperate out your mail() function from the rest of the script.
Ok so here is a select script now to be able to VIEW your queue for approval. Please note that I have added an auto increment column to the table that stored your queued mail. This is to be able to select a line in the table more easily as is generates a unique number for that line of data. This column is called mid (standing for "mail identity").
ok so here is the selection script:
$query = "SELECT * FROM queuemail"; //this is only good if you know you wont get millions else you need to limit it
//limited select:
//$query = "SELECT * FROM queuemail LIMIT 0,10"; //selects the first 10
while($m = mysql_fetch_assoc(mysql_query($query))){
echo $m['to'] . " ";
echo $m['subject'] . " ";
echo '<a href=approve.php?mid=' . $m['mid'] . '>Approve</a><br>';
}
Then finally to clean up afterwards, after you have used your mail() function you should delete the line from the database that you have sent.
Here is the code (including the $_GET variable, this is an unsafe method but is sufficient to display the code you would be using).
mail(); //data can be added either from a new select statement or from POSTING it with the form
$query = "DELETE FROM mailqueue WHERE mid='" . $_GET['mid'] . "'";
mysql_query($query);
echo 'Your mail has been sent and deleted from the queue';
Hope this helps.
You can add timestamps to another column in the database automatically so that you can verify spam posting with something like:
if($_SERVER['REQUEST_TIME'] > ($oldtimeofpost + 100)){ //time is in seconds
//do something
}
else{
//warning
}
Related
I want to send a mail using php through Gmail. I've seen many websites how to do it but I don't Understand how to do them. I am still stuck at the code I've written at first. Please help me how to connect my website (hosted on GoDaddy) to gmail account, and tell correct path to do that.
I am writing a code for clearer vision. In this php code, I am trying to add data in database and if the code works, the user should get an email from the company
if (isset($_POST['name']) && isset($_POST['mobile']) && isset($_POST['email']) && isset($_POST['practice']) && isset($_POST['date']) && isset($_POST['time']))
{
include "_credentials.php";
$name = $_POST['name'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$practice = $_POST['practice'];
$date = $_POST['date'];
$time = $_POST['time'];
$sql = "INSERT INTO <database> (Name, Number, email, Practice, Time, Date) VALUES ('".$name."', ".$mobile.",'".$email."','".$practice."','".$date."','".$time."');";
if ($conn->query($sql) === TRUE) {
$to = $email;
$host = "ssl://smtp.gmail.com";
$subject = "Appointment Confirmation";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: abc#gmail.com' . "\r\n";
$txt = "Hello ".$name.",\n Your Appointment is booked with Doctor at Clinic on ".$date." at ".$time.".";
mail($to,$subject,$message,$headers);
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
First of all you need need to check for error response on mail() function using the following snippet
$success = mail('example#example.com', 'My Subject', $message);
if (!$success) {
$errorMessage = error_get_last()['message'];
}
After the error message , you will be able to sort it out
i am working on script to send a mail to a list of emails from my table using php
presently i run a query on the table and echo all the emails meeting such requirements from the sql query
sql="SELECT * FROM people WHERE status in('member','client')";
$result = mysql_query($sql)or die("Cannot query orders_products data" . mysql_error());
while($row=mysql_fetch_array($result)) {
$list = array();
$list[] = $row['Email'];
echo implode(",",$list);
$email = 'xxxxxxxxxxx';
$emailto = implode( "," ,$list );
$subject = "xxxxxxxxxxxxxxxx";
$headers = "From: $email";
$body .= ++$i.") ".$row['title'] ."\n\n";
}
$body .= "Regards\n\n";
$body .= "xxxxxxxxxxxxxxxxxx\n\n";
$send = mail($emailto, $subject, $body, $headers);
when i try passing these emails to a mail function snippet the mail sending fails.
Please what could i be doin wrong, i need help
Update :
$list[] = $row['Email'];
echo implode(",",$list);
all the emails are displayed
But without commas.
$emailto = implode( "," ,$list );
i use the same method of imploding the array of data gotten from
$list[] = $row['Email'];
By fail i just mean i was hoping since the emails got echoed using the implode it would all successfully pass the emails to $emailto and then send a mail to each of them.
So, what I think you're trying to do is to get the email address from your table where the user is either a member or a client. Then, you have a from address, subject, and a body. In addition, it looks like maybe you're trying to add to the body some unique information. Finally, I think you want to send an individual email to each user, separately.
You could modify your code to be like this:
<?php
$sql="SELECT * FROM people WHERE status in('member','client')";
$result = mysql_query($sql) or die("Cannot query orders_products data" . mysql_error());
$emailContent = 'xxxxxxxxxxx';
$emailSubject = 'xxxxxxxxxxx';
$body = 'xxxxxxxxxxxxxxx';
$headers = "From: from#email.com";
while ($row = mysql_fetch_array($result)) {
// optionally modify body here...?
$emailBody = $body .= $row['title']; // or whatever you're trying to do here...
// send email to each individual person
mail($row['Email'], $emailSubject, $emailBody, $headers);
}
I think this is how you'd modify your code to get it to do what you're asking.
After some more troubleshooting I believe I found the problem. We use QR Tags for our product and when a QR code is scanned it takes the user to the URL that runs this script. If I manually type in the URL or if I use our custom built QR scanner app then the user will receive one email. However if I user any other QR scanning app then it will send multiple emails. How can I make it so that this script will run only once each time the URL is loaded even if its from a third party app?
<?php
$queryString = $_SERVER['QUERY_STRING'];
$count=-6;
$id=substr($queryString,$count,6);
//db connection
$db = new mysqli('localhost', '*****', '*****', '*****');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "SELECT * FROM `****` where id = '$id'";
$result = $db->query($query);
$row = $result->fetch_assoc();
$email = $row['email'];
$ownername = $row['ownername'];
$petname = $row['petname'];
//check to see if tag has been registered
if ($email != "") {
//send email
$datetime = date("D M j G:i:s T Y");
$subject = "Alert";
$mailheader.= "From: " . "Tag Team <support#tag.com>\n";
$mailheader.= "X-Sender: " . "support#tag.com\n";
$mailheader.= "Return-Path: " . "support#tag.com\n";
$mailheader .= "Bcc: support#tag.com";
$body .= "Dear " . $ownername . ", \n\n";
$body .= "" . $petname . "'s Tag has just been scanned.\n\n";
$body .= "Click here to Login :\n";
$body .= "http://www.tag.com\n";
$body .= "********************\n\n";
$body .= "Regards,";
$body .= " \n\n";
$body .= "Tag Team";
$body .= " \n\n";
$body .= "Keeping Pets Safe and Found";
mail($email, $subject, $body, $mailheader ) or die ("Mail could not be sent.");
//end email alert
}
header("Location: http://www.smartphonepettag.com/id/profile.php?id=$id");
mysql_close($db);
?>
In the code snippet I cannot see any reason why your script should be executed more than once but relating to your post yesterday it seems as if something on your mail server is going terribly wrong.
But anyway if it's not an mail server fault the solution would be something like this:
// add this at the very first line
session_start();
// add this in the code
if($_SESSION['send'] != true){
mail($email, $subject, $body, $mailheader ) or die ("Mail could not be sent.");
$_SESSION['send'] = true;
}
This will make sure that the "mail()" function will never be executed twice for the same user.
You can learn more about Session Variables at the PHP manual.
You could create a flag in your database indicating if the email has been sent. Check the flag before sending the email, set it after you send the email.
I am working on a membership signup/join form. The form data is submitted to another page called join.php on pressing submit button I am getting Internal Server Error message. Can anybody help me find the reason/mistake in my coding? Though the data is successfully entered into database.
<?php
// file name : join.php
$con = mysqli_connect("$DBHOST", "$DBUSER", "$DBPASS","$DBNAME");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$city = $_POST['city'];
$state = $_POST['state'];
$ip = $_SERVER['REMOTE_ADDR'];
$name = mysqli_real_escape_string($con,$name);
$email = mysqli_real_escape_string($con,$email);
$phone = mysqli_real_escape_string($con,$phone);
$city = mysqli_real_escape_string($con,$city);
$state = mysqli_real_escape_string($con,$state);
$check = "SELECT COUNT(*) FROM `members` WHERE phone=".$phone."
OR email=".$email." Limit 1";
if (mysqli_query($con,$check)>=1){
echo ("The phone number <strong>".$phone."</strong> or email <strong>
".$email." </strong> address is already registered with us.");
}else{
$query = mysqli_query($con,"INSERT INTO `members`
(`name`,`email`, `phone`, `city`, `state`,`ip`, `regdate`)
VALUES('".$name."','".$email."','".$phone."','".$city."',
'".$state."','".$ip."', NOW('') )")
or die("MYSQL ERROR :".mysqli_error($con));
/* PREPARE MESSAGE FOR EMAIL TO NEW MEMBER */
header("Refresh=07;URL=./index.php");
$headers4 = "<join#mydomain.com>";
$headers = "Reply-to: $headers4\n";
$headers .= "From: $headers4\n";
$headers .= "Errors-to: $headers4\n";
$headers .= "Content-Type: text/html; charset=utf-8\n";
$message = "<br>Dear ".$name." <br><br>";
$message .= "Thanks for joining.<br> Your details are";
$message .= "<br>Name - ".$name." <br>Mobile No. - ".$phone."<br>";
$message .= "Email - ".$email."<br>City, State - ".$city.",".$state."<br>";
$message .= "<br>Regards,<br>Name";
mail("".$email."", "Thanks for Joining", "".$message."", "".$headers."");
echo "<p>Congratulations!<br>IP-".$ip."<br>Your data has been added
into our membership database.<br><strong>Thank you for joining.</strong>";
}
mysqli_close($con);
?>
So many mistakes in it.. Improve your code style to give its quality a boost.
Start by fixing the quotes, very missleading:
mail("".$email."", "Thanks for Joining", "".$message."", "".$headers."");
Should be
mail($email, 'Thanks for Joining', $message, $headers);
$check = "SELECT COUNT(*) FROM `members` WHERE phone=".$phone."
OR email=".$email." Limit 1";
Has missing quotes too, I don't thinkg email and phone are numbers.
$check = "SELECT COUNT(*) FROM `members` WHERE phone='".$phone."'
OR email='".$email."' Limit 1";
There is no header called Refresh, this is kinda Javascript style, but you need HTTP:
header("Refresh=07;URL=./index.php");
Fixed:
header("Location: index.php");
Finally enable error reporting to see what's really wrong.
Currently I have 2 forms. On first user have to send code and receive it, and submit to second form and approve account. I need, when they put email and click submit, on email automatically is added code which they should get on their email, but they dont have to copy/paste code, because it should do automatically. Search for mysql_query("UPDATE users SET verify = 'verified', bullets = bullets + 5000 WHERE ID = '$ida'");
$showoutcome++; $outcome = "Your account is now verified!"; } - Here I need to add, $verifnum, because that's the code which they should get on their email, but as I said script should approve it automatically, and I will use only one form where they enter just email and click verify.
<?php
$saturate = "/[^a-z0-9]/i";
$saturated = "/[^0-9]/i";
$sessionidraw = $_COOKIE['PHPSESSID'];
$sessionid = preg_replace($saturate,"",$sessionidraw);
$userip = $_SERVER[REMOTE_ADDR];
$gangsterusername = $usernameone;
$playerrank = $myrank;
$playerarray =$statustesttwo;
$playerrank = $playerarray['rankid'];
$email = $playerarray['email'];
$verified = $playerarray['verify'];
$ref = $playerarray['ref'];
if($verified == 'verified'){die('<font color=silver face=verdana size=1>Your account is already verified!'); }
if($_POST['verify'] AND $_POST['email']){
$newemail = $_POST['email'];
if(!preg_match("/^[\ a-z0-9._-]+#[a-z0-9.-]+\.[a-z]{1,20}$/i", $_POST['email'])){ $showoutcome++; $outcome = "The email you entered is invalid!"; }else{
$verifnum = rand(1111,9999);
$to = "$newemail";
$subject = "SG - Email Verification";
$header = "From: State Gangsters - Email Verification <admins#stategangsters.com>\r\n" .
'Reply-To: State Gangsters <noreply#sgangsters.com>' . "\r\n" .
'X-Mailer: PHP/' . phpversion() . "\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: text/html; charset=utf-8\r\n" .
"Content-Transfer-Encoding: 8bit\r\n\r\n";
$body = "Your verification code is $verifnum!";
if (mail($to, $subject, $body, $header)){ $showoutcome++; $outcome = "An email has been sent, please check your inbox!";
mysql_query("UPDATE users SET verify = '$verifnum', email = '$newemail' WHERE ID = '$ida'");
}}}
if($_POST['code'] AND $_POST['verifyit']){
$newcode = $_POST['code'];
$getcodee = mysql_query("SELECT verify FROM users WHERE ID = '$ida'");
$doit = mysql_fetch_array($getcodee);
$getcode = $doit['verify'];
if($newcode == $getcode AND $getcode > 0){
mysql_query("UPDATE users SET verify = 'verified', bullets = bullets + 5000 WHERE ID = '$ida'");
$showoutcome++; $outcome = "Your account is now verified!"; }
else{ $showoutcome++; $outcome = "The verification code you entered is incorrect!";
}}
?>
if($_POST['code'] AND $_POST['verifyit']) {
Change that to use $_GET, and create a link in your e-mail that will post back to the page with the appropriate variables, e.g.
$body = "Your verification code is <a href='$PHP_SELF?code=$verifnum&verifyit=1'>$verifnum</a>!";
This aside, your code is really messy (three functionalities in one script), full of obsolete things (<font color=silver>?), weird constructions (using die for regular program flow?) and guaranteed loopholes (mysql_query with variables inserted directly in the SQL?!?!!!). It's not clear where your $ida comes from anyway, but I'm guessing (hoping) that's a consequence of copy/pasting code here for a minimal example.