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
Related
Let me start by saying I have looked into the documentation and unfortunately did not manage to fix my problem. Mainly what I am trying to do is, after the user registers, an email is sent to him and a vkey is sent to my database. After the user clicks on the verification link there the "verified" on my database is supposed to change to 1.
However I am not being able to do so. I am using cpanels emails and I have sent an email through the webmail, so I know they are working. But my script for some reason isn't, I tried following the documentation though...
Here is the function.php:
function createUser($conn, $name, $email, $username, $pwd, $vkey){
$sql = "INSERT INTO users (usersName, usersEmail, usersUid, usersPwd, vkey) VALUES (?, ?, ?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql) ) {
header("location: index.html?error=stmtfailed");
exit();
}
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sssss", $name, $email, $username, $hashedPwd, $vkey);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
header("location: ../mainpage/index.html");
exit();
$to = $email;
$subject = "Verificação da conta";
$message = "
Thanks for signing up!
Your account has been created, you can login with the following credentials after you have activated your account by pressing the url below.
------------------------
Username: '.$name.'
Password: '.$pwd.'
------------------------
Please click this link to activate your account:
https://universitymmt.com/includes/verify.php?vkey=$vkey'.$email.'&hash='.$pwd.'";
$headers = "De: suporte#universitymmt.com \r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" ."\r\n";
mail($to, $subject, $message, $headers);
header("location: index.html?accountverified");
}
This page is has the php that calls for the functions.php:
<?php
if(isset($_POST["submit"])){
$name = $_POST['name'];
$email = $_POST['email'];
$username = $_POST['uid'];
$pwd = $_POST['pwd'];
$pwdRepeat = $_POST['pwdrepeat'];
$vkey = md5(time() .$uid);
require_once 'db_connection.php';
require_once 'functions.php';
if (emptyInputSignup($name, $email, $username, $pwd, $pwdRepeat) !== false) {
header("location: ../index.html?error=emptyInput");
exit();
}
if (invalidUid($username) !== false) {
header("location: ../index.html?error=invalidUid");
exit();
}
if (invalidEmail($email) !== false) {
header("location: ../index.html?error=invalidEmail");
exit();
}
if (pwdMatch($pwd, $pwdRepeat) !== false) {
header("location: ../index.html?error=passwordsdontmatch");
exit();
}
if (uidExists($conn, $username, $email) !== false) {
header("location: ../index.html?error=usernameTaken");
exit();
}
createUser($conn, $name, $email, $username, $pwd, $vkey);
$to = $email;
$subject = "Verificação da conta";
$message = "<a href='https://universitymmt.com/includes/verfiy.php?vkey=$vkey'> Confirmar a minha conta</a>";
$headers = "De: suporte#universitymmt.com \r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" ."\r\n";
mail($to, $subject, $message, $headers);
}
I may add, I added the mail function on both files, hoping one of them would work, which it didn't lol.
Thank you for any help guys.
Hi I am sending confirmation e-mail after signup.How can the link be expired after a few seconds can anyone suggest me.Because if i click on the link after few days also it is getting activated.That should not be happen.Here is my code:
<?php
session_start();
$sessionCaptcha = $_SESSION['vercode'];
$inputStream = file_get_contents("php://input");
$data = json_decode($inputStream);
$connection = mysql_connect("localhost", "enjoytax_account", "account") or die(mysql_error());
$db = mysql_select_db("enjoytax_accounting", $connection);
if($db)
{
$confirm_code=md5(uniqid(rand()));
$username = $data->username;
$email = $data->email;
$password = md5($data->password);
$confirmpassword = md5($data->confirmpassword);
$mobileno = $data->mobileno;
$captcha=$data->captcha;
$check=mysql_query("select email from register where email = '$email'");
$num_rows = mysql_num_rows($check);
if ($num_rows == 0)
{
if($captcha == $sessionCaptcha)
{
$query = mysql_query("insert into register(username,email, password, repassword,mobile,confirm_code) values ('$username','$email', '$password' , '$confirmpassword', '$mobileno','$confirm_code')");
if ($query)
{
$from .= 'info#mail.com' . "\r\n\r\n";
$to = $data->email;
$subject="Your confirmation link here";
$message.="Click on this link to activate your account \r\n";
$message.="http://www.example.com/model/confirmation.php?email=$email&passkey=$confirm_code";
$success = mail($to, $subject, $message);
$successJson='{"success":"We have sent a verification email ' .
'to your email id '.$email.', please check your ' .
'Inbox and verify your email in order to proceed further."}';
print_r($successJson);
}else{
$failureJson='{"error":"We are encountering some issue. Please try after some time."}';
print_r($failureJson);
}
}else{
$failureJson='{"error":"Please Enter Correct Captcha."}';
print_r($failureJson);
}
}else{
$failureJson='{"error":"Email-Id already Exists."}';
print_r($failureJson);
}
}
?>
I have not tested the code but this might help you.
session_start();
if ($query)
{
$from .= 'info#mail.com' . "\r\n\r\n";
$to = $data->email;
$subject="Your confirmation link here";
$message.="Click on this link to activate your account \r\n";
$message.="http://www.example.com/model/confirmation.php?email=$email&passkey=$confirm_code";
$success = mail($to, $subject, $message);
$successJson='{"success":"We have sent a verification email ' .
'to your email id '.$email.', please check your ' .
'Inbox and verify your email in order to proceed further."}';
$_SESSION['now'] = date('i:s');
$now =date('Y-m-d H:i:s');
$futureDate = $now+(60*5);
$formatDate = date("Y-m-d H:i:s", $futureDate);
if($_SESSION['now'] > $formatDate)
{
$failureJson='{"error":"We are encountering some issue. Please try after some time."}';
print_r($failureJson);
}
}
else
{
echo " Query Not Executed";
}
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>"
;
}
}
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.
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.