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.
Related
I have put together a forgot password page that should insert a token to my lost password db table and send the user a email with a link to reset the password but I am not getting the email and just get there was a error message on the forgot password page after clicking the submit button and bit unsure what the issue is. My code is below
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$db = new mysqli("localhost", "username", "password", "databasename");
if(isset($_POST['submit'])){
$email = $_POST['email'];
$stmt = $db->prepare("SELECT * FROM `users` where `customer_email` = ?");
$stmt->bind_param('s', $email);
$stmt->execute();
$res = $stmt->get_result();
if($res->num_rows < 1){
echo "No such email has been found";
} else{
$fetch = $res->fetch_assoc();
$userid = $fetch['user_id'];
$token = bin2hex(openssl_random_pseudo_bytes(45));
$from = "noreply#domain.co.uk";
$url = 'https://www.domain.co.uk/account/passwordreset.php?token='.$token;
if(mail($email, $url, $from)){
//if(mail($to,$subject,$message,$url,$headers)){
$stmt = $db->prepare("INSERT INTO `lost_password`(user_id, token) values(?,?)");
$stmt->bind_param('is', $userid, $token);
$stmt->execute();
$to = $email;
$subject = "New Password Instructions";
$message = " Please visit $url to reset your password";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// More headers
$headers .= 'From: <noreply#domain.co.uk>' . "\r\n";
$mail=mail($to,$subject,$message,$headers);
if($stmt->affected_rows == 1){
echo "We have emailed you instructions on how to reset your password";
} else {
echo "there was an error";
}
}
}
}
?>
If you are working on local server then the error will occure. Have you cheched it on live server? If not please check it on live server.
OR
Instead of using mail() function use PHPMailer
I have a website and have enabled to send mail using the By default mail function of php
My code is this
I have tested it from other posts also.. and for me it is correct.. but it is still not sending the message. Please tell me.. where is the problem
<?php
include_once './config.php';
$con=mysqli_connect(mysql_host,mysql_user,mysql_password,mysql_database);
$Roll = $_REQUEST['UserName'];
ini_set('display_errors',1);
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
$confirmCode = md5(uniqid(rand()));
$tbl_name1 = "temp_forgot_acc";
$orderCheck = "DELETE FROM $tbl_name1 WHERE EmailId = '$Roll'";
mysqli_query($con,$orderCheck);
$order = "INSERT INTO $tbl_name1 (EmailId,confirm_code) VALUES ('$Roll','$confirmCode')";
$result = mysqli_query($con,$order);
//if($result)
// {
// ---------------- SEND MAIL FORM ----------------
// send e-mail to ...
$to=$Roll;
// Your subject
$subject="Your Forgot Pass link here";
// From
$header = 'From: Admin <admin#test.com>' . "\r\n";
// Your message
$message="Your Comfirmation link \r\n";
$message.="http://www.test.com/test.html?passkey=$confirmCode&Email=$Roll";
// send email
mail($to,$subject,$message,$header);
// }
echo '{"data":[';
echo "{" . '"Finish":'.'"YES"}';
echo ']}';
}
mysqli_close($con);
exit();
?>
I am able to insert it in the database... but it is not sending the maill.
Try code something like this in your application:
$from = "sender id" // sender must be valid
$subject = "subject";
$message = 'mail from'.$from.'sender';
$to = "receiver id";
// send mail
$headers = 'From: <test#test.com>' . "\n";
$headers .= "MIME-Version: 1.0\n" ;
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
mail($to,$subject,$message,$headers);
and check what you have in $to value..email id must be correct.
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.
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');
please i am trying to make the message show on newline as the customer types it, but i am getting /r/n between each line and also trying to make the $body .= $_SESSION['username']; appear on a separate line i have tried to use this example to solve but has not been successful the code is below
<?php require_once("include/session.php");?>
<?php require_once("include/dataconnect.php");?>
<?php require_once("include/functions.php");?>
<?php include("include/mheader.php");?>
<?php
$submit = $_POST['Notify'];
$message = mysql_real_escape_string(htmlentities(strip_tags($_POST['message'])));
//echo "$message";
//die();
if('POST' === $_SERVER['REQUEST_METHOD'])
{
if (isset($message))
{
//Get Email Address
$emails = mysql_query("SELECT email FROM reusers WHERE username = '{$_SESSION['username']}'")or die(mysql_error());
//$emails = mysql_query("SELECT reusers.email FROM reusers INNER JOIN repplac ON reusers.username = repplac.Uname AND reusers.username = '".$_SESSION['username']."'")or die(mysql_error());
$results = (mysql_fetch_assoc($emails)) or die(mysql_error());
$email= $results['email'];
//echo "$email";
//die();
if(mysql_num_rows($emails) == 0){
exit("No email addresses found for user '{$_SESSION['username']}'");
}
$email = mysql_result($emails, 0);
//echo "$email";
//die();
$body = $_SESSION['username']. "<br>"
. nl2br($_POST['message']);
$to = $email;
$subject = "copy of your notification";
$headers = "From: noti#r.co.uk\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'Bcc:noti#r.co.uk' . "\r\n";
mail($to,$subject,$body,$headers);
}
}
?>
<p>
<form action='notification.php' method='Post' class='rl'>
<div>
<label for='message' class='fixedwidth'>Message</label>
<textarea name="message" rows ="7" cols="40" id="message"></textarea>
</div>
<div class='buttonarea'>
<p>
<input type='submit' name='notify' value='Notify'>
</p>
</div>
</form>
</p>
<?php include("include/footer.php");?>
Since it's generally safer to send HTML emails in a more archaic form of HTML I'm going to allow the HTML email content to be HTML 4; so it doesn't need to be XML well formed and nl2br() is acceptable.
You're specifying that the content of your email is HTML so normal line endings, \r, \n and \r\n are pretty much irrelevant.
Try something like:
$body = $_SESSION['username']. "<br>"
. nl2br($_POST['message']);
There's no sanity checks or validation in there but I think that's what you're trying to get it to do.
---- EXAMPLE CODE ----
I've just refactored your code somewhat so I could better see what you're doing (it's just a matter of personal preference) and put comments in to show what I'm getting at with regards to sanity checks and validation.
I've not tested any of this, it's pretty much just an example using your code.
<?php
require_once "include/session.php";
require_once "include/dataconnect.php";
require_once "include/functions.php";
require_once "include/mheader.php";
//sanity checks - ensure the form has been posted and that there IS a message
if($_POST && !empty($_POST['message'])) {
//sanity check - ensure there IS a username
$sUsername = !empty($_SESSION['username']) ? $_SESSION['username'] : "";
if($sUsername) {
//check the username against the database?
$resultEmail = mysql_query("SELECT `email` FROM `reusers` WHERE `username` = '{$sUsername}' LIMIT 0, 1")
or die(mysql_error());
//no result - could throw an Exception here
if(mysql_num_rows($resultEmail) == 0) {
die("No email addresses found for user '{$sUsername}'");
}
//email verified against the database
else {
$sEmail = mysql_result($resultEmail, 0);
//create the email
$headers = "From: noti#r.co.uk\r\n"
. 'MIME-Version: 1.0' . "\r\n"
. 'Content-type: text/html; charset=iso-8859-1' . "\r\n"
. 'Bcc:noti#r.co.uk' . "\r\n";
$to = $sEmail; //assuming the email address retrieved from the database has already been mxrr checked etc...
$subject = "copy of your notification";
$body = $sUsername . "<br>"
//remove slashes as this is going in an email, strip tags and convert newlines to "<br>"
// since you're using iso-8859-1 there shouldn't be any oddities unless someone completes
// the form using an Arabic character set (for instance)
. nl2br(strip_tags(stripslashes($_POST['message'])));
//send the email
if(!mail($to, $subject, $body, $headers)) {
die("sendmail error!");
}
}
}
}
?>
try this;
$body = "Username" . "<br>";
$body .= "test1 message for test 1 message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1
test2 message for test 2
test3 message for test 3";
$body = nl2br($body);
and here what i got