Email verification and code approve - php

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.

Related

using aws to send mail with php

I want email to be send from my AWS server. Code works fine except sending email. Can anyone help to send email?
PHP codes :
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%&*_";
$password = substr(str_shuffle($chars), 0, 8);
$password1 = sha1($password);
$email = htmlspecialchars($_POST['email']);
$query = "UPDATE employee SET password ='$password1' WHERE email = '$email'";
$result = mysqli_query($link, $query);
$subject = 'Your New Password';
$status = "";
if ($result) {
$sender = 'no-reply#us.com.sg';
$recipient = $email;
$headers = "From : $sender";
$message = "Your password is :" . $password . ". </br>"
. "You can now login using this password</br>"
. "Click to login <a href = 'login.php'> here.</a>";
if (mail($recipient, $subject, $message, $headers)) {
$status .="The password has been sent to $email.</br>Click to login <a href = 'login.php'> here.</a></br>or send another new password<a href = 'forgetPassword.php'>here</a><br/>";
} else {
$status .="Email failed to sent to $email.Please try again<a href = 'forgetPassword.php'> here.</a>"
;
}
}
First of all, please install mail package in your aws server to send email.
If your server is ubuntu, type below line in command line
sudo apt-get install mailutils
Or If you are in CentOS, try this in command line
yum install mailx
Try below line in command line of mail is sended successfully
echo "Message Body" | mail -s "Message Subject" yourMailId#example.com
Also you need to add html header to send html message. If you dont add html headers, message will be sent as plain text. So please update your program as below.
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%&*_";
$password = substr(str_shuffle($chars), 0, 8);
$password1 = sha1($password);
$email = htmlspecialchars($_POST['email']);
$query = "UPDATE employee SET password ='$password1' WHERE email = '$email'";
$result = mysqli_query($link, $query);
$subject = 'Your New Password';
$status = "";
if ($result) {
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: no-reply#us.com.sg'. "\r\n";
$recipient = $email;
$message = "<html><body>Your password is :" . $password . ". </br>"
. "You can now login using this password</br>"
. "Click to login <a href = 'login.php'> here.</a></body></html>";
if (mail($recipient, $subject, $message, $headers)) {
$status .="The password has been sent to $email.</br>Click to login <a href = 'login.php'> here.</a></br>or send another new password<a href = 'forgetPassword.php'>here</a><br/>";
} else {
$status .="Email failed to sent to $email.Please try again<a href = 'forgetPassword.php'> here.</a>"
;
}
}

Password Reset Link : "TO" email address not working

I have created a password reset function in PHP.
It's working just fine...........except that, for some reason, I'm unable to set the recipient's email address : "TO"
The code works this way :
(a) the user is asked to provide his login/username
(b) php sends an sql query to the database;
(c) if the username is found, php takes the email-address, and sends a Reset Link via email
(d) this reset-link has a unique "token" attached to it
(e) the user clicks on the link in his email, and is re-directed to a new page where he resets his password
Everything is working fine...........except for the email structure itself. The email comprises : TO, CC, SUBJECT, BODY, and HEADERS.
Everything is being shown..........except the actual "TO".
In fact, the only reason I know that the code works is because I'm getting a copy of the email, via the the "CC"
Here is my code :
if(isset($_POST['submit'])) {
$login = $_POST['login'];
$query = "select * from personal_data where login='$login'";
$result = mysqli_query($conn,$query);
$count=mysqli_num_rows($result);
$rows=mysqli_fetch_array($result);
if($count==0) {
echo "Sorry; that username does not exist in our database";
}
else {
function getRandomString($length)
{
$validCharacters = "ABCDEFGHIJKLMNPQRSTUXYVWZ123456789!#+=%&/?*$";
$validCharNumber = strlen($validCharacters);
$result = "";
for ($i = 0; $i < $length; $i++) {
$index = mt_rand(0, $validCharNumber - 1);
$result .= $validCharacters[$index];
}
return $result; }
$token=getRandomString(40);
$q="insert into token (token,login) values ('".$token."','".$login."')";
mysqli_query($conn,$q);
function mailresetlink($to,$token){
$to = $rows['email'];
$subject = "Password Reset";
$uri = 'http://'.$_SERVER['HTTP_HOST'] ;
$message = '
<html>
<head>
<title>Password Reset Link</title>
</head>
<body>
<p>We received a Password-Reset request from your account.</p>
<p>Click on the following link to reset your password : Reset Password</p>
</body>
</html>
';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: Support<support#xxxxx.com>' . "\r\n";
$headers .= 'Bcc: Info<info#xxxxx.com>' . "\r\n";
if(mail($to, $subject, $message, $headers)) {
echo "A password reset link has been sent to your email address."
}
}
if(isset($_POST['login'])) {
mailresetlink($email,$token);
exit();
}
}
}
The reason why your code is not working is due to a few things.
One of which is that $rows needs to reside inside the function mailresetlink($to,$token) function's parameter.
Change that to function mailresetlink($to,$token,$rows) and do the same for the one inside if(isset($_POST['login'])){...}
if(isset($_POST['login'])) {
mailresetlink($email,$token,$rows);
exit();
}
Plus, if it isn't a typo or a bad paste; there is also a missing semi-colon in this line:
echo "A password reset link has been sent to your email address."
^ right there
Having done all of the above, successfully sent all of the information to Email during my test.
Sidenote: Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
You cannot define functions in if or while or whatever scope. Define them before or after you intend to use them. Try with the following code:
<?php
if ( isset($_POST['submit']) ) {
$login = $_POST['login'];
$email = $_POST['email'];
$query = "select * from personal_data where login='$login'";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
$rows = mysqli_fetch_array($result);
if ($count == 0) {
echo "Sorry; that username does not exist in our database";
} else {
if (isset($_POST['login'])) {
mailresetlink($email, $token, $rows);
exit();
}
}
}
function getRandomString($length)
{
$validCharacters = "ABCDEFGHIJKLMNPQRSTUXYVWZ123456789!#+=%&/?*$";
$validCharNumber = strlen($validCharacters);
$result = "";
for ($i = 0; $i < $length; $i++) {
$index = mt_rand(0, $validCharNumber - 1);
$result .= $validCharacters[$index];
}
return $result;
}
$token = getRandomString(40);
$q = "insert into token (token,login) values ('" . $token . "','" . $login . "')";
mysqli_query($conn, $q);
function mailresetlink($to, $token, $rows)
{
$to = $rows['email'];
$subject = "Password Reset";
$uri = 'http://' . $_SERVER['HTTP_HOST'];
$message = '
<html>
<head>
<title>Password Reset Link</title>
</head>
<body>
<p>We received a Password-Reset request from your account.</p>
<p>Click on the following link to reset your password : Reset Password</p>
</body>
</html>
';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: Support <support#xxxxx.com>' . "\r\n";
$headers .= 'Bcc: Info <info#xxxxx.com>' . "\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "A password reset link has been sent to your email address.";
}
}
?>
Also, pay attention to Quentin's advice about preventing SQL injection.
What I did was:
Moved getRandomString and mailresetlink after the if block
Added parameter $rows to mailresetlink function, so it can find use of the $rows variable (which was out of the scope)
You also need to define $email, because it's not being set anywhere, so I did it for you (I guess you also have an input field with the name of email somewhere.
Test it, it should work.

PHP Sending Duplicate Emails

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.

Php Email Form Requesting Information

I want to send an email to someone that clicks the link having the information on them from my database. So they put in their username , password, and email and get the 'Item' and 'Aisle' sent to them. The problem is they can have multiple items under their username. So I need to echo all the information in one email. But its not possible to echo information in an email. Currently it sends an email for each item and aisle information found so it can send 2+ emails of information. Any help would be loved. Thanks!
$Username = mysql_real_escape_string($_POST['Username']);
$Password = mysql_real_escape_string($_POST['Password']);
$Loc = mysql_real_escape_string($_POST['Loc']);
$To = mysql_real_escape_string($_POST['To']);
$Subject = "List";
$query = mysql_query("select * from Members where Username = '$Username' and Password = '$Password'");
while ($row = mysql_fetch_array($query)) {
$headers = 'From: email#email.com';
$Items = $row['Items'];
$Loc = $row['Loc'];
$msg= "Item: $Items
Aisle: $Loc\n";
mail($To, $Subject, $msg, 'From:' . $header);
echo 'Email sent to: ' . $To. '<br>';
Changing the 2nd part of your codes as below:
$query = mysql_query("select * from Members where Username = '$Username' and Password = '$Password'");
$items = '';
$headers = 'From: email#email.com';
while ($row = mysql_fetch_array($query)) {
$items .= $row['Items'] . PHP_EOL;
$loc = $row['Loc']; // what is Loc ?
}
$msg= "Item: $items
Aisle: $loc\n";
mail($To, $Subject, $msg, 'From:' . $header);
echo 'Email sent to: ' . $To. '<br>';
However, your table structure is weird. You should put your items in a separate table with your member ID as foreign key.
Try placing the message in a separate file and include it in the message.
like this.
$message = include('email_massage.php');

php email approval

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
}

Categories