Email verification using php - php

I am new here, and I am continuing previous developer website for the client.
This web will sent an verification email for user after the user sign up for member in the web.
The email is send to the user but my problem now is that the verification doesn't work. When the user click on the verification link, it's does link to the verification.php but show a blank page.
I don't know where is the problem.
This is the account_verification.php file:
session_start();
require_once 'cms/configuration.php';
$username = $_GET['e_username'];
$key = $_GET['key'];
$sql = "SELECT * FROM member WHERE username = '$username'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$memberID = $row['id'];
if ($key == md5($username.$row['id']))
{
$sql = "UPDATE member SET verified = '1' WHERE id = '{$row['id']}'";
$result = mysql_query($sql);
echo ' <script type="text/javascript">
alert("Your account is activated.");
window.location = "homepage.php";
</script>';
}
?>
And this is the membersignup.php file:
<?php
session_start();
require_once 'cms/configuration.php';
include "includes/phpmailer.php";
foreach ($_POST as $key => $value)
{
$_POST[$key] = $value;
}
$e_username = trim($_POST['username']);
$password = $_POST['password'];
$ic_no = $_POST['ic_no'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$contact = $_POST['contact'];
$address = $_POST['address'];
$comp_name = $_POST['comp_name'];
$comp_address = $_POST['comp_address'];
$comp_contact = $_POST['comp_contact'];
$comp_fax = $_POST['comp_fax'];
$comp_email = $_POST['comp_email'];
$about_us = $_POST['about_us'];
$datetime = $_POST['datetime'];
;
$result = mysql_query("SELECT username FROM member WHERE username='$e_username'");
$num_records = mysql_num_rows($result);
if ($num_records !=0){
echo "Please use different username.";
exit();
}
$sql = sprintf("INSERT INTO member (username, password, ic_no,email, birthday, contact, address, company_name, company_address, company_contact, company_fax, company_email, about_us, register_date)
VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',NOW())",
mysql_real_escape_string($e_username),
md5($password),
mysql_real_escape_string($ic_no),
mysql_real_escape_string($email),
mysql_real_escape_string($dob),
mysql_real_escape_string($contact),
mysql_real_escape_string($address),
mysql_real_escape_string($comp_name),
mysql_real_escape_string($comp_address),
mysql_real_escape_string($comp_contact),
mysql_real_escape_string($comp_fax),
mysql_real_escape_string($comp_email),
mysql_real_escape_string($about_us),
mysql_real_escape_string($datetime)
);
$result = mysql_query($sql) or die(mysql_error());
$insertID = mysql_insert_id();
$key = md5($_POST['username'].$insertID);
$link = "http://___/account_verification.php?username={$_POST['username']}&key=$key";
$body = "<div>
<p style='padding:10px;'>
Hello {$_POST['username']}!
</p>
<p style='padding:10px;'>
Thank you for creating an account at ___.
</p>
<p style='padding:10px;'>
Please keep this e-mail for your records. Your account information is as follows:<br/>
Username : $e_username <br/>
Password : {$_POST['password']}
</p>
<p style='padding:10px;'>
Verify your account to complete your registration by clicking the link:<br/>
<a href='$link' target='_blank'>$link</a>
</p>
<p style='padding:10px;'> </p>
<p style='padding:10px;'>
Thanks,<br/>Admin
</p>
</div>";
$subject = "Member Registration and Verification";
if ($result)
{
$sendMailResult = sendPHPMail('noreply#___.com', '___', $_POST['email'], $subject, $body);
if($sendMailResult == TRUE)
echo 1;
else
echo "There's problem sending validation mail to your email. Please try again later.";
}
else
{
echo "There's problem saving your registration details to our database. Please try again later.";
}
?>
Can anyone help me to find what is the problem here?

You are searching for a user that matches $username = $_GET['e_username']; when you are actually only sending in the url username
So, your account_verification.php should be
session_start();
require_once 'cms/configuration.php';
$username = $_GET['username'];
$key = $_GET['key'];
$sql = "SELECT * FROM member WHERE username = '$username'";
etc ...
And your link to this script should be as follows: (note: your username variable is changed to $_POST['e_username']
$link = "http://___/account_verification.php?username={$_POST['e_username']}&key=$key";

Related

Is there any other way of fixing this OTP verification problem?

Am making an verification system after the user signup he/she will be redirected to verify the with otp code. The code doesn't seem to work when i tried it out and displays no error to show.
<?php
include_once("__DIR__ . '/../connection/conn.php");
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$pass = mysqli_real_escape_string($conn, md5($_POST['password']));
$cpass = mysqli_real_escape_string($conn, md5($_POST['cpassword']));
$role = 'user';
$verification_status = '0';
$otp = mt_rand(1111,9999); //create 4 digits otp
$activation_code = rand(time(),10000000); //create a user unique id
$select_users = mysqli_query($conn, "SELECT * FROM `userssystem1` WHERE email = '$email' AND password = '$pass'") or die('query failed');
if(mysqli_num_rows($select_users) > 0){
$message[] = 'user already exist!';
}else{
if($pass != $cpass){
$message[] = 'confirm password not matched!';
}else{
mysqli_query($conn, "INSERT INTO `userssystem1`(username, email, password, role, otp, activation_code, verification_status) VALUES('$username', '$email' , '$cpass' , '$role', '$otp', '$activation_code' , '$verification_status')") or die('query failed to insert');
$message[] = 'registered successfully!';
header('location:verify.php?code='.$activation_code);
}
}
}
?>
After i copy the otp from the data table into the otp input field to make the necessary changes on the data table in the database, the verification_status is supposed to change to verified and otp code will be empty from the database table. `verification_status = 'verified'
<?php
//if user verified, so don't show verify page
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1); error_reporting(E_ALL);
include_once("__DIR__ . '/../connection/conn.php");
if(isset($_POST['submit_otp'])){
if(isset($_GET['code'])){
$activation_code = $_GET['code'];
$otp = $_POST['otp'];
$sqlselect = "SELECT * FROM userssystem1 WHERE activation_code = '".$activation_code."'";
$resultSelect = mysqli_query($conn, $sqlselect);
if (mysqli_num_rows($resultSelect) > 0){
$rowSelect = mysqli_fetch_assoc($resultSelect);
$rowOtp = $rowSelect['otp'];
if ($rowOtp !== $otp) {
echo "<script>alert(Please provide correct OTP...!)</script>";
}else{
$sqlUpdate = "UPDATE userssystem1 SET otp = '', verification_status = 'verified' WHERE otp = '".$otp."' AND activation_code = '".$activation_code."'";
$resultUpdate = mysqli_query($conn, $sqlUpdate);
if ($resultUpdate){
echo "<script>alert(Your email has been verified)</script>";
header("Refresh:1; url=signup.php");
}else{
echo "<script>alert(Your email is not verify)</script>";
}
}
}
}
else{
header("Refresh:1; url=verify.php");
}
}
?>
Without seeing more of your code this is really just a guess, but you're checking for $_POST['submit_otp'] but then later down assign $otp to the value of $_POST['otp']. My guess is that maybe the first if (isset(... is coming back false because the $_POST key is wrong. Or, the second assignment is wrong and the SQL comes back with no rows.

The value is not inserting in database

I want to create an API for registration with OTP verification. The OTP is successfully sent on mobile. But the value of users is not inserted in the database. Here is my signup code.
signup.php
<?php
include('config.php');
if( !empty($_POST['name']) &&
!empty($_POST['mobile']) &&
!empty($_POST['email']) &&
!empty($_POST['password'])
){
$name = $_POST['name'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$password = $_POST['password'];
$str = mt_rand(100000, 999999);
$avalible_user_name="";
$avalible_user_email="";
$SQL= mysql_query("SELECT * FROM users WHERE mobile='".$mobile."' ");
while($row=mysql_fetch_array($SQL)){
$avalible_user_name=$row['mobile'];
}
$SQL= mysql_query("SELECT * FROM users WHERE email='".$email."' ");
while($row=mysql_fetch_array($SQL)){
$avalible_user_email=$row['email'];
}
if($avalible_user_name=="" && $avalible_user_email==""){
$SQLQUERY = mysql_query("INSERT INTO users SET
name = '" . $name."',
mobile = '" . $mobile."',
email = '" . $email."',
password = '" . md5($password)."',
otp = '".$str."',
status = 0 ");
$msg = "Your verification code:".$str.".";
$sms_text = str_replace(" ","%20",$msg);
$api_key = '2584909553545C';
$from = 'chkotp';
$api_url = "**My otp url**";
$response = file_get_contents($api_url);
die(json_encode(array("success"=>"true","message"=>"OTP sent to your mobile number please verify.")));
}else{
die(json_encode(array("success"=>"false","message"=>"Mobile or email all ready exits ")));
}
}else{
die(json_encode(array("success"=>"false","message"=>"Empty Parameters..!!")));
}
?>
Your insert query syntax is wrong,
$new_pass = md5($password);
$SQLQUERY = mysql_query("INSERT INTO users( name, mobile, email, password) values('$name','$mobile','$email','$new_pass')");
I hope it helps.

PHP choose another username

I have made a registration PHP file that runs through an authentication and connects to my database that I made in phpMyAdmin. The problem is, I can put in the same username without consequence and it adds to the database, so I could put; dogs as the username and then again put the same.
How can I make it so the user is told; that username already exists choose another one.
Here's my php so far;
Also please tell me where to insert it.
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysql_real_escape_string($username);
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
$password = stripslashes($password);
$password = mysql_real_escape_string($password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query($query);
if ($result) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
} else {
?>
You should query the database before inserting any record (user) to users table.
Try the code below:
<?php
$username = mysql_real_escape_string( $username ); //Sql injection prevention
$existance = mysql_query("SELECT username FROM users WHERE username = '" . $username . "'");
if( !$existance ){
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query( $query );
if ( $result ) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
else{
//unsuccessful insertion
}
} else {
//the user existed already, choose another username
}
?>
Create an if-statement where you check if $username exists in the db. If it does, throw an error. If not, continue with the code.
Note
Your code is vulnerable to SQL-injection. Read this post: How can I prevent SQL injection in PHP?
Rewriting my entire answer to a working example. I'm going to assume your post variables are the same as mine: email, password, username
<?php
$errorMessage = "";
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$email1 = $_POST['email'];
$username1 = $_POST['username'];
$password1 = $_POST['password'];
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
$username = htmlspecialchars($username);
$connect = mysql_connect("localhost","DBuser", "DBpassword");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("DBName");
$results = mysql_query("SELECT * FROM users WHERE username = '$username'");
while($row = mysql_fetch_array($results)) {
$kudots = $row['username']; }
if ($kudots != ""){
$errorMessage = "Username Already Taken";
$doNothing = 1;
}
$result = mysql_query("SELECT * FROM users WHERE email = '$email'");
while($row2 = mysql_fetch_array($results)) {
$kudots2 = $row2['email']; }
if ($kudots2 != ""){
$errorMessage = "Email Already in use";
$doNothing = 1;
}
//test to see if $errorMessage is blank
//if it is, then we can go ahead with the rest of the code
//if it's not, we can display the error
if ($errorMessage == "") {
$user_name = "DBUsername";
$pass_word = "DBPassword";
$database = "DBName";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$email = quote_smart($email, $db_handle);
$password = quote_smart($password, $db_handle);
$username = quote_smart($username, $db_handle);
if ($username1 == ""){
$errorMessage = "You need a username";
}
if ($password1 == ""){
$errorMessage = $errorMessage . "<br>You need a password.";
}
if (!(isset($_POST['email']))){
$errorMessage = $errorMessage . "<br>You need an email.";
}
$SQL = "SELECT * FROM users WHERE email = $email";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "email already exists";
$doNothing = 1;
}
if ($errorMessage == "") {
$SQL = "INSERT INTO users (email, username, password) VALUES ($email, $username, $password)";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['email'] = "$email1";
$_SESSION['password'] = "$password1";
header ("Location: myaccount.php");
else {
$errorMessage = "Database Not Found";
}
}
OK, now echo $errorMessage right below or above the form, to inform the user that the Email, or Username is taken. I'm pretty sure I have a duplicate function in here for the Email, but this code does work; disregard if somebody says it's vulnerable to SQL injection; this is a working EXAMPLE! If you want to do MySQL real escape string, just Google it. I had to rewrite a couple things because I don't want my full code on a public board, if for some odd reason this doesn't work; send me an eMail(canadezo121#gmail.com) and I'll send you the full page code. (Which WORKS!) This code will probably raise some concerns with other more professional coders, this example gives you a good logical viewpoint of what goes on and how it works. You can adjust it to MySQLi, PDO, etc as you get more familiar with PHP and MySQL.
1 you must verify if the username all ready exists in database (Select)
2 if not exists after you can insert the new user

Assigning variables from mysql to php

I am trying to send a username and password , which are from my database through an email to the users. How do i achieve the purpose? I am using the current code below and whenever i receive the email , i realised that the places for $username and $password are empty , which means the database values are not being sent.
<?php
$to = $email;
$subject = "Registered details with BFS ! ";
$message = "Dear $username, as requested , here are your login details. ";
$message .= " Username = $username Password = $password";
$headers = 'From:noreply#bfs.com';
$sentmail = mail($to,$subject,$message,$headers);
?>
Edit ****
full code
<?php
error_reporting(0);
$email=$_POST['email'];
echo $result['price'];
if($_POST['submit']=='Send')
{
mysql_connect('localhost','root','root') or die(mysql_error);
mysql_select_db('users');
$query="select * from user where email='$email'";
$result=mysql_query($query) or die(error);
if(mysql_num_rows($result))
{
echo "User exists";
$username = mysql_query("select * from user where username = '$username'");
$result = mysql_fetch_assoc($username);
$to = $email;
$subject = "Registered details with BFS ! ";
$message = "Dear $result, as requested , here are your login details. ";
$message .= " Username = $username Password = $password";
$headers = 'From:noreply#bfs.com';
$sentmail = mail($to,$subject,$message,$headers);
}
else
{
echo "No user exist with this email id";
}
}
?>
Change this:
$username = mysql_query("select * from user where username = '$username'");
Into this:
$res = mysql_fetch_assoc( $result );
$res = $res['username'];
$username = mysql_query( "select * from user where username = '$res'" );
and this:
$result = mysql_fetch_assoc($username);
into this:
$result = mysql_fetch_assoc($username);
$username = $result['username'];
$password = $result['password'];
$result = $result['username'];
If it doesn't work I must've missed something :-) But if it does, use it to understand more about how the logic works, and after that read about PDO and use it instead. :-)

Registration module in php error when uploaded on server

I am using registration module in which i first collect data from user and store it to a temporary database('tmp_users') and send a link via email,on clicking link via email user can activate their account(i am moving data to permanent table 'users').i have following files
studentregistration.php(A UI for registration)
processlogin.js (processing form data via jquery)
register.php (script for moving user data to 'tmp_users' and sending them link)
confirm.php(making user permanent,moving 'tmp_users' data to 'users')
in register.php i am seting two session variable $_session['email'],$_session['confirmation'] and i am generating one random unique num via
uniqid(rand()) and sending this in email as passkey which i again use in confirm.php and getting it from url by $_GET['passkey'] if passkey matched than confirming registration otherwise not.
now the problem is that this script executed successfully on my local machine but does not executed on my server.
thank in advance.......
Code for confirm.php
<?php
error_reporting(0);
require 'db/connect.php';
if(session_start())
{
$confirmation = $_GET['passkey'];
$result=$db->query("select * from tmp_users where passkey = '$confirmation'");
$count = $result->num_rows;
if($count == 1)
{
$rows = $result->fetch_all(MYSQLI_ASSOC);
/*print_r($rows);*/
foreach($rows as $row)
{
$eno = $row['eno'];
$fname = $row['fname'];
$lname = $row['lname'];
$sem = $row['sem'];
$branch = $row['branch'];
$mail = $row['mail'];
$contact = $row['contact'];
$password =$row['password'];
}
//making user permenant
$insert=$db->prepare("insert into users(eno,fname,lname,sem,branch,mail,contact,password) values(?,?,?,?,?,?,?,?)");
$insert->bind_param('ississss',$eno,$fname,$lname,$sem,$branch,$mail,$contact,$password);
$insert->execute();
$rowsaffected = $insert->affected_rows;
if($rowsaffected==1){
if($delete=$db->query("delete from tmp_users where passkey='$confirmation'"))
echo"<script>alert('Activated!!! Login Now');document.location='studentlogin.php';</script>";
else
echo "error";
}else{
echo"<script>alert('Error activating account');document.location='index.php';</script>";
}
}else{
echo"<script>alert('You are not registered');document.location='studentregistration.php';</script>";
}
}else
{
header('location:index.php');
}
?>
code for register.php
<?php
session_start();
require '../db/connect.php';
require '../phpmailer/class.phpmailer.php';
require '../mailfunction.php';
$confirmation = md5(uniqid(rand()));
$eno = $_POST['eno'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sem = $_POST['sem'];
$branch= $_POST['branch'];
$mail = $_POST['mail'];
$contact = $_POST['contact'];
$pw = $_POST['pw'];
$password = md5($pw);
$query = ("insert into tmp_users(passkey,eno,fname,lname,sem,branch,mail,contact,password) values (?,?,?,?,?,?,?,?,?);");
$result = $db->prepare($query);
$result->bind_param('sississss',$confirmation,$eno,$fname,$lname,$sem,$branch,$mail,$contact,$password);
if($result->execute()){
$_SESSION['mail']= $mail;
$_SESSION['confirmation'] = $confirmation;
$ToEmail = $mail;
$subject = "Activate your account";
$header = 'FROM:VGECG-LIBRARY <noreply#vgecg.ac.in>';
$MessageHTML = "Click link below to activate your account \r\n";
$MessageHTML.="<a href='localhost/projectlibrary/confirm.php?passkey=$confirmation'>Click here</a>";
$MessageTEXT='';
if(SendMail($ToEmail, $MessageHTML, $MessageTEXT))
{
print "1";
}
else {
print "";
}
}
?>

Categories