I have a user system with user registration and user login. on the login page there is a password reset button and on the password rest button the following codes are there but nothing happens when I try to send a password rest link.
CONTROLLER:
function resetPasswordUser()
{
$status = '';
$this->load->library('form_validation');
$this->form_validation->set_rules('login_email','Email','trim|required|valid_email|xss_clean');
if($this->form_validation->run() == FALSE)
{
$this->forgotPassword();
}
else
{
$email = $this->input->post('login_email');
if($this->user_model->checkEmailExist($email))
{
$encoded_email = urlencode($email);
$this->load->helper('string');
$data['email'] = $email;
$data['activation_id'] = random_string('alnum',15);
$data['createdDtm'] = date('Y-m-d H:i:s');
$data['agent'] = getBrowserAgent();
$data['client_ip'] = $this->input->ip_address();
$save = $this->user_model->resetPasswordUser($data);
if($save)
{
$data1['reset_link'] = base_url() . "resetPasswordConfirmUser/" . $data['activation_id'] . "/" . $encoded_email;
$userInfo = $this->user_model->getCustomerInfoByEmail($email);
if(!empty($userInfo)){
$data1["username"] = $userInfo[0]->username;
$data1["email"] = $userInfo[0]->email;
$data1["message"] = "Reset Your Password";
}
$sendStatus = resetPasswordEmail($data1);
if($sendStatus){
$status = "send";
setFlashData($status, "Reset password link sent successfully, please check mails.");
} else {
$status = "notsend";
setFlashData($status, "Email has failed, try again.");
}
}
else
{
$status = 'unable';
setFlashData($status, "It seems an error while sending your details, try again.");
}
}
else
{
$status = 'invalid';
setFlashData($status, "This email is not registered with us.");
}
redirect('users/forgotPassword');
}
}
// This function used to reset the password
function resetPasswordConfirmUser($activation_id, $email)
{
// Get email and activation code from URL values at index 3-4
$email = urldecode($email);
// Check activation id in database
$is_correct = $this->user_model->checkActivationDetails($email, $activation_id);
$data['email'] = $email;
$data['activation_code'] = $activation_id;
if ($is_correct == 1)
{
$this->load->view('templates/header');
$this->load->view('newPassword', $data);
$this->load->view('templates/footer');
}
else
{
redirect('users/login');
}
}
// This function used to create new password
function createPasswordUser()
{
$status = '';
$message = '';
$email = $this->input->post("email");
$activation_id = $this->input->post("activation_code");
$this->load->library('form_validation');
$this->form_validation->set_rules('password','Password','required|max_length[20]');
$this->form_validation->set_rules('cpassword','Confirm Password','trim|required|matches[password]|max_length[20]');
if($this->form_validation->run() == FALSE)
{
$this->resetPasswordConfirmUser($activation_id, urlencode($email));
}
else
{
$password = $this->input->post('password');
$cpassword = $this->input->post('cpassword');
// Check activation id in database
$is_correct = $this->user_model->checkActivationDetails($email, $activation_id);
if($is_correct == 1)
{
$this->user_model->createPasswordUser($email, $password);
$status = 'success';
$message = 'Password changed successfully';
}
else
{
$status = 'error';
$message = 'Password changed failed';
}
setFlashData($status, $message);
redirect("users/login");
}
}
MODEL:
function checkEmailExist($email)
{
$this->db->select('id');
$this->db->where('email', $email);
$this->db->where('isDeleted', 0);
$query = $this->db->get('users');
if ($query->num_rows() > 0){
return true;
} else {
return false;
}
}
/**
* This function used to insert reset password data
* #param {array} $data : This is reset password data
* #return {boolean} $result : TRUE/FALSE
*/
function resetPasswordUser($data)
{
$result = $this->db->insert('reset_password', $data);
if($result) {
return TRUE;
} else {
return FALSE;
}
}
/**
* This function is used to get customer information by email-id for forget password email
* #param string $email : Email id of customer
* #return object $result : Information of customer
*/
function getCustomerInfoByEmail($email)
{
$this->db->select('id, email, username');
$this->db->from('users');
$this->db->where('isDeleted', 0);
$this->db->where('email', $email);
$query = $this->db->get();
return $query->result();
}
/**
* This function used to check correct activation deatails for forget password.
* #param string $email : Email id of user
* #param string $activation_id : This is activation string
*/
function checkActivationDetails($email, $activation_id)
{
$this->db->select('id');
$this->db->from('reset_password');
$this->db->where('email', $email);
$this->db->where('activation_id', $activation_id);
$query = $this->db->get();
return $query->num_rows;
}
// This function used to create new password by reset link
function createPasswordUser($email, $password)
{
$this->db->where('email', $email);
$this->db->where('isDeleted', 0);
$this->db->update('users', array('password'=>getHashedPassword($password)));
$this->db->delete('reset_password', array('email'=>$email));
}
VIEW:
<div class="row">
<div class="col-md-12">
<?php echo validation_errors('<div class="alert alert-danger alert-dismissable">', ' <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button></div>'); ?>
</div>
</div>
<?php
$this->load->helper('form');
$error = $this->session->flashdata('error');
$send = $this->session->flashdata('send');
$notsend = $this->session->flashdata('notsend');
$unable = $this->session->flashdata('unable');
$invalid = $this->session->flashdata('invalid');
if($error)
{
?>
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $this->session->flashdata('error'); ?>
</div>
<?php }
if($send)
{
?>
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $send; ?>
</div>
<?php }
if($notsend)
{
?>
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $notsend; ?>
</div>
<?php }
if($unable)
{
?>
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $unable; ?>
</div>
<?php }
if($invalid)
{
?>
<div class="alert alert-warning alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $invalid; ?>
</div>
<?php } ?>
<form action="<?php echo base_url(); ?>users/resetPasswordUser" method="post">
<div class="form-group has-feedback">
<input type="email" class="form-control" placeholder="Email" name="login_email" required />
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
</div><!-- /.col -->
<div class="col-xs-4">
<input type="submit" class="btn btn-primary btn-block btn-flat" value="Submit" />
</div><!-- /.col -->
</div>
</form>
Login<br>
</div><!-- /.login-box-body -->
</div><!-- /.login-box -->
CONSTANT:
define('EMAIL_FROM', 'xxxx#gmail.com'); // e.g. email#example.com
define('EMAIL_BCC', 'xxxx#gmail.com'); // e.g. email#example.com
define('FROM_NAME', 'CTL '); // Your system name
define('EMAIL_PASS', 'Your email password'); // Your email password
define('PROTOCOL', 'smtp'); // mail, sendmail, smtp
define('SMTP_HOST', 'smtp.gmail.com'); // your smtp host e.g. smtp.gmail.com
define('SMTP_PORT', '25'); // your smtp port e.g. 25, 587
define('SMTP_USER', 'Your smtp user'); // your smtp user
define('SMTP_PASS', 'Your smtp password'); // your smtp password
define('MAIL_PATH', '/usr/sbin/sendmail');
QUESTION UPDATE
I changed my view to load out my errors and what I get is "Email has failed, try again." Error for mail not sent. Thanks
From your comments, it looks like you are using a localhost server. Localhost servers cannot send emails out IIRC. To test sending emails, you have to have a server that has access to the real world (and the feature has to be enabled on that server).
Related
I'm trying to log a user in but I get an error every time I try to verify the password. The username is verified just fine. My password is stored by password_hash in the database. For example, let's say I signup a username 'thisIsAUser' and the password is 'thisIsAUsersPassword'. The hash would be something like: $2y$10$VR5FKZVLP6/43adb1PsGD.bsmrzp15jdftotz6xubDQtypZ1rKEFW. The error would be the else statement of the if(password_verify). Notice that the else statement of the username not matching has a '.' at the end while the password not matching has a '!'.
Logging in script:
<?php
session_start();
$link = mysqli_connect("localhost", "root", "Yuvraj123", "KingOfQuiz");
if(mysqli_connect_error()) {
die("Couldn't connect to the database. try again later.");
}
$query = "SELECT * FROM `users`";
if($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_array($result);
}
// define variables and set to empty values
$loginSignupButton = "";
$loginUsername = "";
$loginPassword = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$loginUsername = form_input($_POST["loginUsername"]);
$loginPassword = form_input($_POST["loginPassword"]);
$loginSignupButton = form_input($_POST["loginSignupButton"]);
}
function form_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$loginUsernameError = "";
$loginPasswordError = "";
$error = "";
$loggingInUsername = "";
$unhashedPasswordThingyMajig = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["loginUsername"])) {
$loginUsernameError = "<p style='color: red'>Username is required</p>";
echo $loginUsernameError;
} else {
$loginUsername = form_input($_POST["loginUsername"]);
}
if (empty($_POST["loginPassword"])) {
$loginPasswordError = "<p style='color: red'>Password is required</p>";
echo $loginPasswordError;
} else {
$loginPassword = form_input($_POST["loginPassword"]);
}
if($_POST['loginActive'] == "0") {
$query = "SELECT * FROM users WHERE username = '". mysqli_real_escape_string($link, $_POST['loginUsername'])."' LIMIT 1";
$result = mysqli_query($link, $query);
if(mysqli_num_rows($result) > 0) {
$error = "<p style='color: red'>That username is already taken.</p>";
echo $error;
} else {
header ('location: signup.php');
}
} elseif($_POST['loginActive'] == "1") {
$sql = "
SELECT *
FROM users
WHERE username = ?
";
$query = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($query, "s", $_POST["loginUsername"]);
mysqli_stmt_execute($query);
$result = mysqli_stmt_get_result($query);
if (mysqli_num_rows($result)) {
$logInPassword = $_POST['loginPassword'];
if(password_verify($logInPassword, $row['password'])) {
echo "Hello World!";
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid!</p>";
echo $error;
}
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid.</p>";
echo $error;
}
}
}
?>
Form(This is the logging in one, not the signup):
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" id="LoginModalTitle">
<h5 class="modal-title" id="exampleModalLabel LoginModalTitle">Login</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" style="color: white">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="modal-details">
<div class="form-group">
<input type="hidden" id="loginActive" name="loginActive" value="1">
<label for="loginUsername">Username</label>
<input type="text" class="form-control formInput" id="inputUsername" placeholder="Eg: RealKingOfQuiz" name="loginUsername" autocomplete="off" required>
<p><span class="error"><?php echo $loginUsernameError;?></span><p>
</div>
<div class="form-group">
<label for="loginPassword">Password</label>
<input type="password" class="form-control formInput" id="inputPassword" name="loginPassword" required autocomplete="on">
<small>Forgot Password?</small>
<p><span class="error"><?php echo $loginPasswordError;?></span></p>
</div>
<p><span class="error"><?php echo $error;?></span></p>
<div class="alert alert-danger" id="loginAlert"></div>
</form>
</div>
<div class="modal-footer">
<a id="toggleLogin">Sign Up?</a>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button class="btn btn-success" id="LoginSignUpButton" name="loginSignupButton" form="modal-details" disabled>Login</button>
</div>
</div>
</div>
</div>
If you update the section of code from...
$result = mysqli_stmt_get_result($query);
...to the end of the code block with the below; then it should work.
The problem is that you're reading the password from the wrong result set.
$result = mysqli_stmt_get_result($query);
$dbPassword = mysqli_fetch_assoc($result)["password"] ?? null;
if ($dbPassword) {
$logInPassword = $_POST['loginPassword'];
if(password_verify($logInPassword, $dbPassword)) {
echo "Hello World!";
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid!</p>";
echo $error;
}
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid.</p>";
echo $error;
}
You never fetched the row for the user logging in. When you check $row['password'] it's checking the first password in the table, which came from the SELECT * FROM users query at the beginning of the script.
You need to call mysqli_fetch_assoc() after querying for the row for the user.
if (mysqli_num_rows($result)) {
$logInPassword = $_POST['loginPassword'];
$row = mysqli_fetch_assoc($result);
if(password_verify($logInPassword, $row['password'])) {
echo "Hello World!";
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid!</p>";
echo $error;
}
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid.</p>";
echo $error;
}
I use native php session to secure site/assets/kcfinder/browse.php on kcfinder...
because kcfinder can't read sessions from the codeigniter that I made....
can anyone help me, please ...
=> My Form
<form method="POST" action="<?= base_url('Authentication/login'); ?>">
<div class="form-group row">
<label for="staticEmail" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" name="email" id="staticEmail" placeholder="email#example.com">
</div>
</div>
<div class="form-group row">
<label for="inputPassword" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" name="password" id="inputPassword" placeholder="******">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Login</button>
</div>
</form>
=> Authentication.php (Controller)
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Authentication extends CI_Controller
{
function __construct()
{
parent::__construct();
// load libary native session
$this->load->library('Nativesession', 'nativesession');
}
function index()
{
// $this->load->view('login_view');
}
public function login()
{
$this->form_validation->set_rules(
'email',
'Email',
'required|trim|valid_email|xss_clean',
['required' => 'Email Harus Di isi', 'valid_email' => 'Harus email yang valid']
);
$this->form_validation->set_rules(
'password',
'Password',
'trim|required|xss_clean',
['required' => 'Password Harus Di isi']
);
if ($this->form_validation->run() == false) {
$data['judul'] = 'Selamat Datang';
$this->session->set_flashdata(
'pesan',
'<div class="alert alert-warning fixed alert-dismissible fade show fixed" role="alert">
authentication Failed !
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>'
);
$this->load->view('Home/Template/header', $data);
$this->load->view('Home/index', $data);
$this->load->view('Home/Template/footer');
} else {
//Jiko Lolos Validasi buat private function
$this->_login();
}
}
private function _login()
{
$email = $this->input->post('email', TRUE);
$password = $this->input->post('password', TRUE);
//perintah select dari tabel user where email = email inputan
$user = $this->db->get_where('user', ['email' => $email])->row_array();
// var_dump($user);
// die;
if ($email == $user['email']) {
// set native session jika username benar
if (password_verify($password, $user['password'])) {
$this->nativesession->set('status', 'loggedin');
var_dump($this->nativesession->set('status', 'loggedin'));
die;
} else {
$this->session->set_flashdata(
'pesan',
'<div class="alert alert-danger fixed alert-dismissible fade show fixed" role="alert">
Wrong Password !
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>'
);
redirect(base_url());
}
// redirect ke halaman blog
// redirect('blog');
} else {
$this->session->set_flashdata(
'pesan',
'<div class="alert alert-info fixed alert-dismissible fade show fixed" role="alert">
Account Not Found !
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>'
);
// redirect ke login jika username salah
redirect(base_url());
}
}
function logout()
{
$this->nativesession->delete('status');
redirect(base_url());
}
}
=> Nativesession.php (Libraries)
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Nativesession
{
public function __construct()
{
session_start();
}
// function untuk meng-set session
public function set($key, $value)
{
$_SESSION[$key] = $value;
}
// function untuk memanggil session
public function get($key)
{
return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
}
// function untuk menghapus session
public function delete($key)
{
unset($_SESSION[$key]);
}
}
I called the session at /assets/kcfinder/config.php
if(isset($_SESSION['status']) == 'loggedin'){
$status = false;
}else{
$status = true;
}
Session Doesn't work if return the success message. If I directly echo this message Session work perfectly. But when I return this it not work. I need to destroy my session after return my message. I have updated my User.php class & forgotpass.php page
User.php
<?php
$filepath = realpath(dirname(__FILE__));
include_once ($filepath.'/../lib/Session.php');
include_once ($filepath.'/../lib/Database.php');
include_once ($filepath.'/../helpers/Formate.php');
?>
<?php
/
class User{
private $db;
private $fm;
public function __construct(){
$this->db = new Database();
$this->fm = new Formate();
}
*Password Change Method*/
public function updatePass($userId, $data){
$oldpass = $this->fm->validation($data['oldpass']);
$newpass = $this->fm->validation($data['newpass']);
$conpass = $this->fm->validation($data['conpass']);
$oldpass = mysqli_real_escape_string($this->db->link,$oldpass);
$newpass = mysqli_real_escape_string($this->db->link,$newpass);
$conpass = mysqli_real_escape_string($this->db->link,$conpass);
if (empty($oldpass) || empty($newpass) || empty($conpass)) {
$errormsg = "<div class='alert alert-danger alert-dismissible'>
<button type='button' class='close' data-dismiss='alert' aria-
label='Close'><span aria-hidden='true'>×</span></button>
<strong>Error!</strong> Filed must not be empty.
</div>";
return $errormsg;
}else {
$oldpass = md5($oldpass);
$newpass = md5($newpass);
$conpass = md5($conpass);
$passquery = "SELECT password FROM tbl_user WHERE password = '$oldpass'
AND userId = '$userId' ";
$passcheck = $this->db->select($passquery);
if ($passcheck == false) {
$errormsg = "<div class='alert alert-danger alert-dismissible'>
<button type='button' class='close' data-dismiss='alert'
aria-label='Close'><span aria-hidden='true'>×</span>
</button><strong>Error!</strong> The Password doesn't
exist.</div>";
return $errormsg;
}else {
if ($newpass == $conpass ) {
$query = "UPDATE tbl_user
SET
password = '$newpass'
WHERE userId = '$userId'";
$updatepass = $this->db->update($query);
if ($updatepass) {
$successmsg ="<div class='alert alert-success alert-dismissible'>
<button type='button' class='close' data-
dismiss='alert' aria-label='Close'><span aria-
hidden='true'>×</span></button>
<strong>Success!</strong> Password Changed
Successfully.
</div>";
return $successmsg;
Session::destroy();
echo '<script type="text/javascript">setTimeout(function()
{window.top.location="index.php"} , 5000);</script>';
exit();
}else {
$errormsg = "<div class='alert alert-danger alert
dismissible'><button type='button'
class='close' data-dismiss='alert' aria-
label='Close'><span aria-hidden='true'>×
</span></button> <strong>Error!</strong>
Somthing went wrong.</div>";
return $errormsg;
}
}else {
$errormsg = "<div class='alert alert-danger
alert-dismissible'><button type='button'
class='close'data-dismiss='alert' aria-
label='Close'><span aria-hidden='true'>×
</span></button><strong>Error!</strong>
Password does not match.
</div>";
return $errormsg;
}
}
}
}/*End Method*/
Forgotpass.php
<?php include 'inc/header.php'; ?>
<?php $userId = Session::get("userId"); ?>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' &&
isset($_POST['submitpass'])) {
$updatePass = $user->updatePass($userId,$_POST);
}
?>
<!-- Return message will be show here -->
<?php if (isset($updatePass)) {echo $updatePass;} ?>
<div id="tab3" class="tab-pane fade">
<form class="form-horizontal" action="" method="post">
<div class="form-group">
<label class="col-sm-3 control-label">Old Password</label>
<div class="col-sm-5">
<input style="margin-bottom: 0px;" type="password"
name="oldpass" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">New Password</label>
<div class="col-sm-5">
<input style="margin-bottom: 0px;" type="password"
name="newpass" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Confirm Password</label>
<div class="col-sm-5">
<input style="margin-bottom: 0px;" type="password"
name="conpass" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-5">
<button type="submit" name="submitpass" class="btn btn-sm btn-
primary">
Update Password
</button>
</div>
</div>
</form>
</div>
Session.php
<?php
class Session{
public static function init(){
session_start();
}
public static function destroy(){
session_destroy();
session_unset();
}
}
?>
When you return, you're basically saying you're done with the current function, "return this value". Nothing afterwards will be executed. Simply move the statement before the return:
if ($updatepass) {
$successmsg ="<div class='alert alert-success alert-dismissible'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>×</span></button><strong>Success!</strong> Password Changed Successfully.</div>";
Session::passdestroy();
return $successmsg;
What I am trying to accomplish is if the user verified column is 0 it will echo out the message below if the users verified column is 1 it wont show the message.
so I have it working but if they close it I don't want it to show again for that session.
$db = dbconnect();
$stmt = $db->prepare("SELECT * FROM users WHERE ID = ?");
$stmt->bind_param('s', $_SESSION['ID']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['ID'];
$verified = $row['Verified'];
if ($verified == 0) {
echo '
<div class="alert alert-warning alert-dismissible fade show" role="alert">
Your account has not been verified.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>';
return true;
} else {
return false;
}
}
You should set a session variable to show the alert based off of the value retrieved from the database, like so :
PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['verifymsg']) {
$_SESSION['VerifyMessage'] = false;
}
}
$db = dbconnect();
$stmt = $db->prepare("SELECT * FROM users WHERE ID = ?");
$stmt->bind_param('s', $_SESSION['ID']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['ID'];
if (!isset($_SESSION['VerifyMessage']) {
$_SESSION['VerifyMessage'] = ($row['Verified'] == 0) ? true : false;
}
if ($_SESSION['VerifyMessage']) {
echo '
<form method="POST" action="yourscript.php">
<input type="hidden" name="verifymsg" />
<div class="alert alert-warning alert-dismissible fade show" role="alert">
Your account has not been verified.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</form>';
return true;
} else {
return false;
}
}
Here, I used a ternary operation to set a session variable called 'VerifyMessage' if it isn't already set. I also added a <form> and hidden input with the name verifymsg to the html.
When this script sees verifymsg as a post variable, it will set the session variable to false. This can work anyway you want, for example with ajax, but it shows a concept.
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
I am trying to make a registration where website sends a confirmation email and users enter this email and continue registering. However, it doesn't send anything to email. Where am I wrong?
Here is my controller.php:
<?php
class user extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url', 'security'));
$this->load->library(array('session', 'form_validation', 'email'));
$this->load->database();
$this->load->model('User_model');
}
function index()
{
$this->register();
}
function register()
{
//set validation rules
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha|min_length[3]|max_length[30]|is_unique[instructors.instructors_slug]xss_clean');
$this->form_validation->set_rules('mail', 'Email', 'trim|required|valid_email|is_unique[instructors.mail]');
$this->form_validation->set_rules('password', 'password', 'trim|required|md5');
$this->form_validation->set_rules('password2', 'Confirm Password', 'trim|required|md5|matches[password]');
$data['courses'] = $this->Popular_courses_model->get_popular_courses();
$data['news'] = $this->News_model->get_news();
//validate form input
if ($this->form_validation->run() == FALSE)
{
// fails
$this->load->view('templates/header');
$this->load->view('pages/index', $data);
$this->load->view('templates/footer');
}
else
{
//insert the user registration details into database
$data = array(
'instructors_slug' => $this->input->post('username'),
'mail' => $this->input->post('mail'),
'password' => $this->input->post('password')
);
// insert form data into database
if ($this->User_model->insertUser($data))
{
// send email
if ($this->User_model->sendEmail($this->input->post('mail')))
{
// successfully sent mail
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">You are Successfully Registered! Please confirm the mail sent to your Email-ID!!!</div>');
redirect('user/register');
}
else
{
// error
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('user/register');
}
}
else
{
// error
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('user/register');
}
}
}
function verify($hash=NULL)
{
if ($this->User_model->verifyEmailID($hash))
{
$this->session->set_flashdata('verify_msg','<div class="alert alert-success text-center">Your Email Address is successfully verified! Please login to access your account!</div>');
redirect('user/register');
}
else
{
$this->session->set_flashdata('verify_msg','<div class="alert alert-danger text-center">Sorry! There is error verifying your Email Address!</div>');
redirect('user/register');
}
}
}
?>
Here is my model:
<?php
class user_model extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
//insert into user table
function insertUser($data)
{
return $this->db->insert('instructors', $data);
}
//send verification email to user's email id
function sendEmail($to_email)
{
$from_email = 'support#wtf.az'; //change this to yours
$subject = 'Verify Your Email Address';
$message = 'Dear User,<br /><br />Please click on the below activation link to verify your email address.<br /><br /> http://wtf.az/user/verify/' . md5($to_email) . '<br /><br /><br />Thanks<br />Mydomain Team';
//configure email settings
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'cpanel.freehosting.com'; //smtp host name
$config['smtp_port'] = '465'; //smtp port number
$config['smtp_user'] = $from_email;
$config['smtp_pass'] = '*my password here*'; //$from_email password
$config['mailtype'] = 'html';
$config['charset'] = 'iso-8859-1';
$config['wordwrap'] = TRUE;
$config['newline'] = "\r\n"; //use double quotes
$this->email->initialize($config);
//send mail
$this->email->from($from_email, 'WTF');
$this->email->to($to_email);
$this->email->subject($subject);
$this->email->message($message);
return $this->email->send();
}
//activate user account
function verifyEmailID($key)
{
$data = array('status' => 1);
$this->db->where('md5(mail)', $key);
return $this->db->update('instructors', $data);
}
}
?>
Here is my view:
<div class="modal-body">
<div>
<?php echo $this->session->flashdata('msg'); ?>
</div>
<?php $attributes = array('class' => 'rex-forms', 'name' => 'registrationform'); ?>
<?= form_open_multipart('user/register', $attributes); ?>
<div class="form-group">
<span class="text-danger"><?php echo form_error('username'); ?></span>
<input name="username" type="text" class="form-control" placeholder="Имя пользователя">
</div>
<div class="form-group">
<span class="text-danger"><?php echo form_error('mail'); ?></span>
<input name="mail" type="email" class="form-control" placeholder="Электронный адрес">
</div>
<div class="form-group">
<span class="text-danger"><?php echo form_error('password'); ?></span>
<input name="password" type="password" class="form-control" placeholder="Пароль">
</div>
<div class="form-group">
<input name="password2" type="password" class="form-control" placeholder="Повторный ввод пароля">
</div>
</div>
<div class="modal-footer">
<button type="submit" name="submitforreg" class="rex-bottom-medium rex-btn-icon">
<span class="rex-btn-text">регистрация</span>
<span class="rex-btn-text-icon"><i class="fa fa-arrow-circle-o-right"></i></span>
</button>
</div>
</form>
</div>
Not sure if this is the issue, but as per the documentation, the model class name must start with a capital letter.
In your model, try changing this:
class user_model extends CI_Model
to this:
class User_model extends CI_Model