Reputation: 1914
I am a PHP beginner and I just started to create my own website. I am running into a problem that mail() is returning FALSE with no reason.
My idea was to implement a password reset mechanism. When a user enter his email, the HTML form will pass the information to the php script, and the php script will perform verifications and reset the password by a randomly generated password followed up by sending this temperary password to the user email. Below is my code:
<?php
session_start();
$email = $_POST['email'];
function random_string_generator ($character_options, $length_of_generated_string)
{
$random_string = "";
//count the number of characters available for picking
$num_valid_charactor = strlen($character_options);
for ( $i = 0 ; $i < $length_of_generated_string; $i++ ){
$random_pick = mt_rand(1, $num_valid_charactor);
$random_char = $character_options[$random_pick-1];
$random_string .= $random_char;
}
return $random_string;
}
function createSalt()
{
$string = md5(uniqid(rand(), true));
return substr($string, 0, 3);
}
$dbhost = 'localhost';
$dbname = 'my_db';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname, $conn);
$query = "SELECT password, salt FROM users WHERE email = '$email';";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1)
{ //no such user exists
$_SESSION['error'] = '1';
$_SESSION['message'] = 'user does not exist';
header("Location: Forgot_password.php");
}
else
{
$random_pick_options = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$temporary_password = random_string_generator($random_pick_options, 12);
$hash = hash('sha256', $temporary_password);
$salt = createSalt();
$hash = hash('sha256', $salt . $hash);
$query = "UPDATE users set password=$hash, salt=$salt where email=$email;";
mysql_query($query);
//Email user the temporary password
$email_from = "[email protected]";
$email_to = $email;
$message = "Dear user,\n\n your temporary passowrd is: " . $temporary_password . "\n This is an auto-generated email. Please do not reply to this email address.\n\n ALEMC\n";
mail($email_to, "ALEMC: Password Reset", $message, "From: $email_from");
$_SESSION['message'] = "password reset";
header("Location: Login_form.php");
}
?>
Any idea what is wrong? Or is there any better way to do mail sending then using php?
Upvotes: 1
Views: 323
Reputation: 416
I would personally recommend you use something like swiftmailer (http://swiftmailer.org/), it just works. Look at how your PHP Mail/Server configuration is setup. and do something to protect yourself from SQL injection.
Upvotes: 0
Reputation: 7556
There must be something wrong with your php setup. I personally like to use PHPMailer when sending email from php you have a lot more options.
Upvotes: 2