Q:

sending token to email in codeigniter

I'm working on a small application that can provide registering an account and sending token to complete registration to email.
I have everything working except sending emails with which I can't handle and I'm not sure how to do this. I'd really appreciat any help and explanations on how can I actually send an email instead of just displaying token in view.
There are 2 functions in which I want to send token via mail: register and forgot.
This is my Controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Main extends CI_Controller {

        public $status; 
        public $roles;

        function __construct(){
            parent::__construct();
            $this->load->model('User_model', 'user_model', TRUE);
            $this->load->library('form_validation');    
            $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
            $this->status = $this->config->item('status'); 
            $this->roles = $this->config->item('roles');
        }      

    public function index()
    {   
            if(empty($this->session->userdata['email'])){
                redirect(site_url().'/main/login/');
            }            
            /*front page*/
            $data = $this->session->userdata(); 
            $this->load->view('header');            
            $this->load->view('index', $data);
            $this->load->view('footer');
    }

    public function ankieta()
    {
            $data = $this->session->userdata(); 
            $this->load->view('ankieta/header');            
            $this->load->view('ankieta/ankieta', $data);
            $this->load->view('ankieta/footer');
    }

        public function register()
        {

        $config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'ssl://smtp.gmail.com',
        'smtp_port' => 465,
        'smtp_user' => 'mymail@gmail.com',
        'smtp_pass' => 'pass',
        'mailtype'  => 'html', 
        'charset'   => 'utf-8'
        );
        $this->load->library('email', $config);
        $this->email->set_newline("\r\n");

            $this->form_validation->set_rules('firstname', 'Imię', 'required');
            $this->form_validation->set_rules('lastname', 'Nazwisko', 'required');    
            $this->form_validation->set_rules('email', 'Email', 'required|valid_email');    

            if ($this->form_validation->run() == FALSE) {   
                $this->load->view('header');
                $this->load->view('register');
                $this->load->view('footer');
            }else{                
                if($this->user_model->isDuplicate($this->input->post('email'))){
                    $this->session->set_flashdata('flash_message', 'Podany adres email już istnieje');
                    redirect(site_url().'/main/login');
                }else{

                    $clean = $this->security->xss_clean($this->input->post(NULL, TRUE));
                    $id = $this->user_model->insertUser($clean); 
                    $token = $this->user_model->insertToken($id);                                        

                    $qstring = base64_encode($token);                    
                    $url = site_url() . '/main/complete/token/' . $qstring;
                    $link = '<a href="' . $url . '">' . $url . '</a>'; 

                    $message = '';                     
                    $message .= '<strong>Dziekujemy za dokonanie rejestracji.</strong><br>';
                    $message .= '<strong>Aby dokończyć rejestrację przejdź na podany adres:</strong> ' . $link;                          

                    $to = $email;
                    $this->email->clear();
                    $this->email->from('whatever@c.com');
                    $this->email->to($to);
                    $this->email->subject('Thanks for registering');
                    $this->email->message($message);
                    if($this->email->send() === TRUE){ 
                 $this->session->set_flashdata('flash_message', 'Password reset done.');
                redirect(site_url().'/main/login');
             }else{
                 $this->session->set_flashdata('flash_message', 'Password reset fail.');
                redirect(site_url().'/main/forgot');
            }

                };              
            }
        }

        protected function _islocal(){
            return strpos($_SERVER['HTTP_HOST'], 'local');
        }

        public function complete()
        {                                   
            $token = base64_decode($this->uri->segment(4));       
            $cleanToken = $this->security->xss_clean($token);

            $user_info = $this->user_model->isTokenValid($cleanToken); //either false or array();           

            if(!$user_info){
                $this->session->set_flashdata('flash_message', 'Token jest nieprawidłowy lub wygasł');
                redirect(site_url().'/main/login');
            }            
            $data = array(
                'firstName'=> $user_info->first_name,
                'lastName'=> $user_info->last_name, 
                'email'=>$user_info->email, 
                'user_id'=>$user_info->id, 
                'token'=>base64_encode($token)
            );

            $this->form_validation->set_rules('password', 'Hasło', 'required|min_length[5]');
            $this->form_validation->set_rules('passconf', 'Potwierdź hasło', 'required|matches[password]');              

            if ($this->form_validation->run() == FALSE) {   
                $this->load->view('header');
                $this->load->view('complete', $data);
                $this->load->view('footer');
            }else{

                $this->load->library('password');                 
                $post = $this->input->post(NULL, TRUE);

                $cleanPost = $this->security->xss_clean($post);

                $hashed = $this->password->create_hash($cleanPost['password']);                
                $cleanPost['password'] = $hashed;
                unset($cleanPost['passconf']);
                $userInfo = $this->user_model->updateUserInfo($cleanPost);

                if(!$userInfo){
                    $this->session->set_flashdata('flash_message', 'Wystąpił problem ze zmianąTwoich danych');
                    redirect(site_url().'/main/login');
                }

                unset($userInfo->password);

                foreach($userInfo as $key=>$val){
                    $this->session->set_userdata($key, $val);
                }
                redirect(site_url().'/main/index');

            }
        }

        public function login()
        {
            $this->form_validation->set_rules('email', 'Email', 'required|valid_email');    
            $this->form_validation->set_rules('password', 'Hasło', 'required'); 

            if($this->form_validation->run() == FALSE) {
                $this->load->view('header');
                $this->load->view('login');
                $this->load->view('footer');
            }else{

                $post = $this->input->post();  
                $clean = $this->security->xss_clean($post);

                $userInfo = $this->user_model->checkLogin($clean);

                if(!$userInfo){
                    $this->session->set_flashdata('flash_message', 'Logowanie nie powiodło się');
                    redirect(site_url().'/main/login');
                }                
                foreach($userInfo as $key=>$val){
                    $this->session->set_userdata($key, $val);
                }
                redirect(site_url().'/main/index');
            }

        }

        public function logout()
        {
            $this->session->sess_destroy();
            redirect(site_url().'/main/login/');
        }

        public function forgot()
        {

            $this->form_validation->set_rules('email', 'Email', 'required|valid_email'); 

            if($this->form_validation->run() == FALSE) {
                $this->load->view('header');
                $this->load->view('forgot');
                $this->load->view('footer');
            }else{
                $email = $this->input->post('email');  
                $clean = $this->security->xss_clean($email);
                $userInfo = $this->user_model->getUserInfoByEmail($clean);

                if(!$userInfo){
                    $this->session->set_flashdata('flash_message', 'Adres email nie istnieje');
                    redirect(site_url().'/main/login');
                }   

                if($userInfo->status != $this->status[1]){ //if status is not approved
                    $this->session->set_flashdata('flash_message', 'Twoje konto nie zostało aktywowane');
                    redirect(site_url().'/main/login');
                }

                //build token 

                $token = $this->user_model->insertToken($userInfo->id);                    
                $qstring = base64_encode($token);                    
                $url = site_url() . '/main/reset_password/token/' . $qstring;
                $link = '<a href="' . $url . '">' . $url . '</a>'; 

                $message = '';                     
                $message .= '<strong>Zmiana hasła</strong><br>';
                $message .= '<strong>Aby dokonać zmiany hasła przejdź na podany adres:</strong> ' . $link;             

                echo $message;
                exit;

            }

        }

        public function reset_password()
        {
            $token = base64_decode($this->uri->segment(4));       
            $cleanToken = $this->security->xss_clean($token);

            $user_info = $this->user_model->isTokenValid($cleanToken); //either false or array();               

            if(!$user_info){
                $this->session->set_flashdata('flash_message', 'Token jest nieprawidłowy lub wygasł');
                redirect(site_url().'/main/login');
            }            
            $data = array(
                'firstName'=> $user_info->first_name, 
                'lastName'=> $user_info->last_name,
                'email'=>$user_info->email, 
                'user_id'=>$user_info->id, 
                'token'=>base64_encode($token)
            );

            $this->form_validation->set_rules('password', 'Hasło', 'required|min_length[5]');
            $this->form_validation->set_rules('passconf', 'Potwierdź hasło', 'required|matches[password]');              

            if ($this->form_validation->run() == FALSE) {   
                $this->load->view('header');
                $this->load->view('reset_password', $data);
                $this->load->view('footer');
            }else{

                $this->load->library('password');                 
                $post = $this->input->post(NULL, TRUE);                
                $cleanPost = $this->security->xss_clean($post);                
                $hashed = $this->password->create_hash($cleanPost['password']);                
                $cleanPost['password'] = $hashed;
                unset($cleanPost['passconf']);                
                if(!$this->user_model->updatePassword($cleanPost)){
                    $this->session->set_flashdata('flash_message', 'Wystąpił błąd przy próbie zmiany hasła');
                }else{
                    $this->session->set_flashdata('flash_message', 'Twoje hasło zostało zmienione. Możesz się zalogować');
                }
                redirect(site_url().'/main/login');                
            }
        }       

}

This is my model:
<?php
class User_model extends CI_Model {

    public $status; 
    public $roles;

    function __construct(){
        // Call the Model constructor
        parent::__construct();        
        $this->status = $this->config->item('status');
        $this->roles = $this->config->item('roles');
    }    

    public function insertUser($d)
    {  
            $string = array(
                'first_name'=>$d['firstname'],
                'last_name'=>$d['lastname'],
                'email'=>$d['email'],
                'role'=>$this->roles[0], 
                'status'=>$this->status[0]
            );
            $q = $this->db->insert_string('users',$string);             
            $this->db->query($q);
            return $this->db->insert_id();
    }

    public function isDuplicate($email)
    {     
        $this->db->get_where('users', array('email' => $email), 1);
        return $this->db->affected_rows() > 0 ? TRUE : FALSE;         
    }

    public function insertToken($user_id)
    {   
        $token = substr(sha1(rand()), 0, 30); 
        $date = date('Y-m-d');

        $string = array(
                'token'=> $token,
                'user_id'=>$user_id,
                'created'=>$date
            );
        $query = $this->db->insert_string('tokens',$string);
        $this->db->query($query);
        return $token;

    }

    public function isTokenValid($token)
    {
        $q = $this->db->get_where('tokens', array('token' => $token), 1);        
        if($this->db->affected_rows() > 0){
            $row = $q->row();             

            $created = $row->created;
            $createdTS = strtotime($created);
            $today = date('Y-m-d'); 
            $todayTS = strtotime($today);

            if($createdTS != $todayTS){
                return false;
            }

            $user_info = $this->getUserInfo($row->user_id);
            return $user_info;

        }else{
            return false;
        }

    }    

    public function getUserInfo($id)
    {
        $q = $this->db->get_where('users', array('id' => $id), 1);  
        if($this->db->affected_rows() > 0){
            $row = $q->row();
            return $row;
        }else{
            error_log('no user found getUserInfo('.$id.')');
            return false;
        }
    }

    public function updateUserInfo($post)
    {
        $data = array(
               'password' => $post['password'],
               'last_login' => date('Y-m-d h:i:s A'), 
               'status' => $this->status[1]
            );
        $this->db->where('id', $post['user_id']);
        $this->db->update('users', $data); 
        $success = $this->db->affected_rows(); 

        if(!$success){
            error_log('Unable to updateUserInfo('.$post['user_id'].')');
            return false;
        }

        $user_info = $this->getUserInfo($post['user_id']); 
        return $user_info; 
    }

    public function checkLogin($post)
    {
        $this->load->library('password');       
        $this->db->select('*');
        $this->db->where('email', $post['email']);
        $query = $this->db->get('users');
        $userInfo = $query->row();

        if(!$this->password->validate_password($post['password'], $userInfo->password)){
            error_log('Unsuccessful login attempt('.$post['email'].')');
            return false; 
        }

        $this->updateLoginTime($userInfo->id);

        unset($userInfo->password);
        return $userInfo; 
    }

    public function updateLoginTime($id)
    {
        $this->db->where('id', $id);
        $this->db->update('users', array('last_login' => date('Y-m-d h:i:s A')));
        return;
    }

    public function getUserInfoByEmail($email)
    {
        $q = $this->db->get_where('users', array('email' => $email), 1);  
        if($this->db->affected_rows() > 0){
            $row = $q->row();
            return $row;
        }else{
            error_log('no user found getUserInfo('.$email.')');
            return false;
        }
    }

    public function updatePassword($post)
    {   
        $this->db->where('id', $post['user_id']);
        $this->db->update('users', array('password' => $post['password'])); 
        $success = $this->db->affected_rows(); 

        if(!$success){
            error_log('Unable to updatePassword('.$post['user_id'].')');
            return false;
        }        
        return true;
    } 

}

I'm passing $message variable to see if token works. Also while people are registering they have to input their email address. So I want tokens to go directly to emails they input in register form.
Thank you for help.

A:

Configure your localhost mail settings as well

XAMPP
WAMP

Try This
$this->load->library('email');

    $config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'ssl://smtp.gmail.com',
        'smtp_port' => 465,
        'smtp_user' => 'mymail@gmail.com',
        'smtp_pass' => 'pass',
        'mailtype'  => 'html', 
        'charset'   => 'utf-8'
    );

$this->email->initialize($config);
$this->email->set_newline("\r\n");

$clean = $this->security->xss_clean($this->input->post(NULL, TRUE));
$id = $this->user_model->insertUser($clean); 
$token = $this->user_model->insertToken($id);                                        

$qstring = base64_encode($token);                    
$url = site_url() . '/main/complete/token/' . $qstring;
$link = '<a href="' . $url . '">Activation Link</a>'; 

$message = '';                     
$message .= '<strong>Dziekujemy za dokonanie rejestracji.</strong><br>';
$message .= '<strong>Aby dokończyć rejestrację przejdź na podany adres:</strong> '. $link;                        

$toEmail = $this->input->post('email');
$to = $toEmail; # undefine 
$this->email->clear();
$this->email->from('whatever@c.com');
$this->email->to($to);
$this->email->subject('Thanks for registering');
$this->email->message($message);

if(!$this->email->send())
{ 
    echo "fail <br>";
    echo $this->email->print_debugger();
    /*$this->session->set_flashdata('flash_message', 'Password reset fail.');
    redirect(site_url().'/main/register');*/
}
else
{       
     echo "Pass <br>";        
   /* $this->session->set_flashdata('flash_message', 'Password reset done.');
    redirect(site_url().'/main/login');*/
}

