Am creating an application... everything is fine so far. In my registration system have used prepared statement and password hashing and have also try to validate user input in my form fields as well. In order for this system to be completed i need to create a forgot password system which means user can request for new password.
What have done is i have a testing site with all the files, which means i can test if works before adding it to the production site.
With the forgot password have used mysqli once everything is working fine i will then update to prepared, because am still learning prepared statement and doing it this way help me understand so don't judge.
The problem am having with my forgot password is the password is not updating once change. see this screenshot: http://prntscr.com/d5hage
Also as mentioned above have used http://prntscr.com/d5hbg1 in my register and verify in my log-in. But how do used the hashing in my forgot password or how do i update it. In my code below have used md5 which am aware is broken. Please all my coding below.
Reset_Password.php
<?php
// include connection
require_once('include/connection.php');
if(isset($_POST['submit'])){
$user_id = base64_decode($_GET['encrypt']);
$passnew = password_hash($password, $_POST['new_password'], PASSWORD_BCRYPT, array( 'cost' => 12 ) );
$sql = "UPDATE `olami560_test`.`user` SET `password` =? WHERE `user`.`id` =?";
$stmt = $con->prepare($sql);
$stmt->bind_param('si',$passnew, $user_id);
$stmt->execute();
if ($stmt->errno) {
echo "FAILURE!!! " . $stmt->error;
}
else echo "Password Changed Successfully.Click on link to login <a href='http://www.olaskee.co.uk/project/allocation/progress/index.php'>Login</a>{$stmt->affected_rows} rows";
$stmt->close();
}
?>
<form method="post" action="<?php echo $_SERVER['HTTP_REFERER']; ?>" >
<label>New Password</label>
<input type="password" name="new_password"/>
<input type="submit" name="submit" value="Reset" />
</form>
forgot_password.php
<?php
// include connection
require_once('include/connection.php');
if(isset($_GET) && !empty($_GET['email'])){
$email = mysqli_real_escape_string($con,$_GET['email']);
$query = "SELECT id
FROM `user`
WHERE `user_name` LIKE '".$email."'
OR `email` LIKE '".$email."'";
$result = mysqli_query($con,$query);
$Results = mysqli_fetch_array($result);
if(count($Results)>=1)
{
$query2 = "SELECT email
FROM `user`
WHERE `user_name` LIKE '".$email."'
OR `email` LIKE '".$email."'";
$result2 = mysqli_query($con,$query2);
$emailvalue = mysqli_fetch_array($result2);
//$token = md5(uniqid(rand(),true));
//$encrypt = md5($Results['id']);
$encrypt = base64_encode($Results['id']);
$message = "Your password reset link send to your e-mail address.";
$to = $emailvalue['email'];
$subject="Forget Password";
$from = 'leksmaster#gmail.com';
$body= 'Hi, <br/> User <br/>You Requested for Reset Password. <br><br>http://www.olaskee.co.uk/project/allocation/tms/reset_password.php?token='.$token.'&encrypt='.$encrypt.'&action=reset<br/> <br/>--<br>.olaskee<br>';
$headers = "From: " . strip_tags($from) . "\r\n";
$headers .= "Reply-To: ". strip_tags($from) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to,$subject,$body,$headers);
echo $message;
}
else
{
$message = "Account not found please signup now!!";
echo $message;
}
}
?>
I hope have provide enough explanation for you to understand. Thanks any input.
ok, looking through the code there are a few things I think you need to look at.
On the form change this
<form method="post" action="<?php echo $_SERVER['HTTP_REFERER']; ?>" >
to
<form method="post" action="" >
This should submit the form to itself.
The hashing really needs to be password_hash() use the following and it will get you started
$passnew = password_hash( $password, $_POST['new_password'], PASSWORD_BCRYPT, array( 'cost' => 12 ) );
On the form for resetting the password it is a good idea to have the user input the new password twice, that way you can check if they have repeated the password correctly.
if( $_POST[ 'pass1' ] == $_POST[ 'pass2' ] ) // Process else error
In your forgot_password.php file you are calling the same sql statement twice. Call it once, check if the row count is greater then one, if it is use the data from within the result, no need to call it again to do the same thing.
Hopefully this will get you going, have a good day.
Related
First of all I'm very new to PHP so don't be to hard on me. I'm trying to make a forgot password system for my website, but I can't update the password in the mysql database with sha1. If I do it before sha1 encrypting it works(commented out query in the code)
What I want is to receive a random password on the users mail, but in the database I want it to be encrypted with sha1.
Could really use some help here.
<?php
include("connect.php");
if(isset($_POST["email"])) {
$email = $con->real_escape_string($_POST["email"]);
$data = $con->query("SELECT * FROM bruker WHERE ePost='$email'");
if ($data->num_rows > 0) {
$str = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
$str = str_shuffle($str);
$str = substr($str, 0, 15);
$passwordD = $str;
//$con->query("UPDATE bruker SET passord = '$passwordD' WHERE ePost='$email'");
echo $passwordD;
$url = "http://localhost/example";
$msg = "Your new password is: $passwordD\nTo change your password, please visit this: $url";
$subject = "Reset Password";
$headers = "From: Vikerfjell" . "\r\n";
mail($email, $subject, $msg, $headers);
$salt = 'IT2_2017';
$passwordE = sha1($salt.$passwordD);
echo $passwordE;
$con->query("UPDATE bruker SET passord = '$passwordE' WHERE ePost='$email''");
} else {
echo "Please check your link:";
}
} else {
header("Location: index.php");
}
mysqli_close($con);
?>
<form name="form" action="" method="post">
<input type="text" name="email" value="">
<input type="submit" name="update password" />
</form
check the form method in the first then remove the single qoute in this line of code to be as shwon
$con->query("UPDATE bruker SET passord = '$passwordE' WHERE ePost='$email' ");
Note: the mail function will not work on the localhost
I am new to PHP, and I have been working on setting up a reset password script. The biggest problem I am having is storing the last part of the URL into the variable $token.
What exactly do I need to have to ensure that the $token variable gets set after the user clicks the 'Reset Password' button? As of now, after the button is clicked, $token is not set to anything and the url turns into "www.website.com/resetpassword.php" without the token at the end. Thanks for your help!
Here is my form code:
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<div class="login_form">
<h2 style="font-family: Helvetica, sans-serif; font-size: 28pt; padding-top: 50px;">Forgot Password</h2>
<input type="email" name="email" placeholder="Your Email" maxlength="60"/>
<?php
if ( isset($sucMSG) ) {
echo '<span class="successful_registration">'.$sucMSG.'</span>';
}
if ( isset($matchError) ) {
echo '<span class="text-danger">'.$matchError.'</span>';
}
if ( isset($keyError) ) {
echo '<span class="text-danger">'.$keyError.'</span>';
}
?>
<br>
<input type="password" name="pass" placeholder="New Password" maxlength="255" />
<br>
<input type="password" name="cpass" placeholder="Confirm Password" maxlength="255" />
<input type="hidden" name="token" value= "random" />
<br>
<button type="submit" name="btn-reset">Reset Password</button>
<br><br><br>
<br><br><br><br><br><br>
</div>
</form>
Here is the PHP code:
if (isset($_POST['btn-reset'])){
// Gather the post data
$email = trim($_POST['email']);
$email = strip_tags($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$cpass = trim($_POST['cpass']);
$cpass = strip_tags($cpass);
$token = $_GET ['token'];
// Retrieve token from database
$stmt = $conn->prepare('SELECT token FROM token WHERE userEmail=? and NOW() < expire_date');
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$resetKey = $row['token'];
}
// Does the new reset key match the old one?
if ($resetKey == $token && isset($token)){
if ($pass == $cpass){
//hash and secure the password
$password = password_hash($pass, PASSWORD_DEFAULT);
// Update the user's password
$stmt = $conn->prepare('UPDATE user SET userPass = ? WHERE userEmail = ?');
$stmt->bind_param('s', $password);
$stmt->bind_param('s', $email);
$stmt->execute();
$conn = null;
$sucMSG = "Your password has been successfully reset.";
unset($email);
unset($pass);
unset($cpass);
unset($token);
unset($resetKey);
}
else
$matchError = "Your password's do not match.";
}
else
$keyError = "Your password reset key is invalid.";
}
Here is the PHP code from the previous step (forgotpassword.php):
if (isset($_POST['email'])){
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$stmt = $conn->prepare('SELECT * FROM user WHERE userEmail = ?');
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
$count=mysqli_num_rows($result);
// If the count is equal to one, we will send message other wise display an error message.
if($count==1){
$rows=mysqli_fetch_array($result);
$length = 55;
$token = bin2hex(random_bytes($length));//Creating Token
$create_date = date('Y-m-d H:i:s',strtotime("now"));
$expire_date = date('Y-m-d H:i:s',strtotime("+3 hours"));
//Using prepared statements to prevent SQL Injection
$stmt = $conn->prepare('INSERT INTO token (token, userEmail, create_date, expire_date) VALUES (?, ?, ?, ?)');
$stmt->bind_param('ssss', $token, $email, $create_date, $expire_date);
$stmt->execute();
// Create a url which we will direct them to reset their password
$pwrurl = 'https://www.domain.com/resetpassword.php?token='.$token;
$to = $rows['userEmail'];
//Details for sending E-mail
$from = "Company";
$body = "Company password recovery<br>
-----------------------------------------------<br><br>
Welcome to Company password recovery.
You can reset your password by clicking the following link: $pwrurl.<br><br>
Sincerely,<br><br>
Company";
$from = "support#company.com";
$subject = "Company Password recovered";
$headers1 = "From: $from\n";
$headers1 .= "Content-type: text/html;charset=iso-8859-1\r\n";
$headers1 .= "X-Priority: 1\r\n";
$headers1 .= "X-MSMail-Priority: High\r\n";
$headers1 .= "X-Mailer: Just My Server\r\n";
$sentmail = mail ( $to, $subject, $body, $headers1 );
}
elseif ($_POST['email'] == ""){
$fMSG = "Please enter an email address.";
} /*else {
if ($_POST['email'] != "")
$wMSG = "Cannot send password to your email address. Problem with sending mail.";
}*/
//If the message is sent successfully, display sucess message otherwise display an error message.
if($sentmail==1){
$sMSG = "Your Password Has Been Sent To Your Email Address.";
}
else{
if($_POST['email']!="")
$nMSG = "Cannot send password to your email address. Problem with sending mail.";
}
}
Note: I am posting as a community wiki, since no rep gain should come of this.
"Why don't you use the token as a hidden field rather than in query string, just a suggestion. – HSharma"
...
#Fred-ii- I don't know how to ping people, but the comment above this one has what ended up solving my problem. Thanks for your help! – jh95"
"#HSharma suggestion was what ultimately solved my problem. I added this to my html form <?php echo' <input type="hidden" name="token" value="'; if (isset($_GET['token'])) { echo $_GET['token']; } echo '" />' ?> and in my PHP script I added $token = $_POST ['token']; and now the token sets properly. Thanks everyone for your help!"
However and as I stated in comments:
"Since the length for it most probably surpasses the column's length, you need to increase it by ALTERing the column to be of a higher value in length, one big enough. You then need to clear the values from it and start over; you have no choice."
So, I've been trying to create a Signup/Login process using PHP and MySQL. I created a Signup form, and a handling page. Then I tred it out, set the email as a#a.com and password as MyPassword.
I then checked the database and got surprised. The email was correctly inputted, alright, but the password wasn't! It was one of the passwords that I used to test before, and it is a pretty personal one.
Every time I tried it again, the same thing happened. The password was always changed to my personal one whenever I signed up.
The problem is that, in my code, I don't have that personal password, anywhere. I only used it to test my signup flow once, and now it's stuck to my database!
Here, I registered using test credentials. The password is asd and it's obviously 3 letters long.
But when I check the database, I see the following. Even though I edited the password so you can't see it, it's still obvious it's more than 3 letters long.
Is this some kind of MySQL over-writing thing, that I just don't know about yet?
Here is the full code of the SignUp Page (Might be a little long, bear with me):
<?php
session_start();
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['signUpemail'];
$password = $_POST['signUppassword'];
include("mysql_base.php");
echo "Preparing MYSQL Statement...<br>";
echo "<script>";
echo "firstPart()";
echo "function firstPart() {";
echo "document.write('Starting to process MYSQL Statement...')";
echo "window.setTimeout(secondPart(),2000)";
echo "}";
echo "function secondPart() {";
echo "document.write('Starting to stop processing MSYQL Statement...')";
echo "}";
echo "</script>";
echo "Started to proccess...<br>";
$sql = "INSERT INTO pages_accounts (email, pass, firstname, lastname, confirm) VALUES ('".$email."','".$password."','".$firstName."','".$lastName."','0')";
if ($conn->query($sql) === true){
echo "<b>SIGNUP SUCCESS</b><br>";
echo "SUCH HAPPINESS. WOW. MMM.<br><br>";
echo "--Check your mail for a confirmation email. Check SPAM too!--";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: FoxInFlame Pages<pages#foxinflame.tk>' . "\r\n";
$message = "
<html>
<body>
<center>
<div style='background-color:orange'><h1>Confirm your Account</h1><br><h3>At FoxInFlame Pages</h3></div>
You seem to have registered for an account at FoxInFlame Pages. Now please click on the following link to complete your registration, and start creating amazing websites!<br><a href='http://www.foxinflame.tk/pages/confirm.php?id=".$conn->insert_id."'>Click Here</a>
</center>
</body>
</html>
";
mail($email, "[CONFIRM] Account on FoxInFlame Pages", $message);
} else {
echo "MUCH SADNESS. SUCH DEPRESSION. FAIL ERROR. NO RETURN.";
echo "Error: ".$sql."<br>".$conn->error;
};
?>
Your problem will be in include("mysql_base.php");. That file will be setting $password for it's own internal use, which is overwriting the $password variable that you get from $_POST;
2 options to get around this:
1 - Open the database connection first.
<?php
session_start();
include("mysql_base.php");
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['signUpemail'];
$password = $_POST['signUppassword'];
2 - Use different variable names:
<?php
session_start();
include("mysql_base.php");
$signup_firstName = $_POST['firstName'];
$signup_lastName = $_POST['lastName'];
$signup_email = $_POST['signUpemail'];
$signup_password = $_POST['signUppassword'];
Aside from this, the password field on the sign up page doesn't have name="signUppassword", and you have no SQL Injection protection.
On your page I see:
<input style="color:white" type="password" name="password" required="" autocomplete="off">
So your input name is password
But in your code you are trying to get signUppassword:
$password = $_POST['signUppassword'];
Do you have some transformation somewhere ? javascript?
I have a forgot password script in PHP below. The idea of the script is to submit the email address, the script then sees if the email address is on the database, then it changes the password and then sends an email with the temporary address to the email that was submitted in the form.
The script appears to change the password and do everything except it does not appear to actually send the email with the temporary password.
It has been a long time since I have used this script (or PHP for that matter) so any help would be appreciated.
<?php # forgot_password.php
require_once ('./includes/config.inc.php');
$page_title = 'Forgot Password';
include ('./includes/header.html');
if (isset($_POST['submitted'])) { // Handle the form.
require_once ('database-connection.php');
if (empty($_POST['user_email'])) { //Validate the email address.
$uid = FALSE;
echo 'You forgot to enter your email address!';
} else {
$query = "SELECT ID FROM wp_users WHERE user_email='". escape_data($_POST['user_email']) . "'";
$result = mysql_query ($query)or trigger_error("Query:$query\n<br />MySQL Error: " .mysql_error());
if (mysql_num_rows($result)== 1) {
list($uid) = mysql_fetch_array ($result, MYSQL_NUM);
} else {
echo 'This email address is not registered';
$uid = FALSE;
}
}
if ($uid) { // If everything's OK.
$p = substr ( md5(uniqid(rand(),1)), 3, 10);
$query = "UPDATE wp_users SET user_pass=SHA('$p') WHERE ID=$uid";
$result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " .mysql_error());
if (mysql_affected_rows() == 1) {
$body = "Your password to log into the site has been temporarily changed to '$p'.
Please log in using this password and your username. At that time you may change your password to something more familiar.";
mail($_POST['user_email'], 'Your temporary password.', $body,
'From:info#website.com.au'); //From email address
echo 'Your password has been temporarily changed.
An email from info#website.com.au will be sent to your registered email address with a new, temporary password which you can log in with.
Once you have logged in with this password, you may change it by clicking on the "Change Password" link at the bottom of your screen.';
mysql_close(); // Close the database connection.
include ('./includes/footer.html'); // Include the HTML footer.
exit();
} else { //If it did not run OK.
echo 'Your password could not be changed due to a system error. We apologize for any inconvenience.';
}
} else { // Failed the validation test.
echo '<p><font color="red"size="+1">Please try again.</font></p>';
}
mysql_close(); // Close the database connection.
} // End of the main Submit conditional.
?>
<p>Enter your email address below and your password will be reset.</p>
<form action="forgot_password.php" method="post">
<p><b>Email Address:</b> <input type="text"
name="user_email" size="30" maxlength="40" value="<?php if (isset($_POST['user_email'])) echo $_POST['user_email']; ?>" /></p>
<div align="center"><input type="submit" name="submit" value="Reset My Password" /></div>
<input type="hidden" name="submitted" value="TRUE" />
</form>
<?php
include ('./includes/footer.html');
?>
When you enter your password in DB try to avoid hashing algorithm. SHA is a hashing algorithm not a encrypt algorithm. Please make sure your password field in database must have a big length. I think your SHA() generates a long string. If all things are working fine then please change your mail header to below.
$header = "From: noreply#example.com\r\n";
$header.= "MIME-Version: 1.0\r\n";
$header.= "Content-Type: text/plain; charset=utf-8\r\n";
$header.= "X-Priority: 1\r\n";
and try
mail($to,$from,$message,$header);
I have already asked this before but I never seem getting how it works(I tried a lot but no success at all) could someone tell me how can I send a activation link to the users email address up on registration and don't allow the user until they activate their account by following the link in the email address? What should I do? I'm not getting it at all...please help me out..
What I have in a table users in database:
1 id int(11) AUTO_INCREMENT
2 username varchar(255)
3 password char(64)
4 salt char(16)
5 email varchar(255)
register.php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the registration form has been submitted
// If it has, then the registration code is run, otherwise the form is displayed
if(!empty($_POST))
{
// Ensure that the user has entered a non-empty username
if(empty($_POST['username']))
{
echo "Please enter a username.";
}
// Ensure that the user has entered a non-empty password
if(empty($_POST['password']))
{
die("Please enter a password.");
}
// Make sure the user entered a valid E-Mail address
// filter_var is a useful PHP function for validating form input, see:
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
$query = "
SELECT
1
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if($row)
{
die("This username is already in use");
}
// Now we perform the same type of check for the email address, in order
// to ensure that it is unique.
$query = "
SELECT
1
FROM users
WHERE
email = :email
";
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if($row)
{
die("This email address is already registered");
}
// An INSERT query is used to add new rows to a database table.
// Again, we are using special tokens (technically called parameters) to
// protect against SQL injection attacks.
$query = "
INSERT INTO users (
username,
password,
salt,
email
) VALUES (
:username,
:password,
:salt,
:email
)
";
$to = "email";
$subject = "Your Account Information!";
$body = <<<EMAIL
Hello {'email'}, here is your account information!
Username:{'username'}
Password:{'password'}
Please activate your account by clicking the following activation link:
http://www.mywebsite.com/activate.php?aid={$aid}
EMAIL;
$headers = 'From: noreply#yourdomain.com' . "\r\n" .
'Reply-To: noreply#yourdomain.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
if(mail($to, $subject, $body, $headers)){
echo("<p>Your account information was successfully sent to your email - ('email')! <br><br>Please open your email and click the activation link to activate your account.</p><br><p>If you do not see your account information in your inbox within 60 seconds please check your spam/junk folder.</p>");
} else {
echo("<p> Unfortunately, your account information was <u>unsuccessfully</u> sent to your email - ('email'). </p>");
}
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['password'] . $salt);
for($round = 0; $round < 65536; $round++)
{
$password = hash('sha256', $password . $salt);
}
$query_params = array(
':username' => $_POST['username'],
':password' => $password,
':salt' => $salt,
':email' => $_POST['email']
);
try
{
// Execute the query to create the user
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
}
header("Location: login.php");
die("Redirecting to login.php");
}
?>
<h1>Register</h1>
<form action="" method="post">
Username:<br />
<input type="text" name="username" required value="" />
<br /><br />
E-Mail:<br />
<input type="text" name="email" required value="" />
<br /><br />
Password:<br />
<input type="password" required name="password" value="" />
<br /><br />
<input type="submit" value="Register" />
</form>
login.php
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
$submitted_username = '';
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
// The parameter values
$query_params = array(
':username' => $_POST['username']
);
try
{
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
// Redirect the user to the private members-only page.
header("Location: private.php");
die("Redirecting to: private.php");
}
else
{
// Tell the user they failed
print("The Username/Password is invalid.");
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
<h1>Login</h1>
<form action="login.php" method="post">
Username:<br />
<input type="text" name="username" required value="<?php echo $submitted_username; ?>" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" required />
<br /><br />
<input type="submit" value="Login" />
</form>
Register
For one you're not emailing the user anything in this script. What you should do is create a registration table and store the values there along with a token and a datetime. Some URL based identifier. A simple md5 of the email and timestamp concat would work fine.
$token = md5($_POST['email'].time());
Then email the user a link - something like:
http://www.yoursite.com/register/confirm?token=yourmd5token
This script would fetch the stored user info from that token, make sure the datetime was within an hour or so, then push the data into the user table only on confirmation so you don't fill up a table unnecessarily.
Based on the code you provided, you're not a true beginner in PHP. So you should have no problems google searching examples of the things mentioned. This is too involved to write it all out for you since typically SO is used for quick help and basic QA. Yours is more of a full project thing.
Here is a conceptual overview of one way to do email verification. This question is still too high level to add in any real code to the answer. Also, please consider this may not be the best way to do verification, just a simple way.
Add 2 columns to the database:
is_verified
verification_token
In login.php:
When creating the user set is_verified=0 and create a random verification_token.
After creating the user, build a link to verify.php with the token as a query string parameter.
Send an email to the email address with the link to verify
Redirect the user to a page called verificationWaiting.php which alerts them to check their email and click the link.
Create a page called verify.php that:
Checks the database for a the token in the query string and sets the is_verified flag to true if the user with the toke is found.
Redirects the user to the login page
Modify login.php to make sure the user has is_verified set as an authentication condition.
This is just a broad overview of one way to do it. There are many additional features you could add. Hope this helps get you started.
You have some options, you can add a new column named something like "active" and default that to 0 until the user has clicked on a generated link (say, yoursite.com/activate.php?key=)
have the key = something like the users email address.
Once the user has clicked the link and entered the password they have on file from previously registering, you can set the active column to 1.
The second option is to generate a random password, and require the user to get the password from his/her email. Thus requiring a valid email address.