php variable will not display in email - php

The assignment I'm working on (an E-commerce course) asks that I use php to generate a new password for a user and send the user an email with the new password. I successfully generate the password, send the email from my school's server to myself (a gmail account), using php mail() however the php variable representing the password is always blank. I have been looking for answers to this on here and other websites but cannot find what I'm doing wrong.
I am looking to solve this particular issue and am not looking to use PHPMailer or some other alternative. Also I am not looking to discuss more secure ways to send email, or discuss encryption, just looking to discuss this particular issue and why it is or isn't working. Thank you in advance for any advice.
if ($mysqli->conect_errno) {
die("Error: Could not connect to database." . $mysqli->connect_error);
} else {
echo "<p>Connected<br></p>";
}
$email = $_POST['email_input'];
try {
$password = reset_password($email, $mysqli);
notify_password($email, $password, $mysqli);
echo 'Your password has changed and has been emailed to you.<br>';
}
catch(Exception $e) {
echo 'Your password could not be reset';
}
function reset_password($email, $mysqli){
$new_password = randomString(8, 12);
if ($new_password == false) {
throw new Exception('could not generate new password');
}
$rand_number = rand(0, 999);
$new_password .= $rand_number;
echo "NEW PASSWORD: " .$new_password."\r\n";
$query = "UPDATE registration
SET password = sha1('".$new_password."')
WHERE email = '".$email."'";
$result = $mysqli->query($query);
if($result) {
echo "<br>Password Reset<br>";
}else {
echo "An error has occured";
}
}
function randomString($min_length, $max_length){
return substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), $min_length, $max_length);
}
function notify_password($email, $password, $mysqli){
$query = "SELECT email FROM registration WHERE email='".$email."'";
$result = $mysqli->query($query);
if(!$result){
throw new Exception('could not find email address');
}else if ($result->num_rows == 0) {
throw new Exception('Could not find email address:user not in database');
}else {
$row = $result->fetch_object();
$email = $row->email;
$from = "From support#HelpFinder \r\n";
$mesg = "Your password has been changed to ".$password."\r\n"."Please change it the next time you log in.\r\n";
if(mail($email, 'HelpFinder Login Information', $mesg, $from)) {
return true;
}else {
throw new Exception('Could not send email.');
}
}
}
the email message that arrives
example from text book I'm learning from

check if you are sending the $password variable as parameter correctly,
may be its empty

First please check that you have a double $result before the if declaration.
$result = $result = $mysqli->query($query);
After that you could try to make a var_dump to $password variable to check if it was correctly passed to the notify_password function. You could also post the $password variable definition so we could check in more depth.

Related

How would I go by checking if email is already in use?

I have been working on my account creation page and I am stuck onto where I should be checking if email is already in use and how to go by it. would I need to make a query statement like this
Select * from Customers WHERE Email = $email)
and check that way?
<?php
session_start();
?>
<?php require_once("headerTH.html") ?>
<?php
$db= new PDO("sqlite:onlinestore.db");
if(ISSET($_POST['register'])){
$username = $_POST['username'];
$email = $_POST['email'];
$psw = sha1($_POST ['psw']);
$tel = $_POST['tel'];
if(! empty($email) && !empty($psw)) {
$query = "INSERT INTO Customers (UserName, Passwd, PhoneNumber, Email) VALUES(:UserName, :Passwd, :PhoneNumber, :Email)";
$result = $db->prepare($query);
$result->bindParam(":UserName", $username);
$result->bindParam(":Passwd", $psw);
$result->bindParam(":Email", $email);
$result->bindParam(":PhoneNumber", $tel);
// Account pass or fail
if($result->execute()){
echo"You have successfully created an account.{$_POST['email']}<br>";
}else{
///print_r($db->errorInfo());
require_once("create.php");
}
} else {
echo "all fields are required";
require_once("create.php");
}
} else {
require_once("create.php");
}
?>
<?php require_once("footerT.html")?>
I think the ideal way to do this is to check if the new email exists in the database, and based on that situation. The user will be able to create the account if the new email doesn't exist in the database, otherwise you should show an alert that email already exists.
Just required a simple if statment at the top
$stmt = $db->prepare("SELECT * FROM Customers WHERE Email=?");
$stmt->execute([$email]);
$user = $stmt->fetch();
if($user){
//email found
echo "Email already used";
}else if($result->execute()){
echo"You have successfully created an account.{$_POST['email']}<br>";
}else{
///print_r($db->errorInfo());
require_once("create.php");
}
} else {
echo "all fields are required";
require_once("create.php");
}
}
If it's me, YES, like what you said, I create a new function let say function checkUserByEmail($email) to check if the email already exists or not.
Then again you can use the same function if you need to check the user by email, let say at the time of login (if you using email for login).
By the way, DON't FORGET TO SANITIZE YOUR INPUTS ;)

Register form won't process a new member PHP

I'm making a website that users can log in and new members can sign in, but when I go and test the site and go to the new member button to register, it gives me a warning saying that the password has to be between 6 and 12 characters even when I do put a password in that is in between those parameters. The code that I'm using is
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
// include function files for this application
require_once('bookmark_fns.php');
//create short variable names
$email=$_POST['email'];
$username=$_POST['username'];
$passwd=$_POST['passwd'];
$passwd2=$_POST['passwd2'];
// start session which may be needed later
// start it now because it must go before headers
session_start();
try {
// check forms filled in
if (!filled_out($_POST)) {
throw new Exception('You have not filled the form out correctly. Please go back and try again.');
}
// email address not valid
if (!valid_email($email)) {
throw new Exception('That is not a valid email address. Please go back and try again.');
}
// passwords not the same
if ($passwd != $passwd2) {
throw new Exception('The passwords you entered do not match. Please go back and try again.');
}
// check password length is ok
// ok if username truncates, but passwords will get
// munged if they are too long.
if (!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z]{6,12}$/', $passwd)) {
throw new Exception('Your password must be between 6 and 12 characters inclusive. Please go back and try again.');
}
// attempt to register
// this function can also throw an exception
register($username, $email, $passwd);
// register session variable
$_SESSION['valid_user'] = $username;
// provide link to members page
do_html_header('Registration successful');
echo "Welcome " . $_POST["username"];
echo 'Your registration was successful. Go to the members page to start setting up your bookmarks!';
do_html_url('member.php', 'Go to members page');
// end page
do_html_footer();
}
catch (Exception $e) {
do_html_header('Warning:');
echo $e->getMessage();
do_html_footer();
exit;
}
?>
I want the page to be able to display the person's name when they've registered correctly or display an error message saying that they need to enter a password between 6 to 12 characters and being inclusive or if they've not entered an email or name.
EDIT
Since changing the line 34 from 8,12 to 6,12 I have now got Warning: mysqli::mysqli(): (HY000/2002): No such file or directory in the file shown
<?php
function db_connect() {
$result = new mysqli('localhost', 'bm_user', 'password', 'bookmarks');
if (!$result) {
throw new Exception('Could not connect to database server');
} else {
return $result;
}
}
?>
And Warning: mysqli::query(): Couldn't fetch mysqli in the file
require_once('db_fns.php');
function register($username, $email, $password) {
// register new person with db
// return true or error message
// connect to db
$conn = db_connect();
// check if username is unique
$result = $conn->query("select * from user where username='".$username."'");
if (!$result) {
throw new Exception('Could not execute query');
}
if ($result->num_rows>0) {
throw new Exception('That username is taken - go back and choose another one.');
}
// if ok, put in db
$result = $conn->query("insert into user values
('".$username."', sha1('".$password."'), '".$email."')");
if (!$result) {
throw new Exception('Could not register you in database - please try again later.');
}
return true;
}
function login($username, $password) {
// check username and password with db
// if yes, return true
// else throw exception
// connect to db
$conn = db_connect();
// check if username is unique
$result = $conn->query("select * from user
where username='".$username."'
and passwd = sha1('".$password."')");
if (!$result) {
throw new Exception('Could not log you in.');
}
if ($result->num_rows>0) {
return true;
} else {
throw new Exception('Could not log you in.');
}
}
function check_valid_user() {
// see if somebody is logged in and notify them if not
if (isset($_SESSION['valid_user'])) {
echo "Logged in as ".$_SESSION['valid_user'].".<br />";
} else {
// they are not logged in
do_html_heading('Warning:');
echo 'You have not filled the form out correctly.
Please go back and try again.<br />';
do_html_url('login.php', 'Login');
do_html_footer();
exit;
}
}
function change_password($username, $old_password, $new_password) {
// change password for username/old_password to new_password
// return true or false
// if the old password is right
// change their password to new_password and return true
// else throw an exception
login($username, $old_password);
$conn = db_connect();
$result = $conn->query("update user
set passwd = sha1('".$new_password."')
where username = '".$username."'");
if (!$result) {
throw new Exception('Password could not be changed.');
} else {
return true; // changed successfully
}
}
function get_random_word($min_length, $max_length) {
// grab a random word from dictionary between the two lengths
// and return it
// generate a random word
$word = '';
// remember to change this path to suit your system
$dictionary = '/usr/dict/words'; // the ispell dictionary
$fp = #fopen($dictionary, 'r');
if(!$fp) {
return false;
}
$size = filesize($dictionary);
// go to a random location in dictionary
$rand_location = rand(0, $size);
fseek($fp, $rand_location);
// get the next whole word of the right length in the file
while ((strlen($word) < $min_length) || (strlen($word)>$max_length) || (strstr($word, "'"))) {
if (feof($fp)) {
fseek($fp, 0); // if at end, go to start
}
$word = fgets($fp, 80); // skip first word as it could be partial
$word = fgets($fp, 80); // the potential password
}
$word = trim($word); // trim the trailing \n from fgets
return $word;
}
function reset_password($username) {
// set password for username to a random value
// return the new password or false on failure
// get a random dictionary word b/w 6 and 13 chars in length
$new_password = get_random_word(6, 13);
if($new_password == false) {
throw new Exception('Could not generate new password.');
}
// add a number between 0 and 999 to it
// to make it a slightly better password
$rand_number = rand(0, 999);
$new_password .= $rand_number;
// set user's password to this in database or return false
$conn = db_connect();
$result = $conn->query("update user
set passwd = sha1('".$new_password."')
where username = '".$username."'");
if (!$result) {
throw new Exception('Could not change password.'); // not changed
} else {
return $new_password; // changed successfully
}
}
function notify_password($username, $password) {
// notify the user that their password has been changed
$conn = db_connect();
$result = $conn->query("select email from user
where username='".$username."'");
if (!$result) {
throw new Exception('Could not find email address.');
} else if ($result->num_rows == 0) {
throw new Exception('Could not find email address.');
// username not in db
} else {
$row = $result->fetch_object();
$email = $row->email;
$from = "From: support#phpbookmark \r\n";
$mesg = "Your PHPBookmark password has been changed to ".$password."\r\n"
."Please change it next time you log in.\r\n";
if (mail($email, 'PHPBookmark login information', $mesg, $from)) {
return true;
} else {
throw new Exception('Could not send email.');
}
}
}
?>
Your regex is off. You want 6-12 characters, but your regex is accomodating 8-12:
{8,12}
Change to:
{6,12}
But as was pointed out in the comments, there is no reason you should be messing with a user's password, offering (forcing) restrictions like that. And to be perfectly honest, when (and it's been a long time since) I come across a site that restricts what I can use as a password, I simply don't register.

Registration form: problems with email check

i have a problem with the realization of a registration form. My php script should check if the user email is already in use.
if the email is in use the php script should show an error message, if it is not the registration is successfully completed.
$email = $_POST['email'];
try{
$sql = "SELECT count(mail) FROM user WHERE mail = '$email'";
$result = $pdo->exec($sql);
}catch(PDOException $e){
echo $e;
exit(); }
if($result == 0){
//registration complete }
else{
//email already in use }
my problem is that i obtain always 0 as result also if the email is already inside the database. But if i execute that sql code inside my xampp' server i obtain 1 so the code works perfectly.
Thank you to all for help :)
You need to do this:
$email = $_POST['email'];
try{
$sql = "SELECT mail FROM user WHERE mail = :email";
$sql = $pdo->prepare($sql);
$sql->execute(array(':email'=> $email));
}catch(PDOException $e){
echo $e;
exit(); }
if($sql->rowCount() == 0){
//registration complete }
else{
//email already in use }

PHP Email Confirmation Function MySQL Database error

There are many questions about email confirmation, databases, and permissions on Stackoverflow, but nothing I could find that would help me with this.
This specific question is directed to an email confirmation function built with PHP. The tutorial I am using can be found here: http://www.phpeasystep.com/phptu/24.html. Everything is working, however when the user clicks the email confirmation link (which would move their information from the temp_table to the confirmed_table), I receive this error:
Error updating database: No database selected
From what I have gathered from different sites/research/Stackoverflow questions is that this is due to the permissions of the database(s) I am working with (please correct me if it is another problem). I have read that I need to change all the users to be able to READ, but am unsure whether I should do this to both the databases as a whole (I couldn't find whether you can set the privileges for all the users in a database to automatically have the READ privileged), or the PHP when I add them to the temp_table. The tutorial I showed above doesn't say anything about it, so I am confused.
Registration form code:
<?php
session_start();
if(isset($_SESSION['aI']) || isset($_SESSION['pss'])) {
header("Location: pa.php");
}
include 'db.php';
if(isset($_POST['rSub'])) {
// connects to database using PHP Data Objects, throws exception if error in connection
try {
$conn = new PDO("mysql:host=$svrHost;db=$svrDb", $sUme, $sp);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "ERROR: " . $e->getMessage();
}
$error = '';
if($_POST['fN'] == '' || $_POST['lN'] == '' || $_POST['aI'] == '' || $_POST['eml'] == '' || $_POST['pss'] == ''
|| $_POST['pss2'] == '') {
$error = "<li style=\"color:#C70000; font-weight:bold;\"><center>- All fields are required. Try again.</font><center></li>";
}
if($error == '') {
$fN = ucfirst($_POST['fN']);
$lN = ucfirst($_POST['lN']);
$aI = $_POST['aI'];
$eml = $_POST['eml'];
$pss = $_POST['pss'];
$pss2 = $_POST['pss2'];
$admin = 0;
if($error != '') {
$error = "<ul>".$error."</ul>";
$_SESSION['error'] = $error;
}
else {
$hF = "$2y$10$"; // 2y = blowfish and 10 = num of hashes
$sa = "testsaltforwebsite1219"; //"random" 22-character sa
$fAS = $hF.$sa;
$sha = crypt($pss, $fAS);
// Random confirmation code
$c_cd=md5(uniqid(rand()));
$insert = $conn->prepare("INSERT INTO t_awhole (c_cd, fN, lN, aI, eml, pss)
VALUES (:c_cd, :fN, :lN, :aI, :eml, :pss)");
$insert->bindParam(':c_cd', $c_cd);
$insert->bindParam(':fN', $fN);
$insert->bindParam(':lN', $lN);
$insert->bindParam(':aI', $aI);
$insert->bindParam(':eml', $eml);
$insert->bindParam(':pss', $sha);
$result=$insert->execute();
// ---------------- Confirmation email ---------------- \\
// table name
$t_apart=t_awhole;
if($result){
// send e-mail to ...
$to=$eml;
// Your subject
$subject="Registration Confirmation";
// From
$header="from: no-reply#example.com"; //Need the address to send the eml to.
// Your message
$message="Copy and paste this link in your browser to activate your account: \r\n";
$message.="\n";
$message.="(serverAddress)/confirmation.php?passkey=$c_cd \r\n";
$message.="\n";
$message.="Thank you";
// send eml
$sml = mail($to,$subject,$message,$header);
}
// if not found
else {
echo "Your email Is Not Registered. Please Register.";
}
// if your email succesfully sent
if($sml){
echo '<script> window.location.href="emlC.php"</script>';
}
else {
echo "Cannot Send Confirmation Link To Your email Address.";
}
// ---------------- Confirmation email ---------------- \\
$_SESSION['aI'] = $aI;
$_SESSION['pss'] = $pss;
$_SESSION['admin'] = 0;
$stmt = $conn->prepare("SELECT DISTINCT dN, dU, ex FROM doc WHERE aI != '0'");
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row)
{
$ex = $row['ex'];
$dU = $row['dU'];
$dN = $row['dN'];
$insert = $conn->prepare("INSERT INTO doc (dN, dU, aI, ex)
VALUES (:dN, :dU, :aI, :ex)");
$insert->bindParam(':aI', $aI);
$insert->bindParam(':ex', $ex);
$insert->bindParam(':dU', $dU);
$insert->bindParam(':dN', $dN);
$insert->execute();
}
}
}
?>
Confirmation page code:
<?php
include('db.php');
// passkey that got from link
$pk=$_GET['pk'];
$t_awhole_conf="t_awhole";
// Retrieve data from table where row that match this passkey
$sql_conf1="SELECT * FROM $t_awhole_conf WHERE confirm_code ='$pk'";
$result_conf=mysql_query($sql_conf1) or die ('Error updating database: '.mysql_error());
// If successfully queried
if($result_conf){
// Count how many row has this passkey
$count=mysql_num_rows($result_conf);
// if found this passkey in our database, retrieve data from table "t_awhole"
if($count==1){
$rows=mysql_fetch_array($result_conf);
$fN = $rows['fN']; // capitalizes the first letter (6-26-14)
$lN = $rows['lN']; // capitalizes the first letter (6-26-14)
$aI = $rows['aI'];
$eml = $rows['eml'];
$pss = $rows['pss'];
$pss2 = $rows['pss2'];
$a_whole_conf="a_whole";
// Insert data that retrieves from "t_awhole" into table "a_whole"
$sql_conf2="INSERT INTO $a_whole_conf(fN, lN, aI, eml, pss, admin)
VALUES ($fN, $lN, $aI, $eml, $pss, $admin)";
$result_conf2=mysql_query($sql_conf2);
}
// if not found passkey, display message "Wrong Confirmation code"
else {
echo "Wrong Confirmation code";
}
// if successfully moved data from table"t_awhole" to table "a_whole" displays message "Your account has been activated" and don't forget to delete confirmation code from table "t_awhole"
if($result_conf2){
echo "Your account has been activated";
// Delete information of this user from table "t_awholeb" that has this passkey
$sql_conf3="DELETE FROM $t_awhole_conf WHERE confirm_code = '$pk'";
$result_conf3=mysql_query($sql_conf3);
}
}
?>
In your Registration form code, you have two lines that create the connection to the database (new PDO ...). You can further use $conn to execute statements.
In your Confirmation code, you don't create any connection before calling mysql_query (why the switch from PDO to mysql functions ?).
See the mysql_query documentation here.

PHP Foreach used to send emails from database?

I am a bit confused about how to use foreach. I read some internet things on it and I kind of understand how it works, but I don't fully understand it. I think I could use foreach to create a PHP mass emailer that sends blank carbon copy to email addresses and adresses the customer by name in the subject (Dear, Michael Here is your email). I've figured out how to retrieve the names and emails from my database into variables and I know how to email, but I don't know how to send multiple emails at once and to associate the name and email address.
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "MichaelBerna.db.10339998.hostedresource.com";
$username = "MichaelBerna";
$dbname = "MichaelBerna";
//These variable values need to be changed by you before deploying
$password = "********";
$usertable = "subscribers";
$yourfield = "name";
$yourfield1 = "email";
//Connecting to your database
$link = mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database! Please try again later.");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result)
{
while($row = mysql_fetch_array($result))
{
$name = $row["$yourfield"];
$email = $row["$yourfield1"];
echo "Name: $name<br>";
echo "Email: $email<br>";
//mysqli_free_result($result);
//mysqli_close($link);
}
}
?>
Here is my email code:
<?php
require_once '../PHPMailer_5.2.2/class.phpmailer.php';
$name = $_POST['name'] ;
$email = $_POST['email'] ;
//$file = $_POST['file'] ; // I'm going to later add a file later to be attached in email from database
$body = "Hey $name thank you for continuing to be a valued customer! This month's story is included in this email asa an attachment.";
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
try
{
$mail->AddAddress($email, $name);
$mail->SetFrom('admins_email#yahoo.com', 'Site Admin');
$mail->AddReplyTo('admins_email#yahoo.com', 'Site Admin');
$mail->Subject = "Dear $name Your monthly subscription has arrived!";
$mail->Body = $body;
if ($_FILES['file']['size'])
{
$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);// attachment
}
$mail->Send();
echo "Email Sent Successfully</p>\n";
}
catch (phpmailerException $e)
{
echo $e->errorMessage(); //Pretty error messages from PHPMailer
}
catch (Exception $e)
{
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
Basically, I need a way to combine these two scripts and link them together and that's what I'm unsure of how to do.
Put the mailing code in a function, e.g. send_mail(), so that it can be called from different places. Then change your database query loop to:
while ($row = mysql_fetch_assoc($result)) {
send_mail($row['name'], $row['email'), "Text of the email");
}

Categories