Monday, 4 April 2016

How to set up email verification using PHP CodeIgniter

Database Structure: 
CREATE TABLE `users` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(20) NOT NULL,
`last_name` varchar(20) NOT NULL,
`password` varchar(20) NOT NULL,
`email` varchar(50) NOT NULL,
`is_verified` int(1) NOT NULL DEFAULT '0',
`hash` varchar(32) NOT NULL,
PRIMARY KEY (`userid`)
)
Controller: 


<?php
function insert_user() {
$this->data = array( //$data is a global variable
'first_name' => $_POST['fname'],
'last_name' => $_POST['lname'],
'email' => $_POST['email'],
'password' => md5($_POST['password']),
'hash' => md5(rand(0, 1000))
);
$this->user_registration_model->insert_record($this->data);
}
?>
<?php
function send_confirmation() {
$this->load->library('email'); //load email library
$this->email->from('admin@mysite.com', 'My Site'); //sender's email
$address = $_POST['email']; //receiver's email
$subject="Welcome to MySite!"; //subject
$message= /*-----------email body starts-----------*/
'Thanks for signing up, '.$_POST['fname'].'!
Your account has been created.
Here are your login details.
-------------------------------------------------
Email : ' . $_POST['email'] . '
Password: ' . $_POST['password'] . '
-------------------------------------------------
Please click this link to activate your account:
' . base_url() . 'index.php/user_registration/verify?' .
'email=' . $_POST['email'] . '&hash=' . $this->data['hash'] ;
/*-----------email body ends-----------*/
$this->email->to($address);
$this->email->subject($subject);
$this->email->message($message);
$this->email->send();
}
?>


<?php
function verify() {
$result = $this->user_registration_model->get_hash_value($_GET['email']);
if($result){
if($result['hash']==$_GET['hash']){
$this->user_registration_model->verify_user($_GET['email']);
}
}
}
?>
Model: 

<?php
function verify_user($email) {
$data = array('is_verified' => 1);
$this->db->where('email', $email);
$this->db->update('users', $data);
}
?>

No comments:

Post a Comment