CodeIgniter tutorials for beginners Hindi me part-4

Hello dosto kaise ho sb ? kaisi chal rahi coding hope achhi chal rahi hogi. chalo hamne user ka registration or session creat karna to sikh liya last part me. sab sikhe ke nahi ache se. samj me aagaya sabako lagta hai. dosto chalo aaj ham user ka email verify karate hai otp bhej ke kya bolate ho. ye sikhana bhi jaruri hai na ? to chalo shuru karte hai

sabase pahale hame register controller me jana hoga wahi se email pe OTP bhejenge na dosto sahi kaha na. jaise apane model ne user ka data successfully add kardiya to wo apane ko return true karega na. or return true kiya to hamane user ko welcome flash message display karaya tha na? yaad hai ya bhulgaye 🙂 to wahi pe ham email bhejane ka code likh ke user ko ham verify email page pe redirect / bhejdenge(hamne last part me user ko register ke bad login pe bheja tha) or use bollenge “bhai register hogaya hai aapke email pe otp aaya hoga yaha otp input karke verify kardo email ya aap ise skip bhi kar sakte ho” to ye karne ke liye hamko coding karni padegina chaliye fir project khol le jate hai register controller or model me. usase pehale hame database me do column add karne honge OTP or EmailConf.

Add New Columns to database

ALTER TABLE users ADD COLUMN OTP int;
ALTER TABLE users ADD COLUMN EmailConf bit DEFAULT 0;

Register controller

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Register extends CI_Controller {
	public function index()
	{
		$this->load->library('form_validation');
		$this->form_validation->set_rules('FullName', 'FullName', 'trim|required|alpha|htmlspecialchars|xss_clean');
		$this->form_validation->set_rules('Email', 'Email', 'trim|required|is_unique[users.Email]|htmlspecialchars|xss_clean',
		array('required' => 'You must provide a %s.','is_unique' => 'This %s already exists.'));
		$this->form_validation->set_rules('Password', 'Password', 'trim|required|min_length[5]|max_length[20]|htmlspecialchars|xss_clean');
		$this->form_validation->set_rules('passwordcnf', 'Password Confirmation', 'trim|required|matches[Password]|htmlspecialchars|xss_clean');
	
		if ($this->form_validation->run())
		{
			$FullName=$this->input->post('FullName');
			$Email=$this->input->post('Email');
			$Password=$this->input->post('Password');
			$pwd_hash=password_hash($Password,PASSWORD_BCRYPT);
			$this->load->model('registermodel');
			if($this->registermodel->add_user($FullName,$Email,$pwd_hash))
			{
				$id=$this->db->insert_id();//this function provide last created user id
				$newdata = array(
						'id'  => $id,
						'logged_in' => TRUE
					);
				$this->session->set_userdata($newdata);//on register sucsses insert session id 
				$this->session->set_flashdata('Reg_success','<p>Register successfully Welcome '.$FullName.',<br>
                Thankyou for join Hello world!<br> OTP successfully sended/Check your mail !!');
				return redirect('emailverify');
			}
			else{
				$this->session->set_flashdata('Reg_failed','<p>Some error occerd / try again!');
				return redirect('register');
			}
        }    
		else
		{
			$this->load->view('header');
			$this->load->view('register');
			$this->load->view('footer');
		}	
    }
    
    public function login()
	{
		$this->load->view('header');
		$this->load->view('login');
		$this->load->view('footer');
	}
}

Register Model

<?php
class registermodel extends CI_Model{
    public function add_user($FullName,$Email,$pwd_hash)
    {
      //Email cofig for send verification OTP
      $otp = rand(100000,999999);//this function creat random otp to all users
				$config = Array(
					'protocol' => 'smtp',
					'smtp_host' => 'ssl://smtp.googlemail.com',//when on live server you have to use hosting smtp host
					'smtp_port' => 465,
					'smtp_user' => 'masterarts002@gmail.com', // change it to yours
					'smtp_pass' => 'password@007', // change it to yours
					'mailtype' => 'html',
					'charset' => 'iso-8859-1',
					'wordwrap' => TRUE
				 );
				$this->load->library('email', $config);
				$this->email->set_newline("\r\n");
				$this->email->from('masterarts002@gmail.com', "Hello world Team");//change it yours
				$this->email->to($Email);  
				$this->email->subject("Hello word Forgot password");
				$this->email->message('<h3>Dear User</h3><br>'.'User Name: '.$FullName.'<br>Your One Time Password: '.$otp.'<br>Click <a href="http://localhost/masterarts/emailverify">here</a> to set password<br><h3>Thanks & Regards,<br>Moderation Team</h3>');
				$this->email->send();
				
          
      $new_user_data = array(
        'FullName' => $FullName,
        'Email' => $Email,
        'Password' => $pwd_hash,
        'OTP'=> $otp,
      );
      
      return  $this->db->insert('users',$new_user_data);
      
    }
}

dosto, local host se email sending function kabhi kabhi kam nahi karta security wise thoda strict hai Gmail na. per 100% garanty hai on server ye code 100% work karega. mene bahut site pe use kiya hai. bus smtp host acha hona chahiye server ka. hostinger ka mast hai.

OTP email na aaye to aap menually OTP check karle database me. verify function ki codding ke liye jaruri hai na chalo emailverify php bana lete view me or use load kara lete

emailverify view

<?php echo form_open('register/emailverify'); ?>
<!-- error message registration failed -->
<?php  if($error=$this->session->flashdata('Reg_success')):  ?>
        <div class="row">
            <div class="col-lg-12">
                <div class="alert alert-success">
                    <?= $error; ?>
                </div>
            </div>
        </div>
    <?php endif; ?>
<!-- for otp error -->
    <?php  if($error=$this->session->flashdata('otp_fail')):  ?>
        <div class="row">
            <div class="col-lg-12">
                <div class="alert alert-danger">
                    <?= $error; ?>
                </div>
            </div>
        </div>
    <?php endif; ?>
<h1>Email Verify</h1>
<form>
  <div class="form-group row">
    <div class="col-md-6">
       <label for="exampleInputEmail1">OTP</label>
       <input type="text" class="form-control" name="OTP" aria-describedby="emailHelp" placeholder="Enter email">
       <small id="emailHelp" class="form-text text-muted">don't share your OTP with anyone else.</small>
    </div>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

Register controller

add this function to register controller

public function emailverify()
	{
		$this->load->library('form_validation');
		$this->form_validation->set_rules('OTP', 'OTP', 'trim|required|htmlspecialchars|xss_clean');
		if ($this->form_validation->run())
		{
			$this->load->model('registermodel');
			$OTP = $this->input->post('OTP');
			if($this->registermodel->email_verify($OTP))
			{
				$this->session->set_flashdata('Reg_success','<p>successfully Verified Welcome');
				return redirect('login');
			}
			else
			{
				$this->session->set_flashdata('otp_fail','<p>Wronge OTP please input vailid opt');
				return redirect('register/emailverify');
			}
		}
		$this->load->view('header');
		$this->load->view('emailverify');
		$this->load->view('footer');
	}

Register Model

add this function to register model

public function email_verify($OTP)
    {
      $q = $this->db->select('*')
               ->where('OTP',$OTP)
               ->get('users');
      if($q->num_rows())//means row 0 se jyada hai
      {
        $this->db->set('EmailConf',TRUE)
                 ->where('OTP',$OTP)
                 ->update('users');
           return true;
      }
      else
      {
        return false;
      }         
    }

dosto otp aap database se lele apani site hai mail nahi aaya to hehe. waise verify karliya hamane aaj oe user ko login page pe bhej diya. agale part me user ko login karayenge.

dosto aapko main sikha raha hu samaj aaraha hai yaa nahi aap muje comment karake jarur bataye. dekhiye aap jab tak muje meri galtiya nahi batayenge me samj nahi paunga ki mistek kaha horahi. me aapke hisab se aapko samjane ki puri koshish karunga.

happy coding dosto