• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sending a Code to an Email Address in CodeIgniter

#1
I'm developing a simple website in CodeIgniter and want to start with an Introduction Page (which I have completed) and for those users interested in registering it moves to a page for the user to (1) Insert & Submit an email address which then sends an automatically generated 4 or 5 or 6 digit code to the email address and then moves to a page for the user to (2) Insert & Submit the code, which if correct then moves to a (3) username & password page (which I have almost completed) and when the username & password have been provided to (4) Send the extended username (that is with an integer on the end) & password to the email address, and moves to another page to (5) provide additional details (which I'm in the process of developing).

Can anybody provide me with simple coding for (1) Inserting & Submitting an email address and sending the Code. and (2) Inserting & Submitting the code and moving to the username & password page. and (4) Sending the extended username & password to the email address?

Preferably with CSS & Javascript in the same pages.

And be able to test from localhost.
Reply

#2
Start with creating a table in your database with the required fields. Maybe it's a good idea to have a users table, and also a registration table which holds the users that are in the registration proces.

Then create a controller with the functions you need to handle the different steps.
E.g.
PHP Code:
class Registration extends CI_Controller
{

 
  public function __construct()
 
  
    
parent::__construct();
    
$this->load->library(array('form_validation','email'));
 
  }

 
  public function step1() 
 
  {
 
     /*
        set form validation rules here, see documentation about form_validation library
     */
 
     if ($this->form_validation->run() == FALSE) {
 
          //load form
 
     }
 
     else {
           
$this->load->helper('string');
           
//generate code with string_random();  see documentation about the string helper
 
          //insert POST data into database table, see documentation about Query Builder
 
          //send e-mail with the email library, see documentation about email library
 
          redirect ('registration/step2');
 
    }
 
  }

 
  public function step2()
 
  {
 
     /*
        set form validation rules here
     */
 
     if ($this->form_validation->run() == FALSE) {
 
          //load form
 
     }
 
     else {
 
          //update POST data into database table, see documentation about Query Builder
 
          redirect ('registration/step3');
 
    }

 
  }

 
  //etc.


If necessary, you can store the e-mail address in a session variable, to reuse it from step to step. See documentation about Session library.
At the final step, create the record in the users table and delete the registration record. See documentation about Query Builder.

The actual work is up to you. I'm glad to help you in the right direction, but I'm not doing all coding for you. You learn faster and better, doing that yourself. Take a close look at the CI documentation. It's great.
Reply

#3
I'm having difficulty inserting the code into the database. I can get the email address inserted OK.

I searched "generate code with string_random();  see documentation about the string helper" in CodeIgniter's User Guide but could not get anything to work. But found another Random String which works if I insert it into the view page, but I can't get that into the database. I've tried many variations, including a separate Model Page but still can't get the code into the database.

This is my Controller Page;

PHP Code:
<?php
defined
('BASEPATH') OR exit('No direct script access allowed');

class 
Email extends CI_Controller
{
public function 
index()
{
$this->load->model('Email_model''email_model');
$this->load->helper(array('form''url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email''email''required|min_length[10]|max_length[40]|valid_email|is_unique[tbl_members.email_address]', array(
'required' => 'You have not entered an %s address.''min_length' => 'Your %s address must be a minimum of 10 characters.',
'max_length' => 'Your %s address must be a maximum of 40 characters.''valid_email' => 'You must enter a valid %s address.','is_unique' => 'That %s address already exists in our Database.'));
if (
$this->form_validation->run() == FALSE// The email address does not exist.
{
$this->load->view('email');
}
else
{
$email $this->input->post('email');
$this->email_model->insert_email($email);
//Works OK up to here
$code $this->$random_string();
$random_string chr(rand(65,90)) . rand(1,9) . chr(rand(65,90)) . rand(1,9) . chr(rand(65,90)) . chr(rand(65,90)); //This works in the view page
$this->code_model->insert_code($code);
}
}


This is my Model Page;

PHP Code:
<?php
defined
('BASEPATH') OR exit('No direct script access allowed');

class 
Email_model extends CI_Model
{

function 
__construct()
{
parent::__construct();
$this->load->database();
}

public function 
insert_email($email)
{
$data = array(
'email_address' => $email,
);
$this->db->insert('tbl_members'$data);
return 
$this->db->insert_id();
}

public function 
insert_code($code)
{
$data = array(
'pass_word' => $code
);
$this->db->insert('tbl_members'$data);
return 
$this->db->insert_id();
}

Reply

#4
I can't see if $this->random_string() is a function inside your controller.
If it is, the next line of code doesn't make sense.
If it's not, you will get an error message on that line.

I think you should do this:
PHP Code:
$this->load->helper('string');
$code random_string('md5');   //random_string() is a helper function! 

To save the code into your database, the pass_word field must be a VARCHAR field that can hold 32 characters, because an md5 is always 32 characters long. If you want a shorter code, you can use one of the other options of the random_string() helper function.
http://www.codeigniter.com/userguide3/he...elper.html
Reply

#5
Universally Unique Identifier Generator

Great for creating unique numbers for codes.


PHP Code:
<?php
defined
('BASEPATH') OR exit('No direct script access allowed');

/**
 * ------------------------------------------------------------------------
 * Editor   : PhpStorm 2017.1
 * Date     : 3/2/2017
 * Time     : 2:36 PM
 * Authors  : Raymond L King Sr.
 * ------------------------------------------------------------------------
 * 
 * Class        UUID
 *
 * @project     starter
 * @author      Raymond L King Sr.
 * @link        http://www.procoversfx.com
 * @copyright   Copyright (c) 2009 - 2017 Custom Software Designers, LLC.
 * @license     http://www.procoversfx.com/license
 * ------------------------------------------------------------------------
 */

// version 3, 4 and 5 uuid for namespace - can be generated online
//define('Uuid_Namespace', '1fb10795-5f81-454c-b857-2bc81956b0af');

/**
 * Class UUID
 *
 * Universally Unique Identifier Generator
 *
 * USAGE:
 *
 * $str = ''; // or Uuid_Namespace;
 *
 * $this->load->library(uuid);
 *
 * echo $str.$this->uuid->guid_v4()."<br><br>";
 *
 * echo $str.$this->uuid->v3(Uuid_Namespace, md5(uniqid(mt_rand(), true)))."<br><br>";
 * xxxxxxxx-xxxx-xxxx-xxxx-Out = Xxxxxxxxxxxx
 *
 * echo $str.$this->uuid->v4()."<br><br>";
 * xxxxxxxx-xxxx-xxxx-xxxx-Out = Xxxxxxxxxxxx
 *
 * echo $str.$this->uuid->v5(Uuid_Namespace, md5(uniqid(mt_rand(), true)))."<br><br>";
 * xxxxxxxx-xxxx-xxxx-xxxx-Out = Xxxxxxxxxxxx
 */

class UUID {

    
/**
     * Class variables - public, private, protected and static.
     * --------------------------------------------------------------------
     */

    /**
     * v3 ()
     * --------------------------------------------------------------------
     *
     * Version 3 UUIDs are named based.  They require a namespace (another
     * Valid UUID) and a value (the name).  Given the same namespace and
     * Name, the output is always the same.
     *
     * @param   Uuid   $namespace
     * @param   String $name
     * @return  bool|string
     */
    
public static function v3($namespace$name)
    {
        if (! 
self::isIdValid($namespace))
        {
            return 
false;
        }

        
// Get hexadecimal components of namespace
        
$nHex str_replace(array('-''{''}'), ''$namespace);

        
// Binary Value
        
$nStr '';

        
// Convert Namespace UUID to bits
        
for ($i 0$i strlen($nHex); $i += 2)
        {
            
$nStr .= chr(hexdec($nHex[$i].$nHex[$i 1]));
        }

        
// Calculate hash value
        
$hash md5($nStr.$name);

        return 
sprintf('%08S-04S-%%%04X-%04X-12s',

            
// 32 bits for "time_low"
            
substr($hash08),

            
// 16 bits for "time_mid"
            
substr($hash84),

            
/**
             * 16 bits for "time_hi_and_version",
             * Four most significant bits holds version number 3
             */
            
(hexdec(substr($hash124)) & 0X0Fff) | 0X3000,

            
/**
             * 16 bits, 8 bits for "clk_seq_hi_res", 8 bits for "clk_seq_low",
             * Two most significant bits holds zero and one for variant DCE1.1
             */
            
(hexdec(substr($hash164)) & 0X3Fff) | 0X8000,

            
// 48 bits for "node"
            
substr($hash2012)
        );
    }

    
/**
     * v4 ()
     * --------------------------------------------------------------------
     *
     * Version 4 UUIDs are pseudo-random.
     */
    
public static function v4()
    {
        return 
sprintf ('%04X%04X%04X04X-%04X-%%%04X-04X04X-%',

            
// 32 bits for "time_low"
         
   mt_rand(00Xffff), mt_rand(00Xffff),

            
// 16 bits for "time_mid"
         
   mt_rand(00Xffff),

            
/**
             * 16 bits for "time_hi_and_version",
             * Four most significant bits holds version number 4
             */
         
   mt_rand(00X0Fff) | 0X4000,

            
/**
             * 16 bits, 8 bits for "clk_seq_hi_res", 8 bits for "clk_seq_low",
             * Two most significant bits holds zero and one for variant DCE1.1
             */
         
   mt_rand(00X3Fff) | 0X8000,

            
// 48 bits for "node"
         
   mt_rand(00Xffff), mt_rand(00Xffff), mt_rand(00Xffff)
        );
    }

    
/**
     * guid_v4 ()
     * --------------------------------------------------------------------
     *
     * @return  string
     */
    
public static function guid_v4()
    {
        if (
function_exists('com_create_guid') === true)
        {
            return 
trim(com_create_guid(), '{}');
        }

        
$data openssl_random_pseudo_bytes(16);

        
// set version to 0100
        
$data[6] = chr(ord($data[6]) & 0x0f 0x40);

        
// set bits 6-7 to 10
        
$data[8] = chr(ord($data[8]) & 0x3f 0x80);
        
        return 
vsprintf('%s%s-%s-%s-%s-%s%s%s'str_split(bin2hex($data), 4));
    }

    
/**
     * v5 ()
     * --------------------------------------------------------------------
     *
     * Version 5 UUIDs are named based.  They require a namespace (another
     * Valid UUID) and a value (the name).  Given the same namespace and
     * Name, the output is always the same.
     *
     * @param   Uuid   $namespace
     * @param   String $name
     * @return  bool|string
     */
    
public static function v5($namespace$name)
    {
        if (! 
self::isIdValid($namespace))
        {
            return 
false;
        }

        
// Get hexadecimal components of namespace
        
$nHex str_replace(array('-''{''}'), ''$namespace);

        
// Binary Value
     
   $nStr '';

        
// Convert Namespace UUID to bits
        
for ($i 0$i strlen($nHex); $i += 2)
        {
            
$nStr .= chr(hexdec($nHex[$i].$nHex[$i 1]));
        }

        
// Calculate hash value
        
$hash sha1($nStr.$name);

        return 
sprintf('%08S-04S-%%%04X-%04X-12s',

            
// 32 bits for "time_low"
            
substr($hash08),

            
// 16 bits for "time_mid"
            
substr($hash84),

            
/**
             * 16 bits for "time_hi_and_version",
             * Four most significant bits holds version number 5
             */
            
(hexdec(substr($hash124)) & 0X0Fff) | 0X5000,

            
/**
             * 16 bits, 8 bits for "clk_seq_hi_res", 8 bits for "clk_seq_low",
             * Two most significant bits holds zero and one for variant DCE1.1
             */
            
(hexdec(substr($hash164)) & 0X3Fff) | 0X8000,

            
// 48 bits for "node"
            
substr($hash2012)
        );
    }

    
/**
     * isIdValid ()
     * --------------------------------------------------------------------
     *
     * @param   $uuid
     * @return  bool
     */
    
public static function isIdValid($uuid)
    {
        return 
preg_match ('/^\{?[0-9A-f]{8}\-?[0-9A-f]{4}\-?[0-9A-f]{4}\-?'.
         
                  '[0-9a-f]{4}\-?[0-9a-f]{12}\}?$/i'$uuid) === 1;
    }

  // End of UUID Class.

/**
 * ------------------------------------------------------------------------
 * Filename: UUID.php
 * Location: ./application/libraries/UUID.php
 * ------------------------------------------------------------------------
 */ 

You could slim this down by creating a helper using methods instead.
What did you Try? What did you Get? What did you Expect?

Joined the CodeIgniter Community in 2009.          ( Skype: insitfx )
Reply

#6
http://php.net/manual/en/function.random-bytes.php
https://github.com/paragonie/random_compat


https://www.codeigniter.com/user_guide/l...ndom_bytes
https://github.com/bcit-ci/CodeIgniter/b...y.php#L598

https://paragonie.com/blog/2015/07/commo...generators
Reply

#7
(04-22-2017, 12:48 AM)Wouter60 Wrote: I can't see if $this->random_string() is a function inside your controller.
If it is, the next line of code doesn't make sense.
If it's not, you will get an error message on that line.

I think you should do this:
PHP Code:
$this->load->helper('string');
$code random_string('md5');   //random_string() is a helper function! 

To save the code into your database, the pass_word field must be a VARCHAR field that can hold 32 characters, because an md5 is always 32 characters long. If you want a shorter code, you can use one of the other options of the random_string() helper function.
http://www.codeigniter.com/userguide3/he...elper.html

*************************
Yes, I had some errors in the Controller coding. It now looks like this;

PHP Code:
$email $this->input->post('email');
$random_string chr(rand(65,90)) . rand(1,9) . chr(rand(65,90)) . rand(1,9) . chr(rand(65,90)) . chr(rand(65,90));
$code $random_string;
$this->email_model->insert_email($email$code);
$this->load->view('code'); 

And I've changed the Model coding. It now looks like this;

PHP Code:
public function insert_email($email$code)
{
$data = array(
'email_address' => $email,
'pass_word' => $code
);
$this->db->insert('tbl_members'$data);
return 
$this->db->insert_id();


It now works good.
Reply

#8
(04-22-2017, 04:29 AM)InsiteFX Wrote: Universally Unique Identifier Generator

Great for creating unique numbers for codes.


PHP Code:
<?php
defined
('BASEPATH') OR exit('No direct script access allowed');

/**
 * ------------------------------------------------------------------------
 * Editor   : PhpStorm 2017.1
 * Date     : 3/2/2017
 * Time     : 2:36 PM
 * Authors  : Raymond L King Sr.
 * ------------------------------------------------------------------------
 * 
 * Class        UUID
 *
 * @project     starter
 * @author      Raymond L King Sr.
 * @link        http://www.procoversfx.com
 * @copyright   Copyright (c) 2009 - 2017 Custom Software Designers, LLC.
 * @license     http://www.procoversfx.com/license
 * ------------------------------------------------------------------------
 */

// version 3, 4 and 5 uuid for namespace - can be generated online
//define('Uuid_Namespace', '1fb10795-5f81-454c-b857-2bc81956b0af');

/**
 * Class UUID
 *
 * Universally Unique Identifier Generator
 *
 * USAGE:
 *
 * $str = ''; // or Uuid_Namespace;
 *
 * $this->load->library(uuid);
 *
 * echo $str.$this->uuid->guid_v4()."<br><br>";
 *
 * echo $str.$this->uuid->v3(Uuid_Namespace, md5(uniqid(mt_rand(), true)))."<br><br>";
 * xxxxxxxx-xxxx-xxxx-xxxx-Out = Xxxxxxxxxxxx
 *
 * echo $str.$this->uuid->v4()."<br><br>";
 * xxxxxxxx-xxxx-xxxx-xxxx-Out = Xxxxxxxxxxxx
 *
 * echo $str.$this->uuid->v5(Uuid_Namespace, md5(uniqid(mt_rand(), true)))."<br><br>";
 * xxxxxxxx-xxxx-xxxx-xxxx-Out = Xxxxxxxxxxxx
 */

class UUID {

 
/**
 * Class variables - public, private, protected and static.
 * --------------------------------------------------------------------
 */

 /**
 * v3 ()
 * --------------------------------------------------------------------
 *
 * Version 3 UUIDs are named based.  They require a namespace (another
 * Valid UUID) and a value (the name).  Given the same namespace and
 * Name, the output is always the same.
 *
 * @param   Uuid   $namespace
 * @param   String $name
 * @return  bool|string
 */
 
public static function v3($namespace$name)
 {
 if (! 
self::isIdValid($namespace))
 {
 return 
false;
 }

 
// Get hexadecimal components of namespace
 
$nHex str_replace(array('-''{''}'), ''$namespace);

 
// Binary Value
 
$nStr '';

 
// Convert Namespace UUID to bits
 
for ($i 0$i strlen($nHex); $i += 2)
 {
 
$nStr .= chr(hexdec($nHex[$i].$nHex[$i 1]));
 }

 
// Calculate hash value
 
$hash md5($nStr.$name);

 return 
sprintf('%08S-04S-%%%04X-%04X-12s',

 
// 32 bits for "time_low"
 
substr($hash08),

 
// 16 bits for "time_mid"
 
substr($hash84),

 
/**
 * 16 bits for "time_hi_and_version",
 * Four most significant bits holds version number 3
 */
 
(hexdec(substr($hash124)) & 0X0Fff) | 0X3000,

 
/**
 * 16 bits, 8 bits for "clk_seq_hi_res", 8 bits for "clk_seq_low",
 * Two most significant bits holds zero and one for variant DCE1.1
 */
 
(hexdec(substr($hash164)) & 0X3Fff) | 0X8000,

 
// 48 bits for "node"
 
substr($hash2012)
 );
 }

 
/**
 * v4 ()
 * --------------------------------------------------------------------
 *
 * Version 4 UUIDs are pseudo-random.
 */
 
public static function v4()
 {
 return 
sprintf ('%04X%04X%04X04X-%04X-%%%04X-04X04X-%',

 
// 32 bits for "time_low"
 
   mt_rand(00Xffff), mt_rand(00Xffff),

 
// 16 bits for "time_mid"
 
   mt_rand(00Xffff),

 
/**
 * 16 bits for "time_hi_and_version",
 * Four most significant bits holds version number 4
 */
 
   mt_rand(00X0Fff) | 0X4000,

 
/**
 * 16 bits, 8 bits for "clk_seq_hi_res", 8 bits for "clk_seq_low",
 * Two most significant bits holds zero and one for variant DCE1.1
 */
 
   mt_rand(00X3Fff) | 0X8000,

 
// 48 bits for "node"
 
   mt_rand(00Xffff), mt_rand(00Xffff), mt_rand(00Xffff)
 );
 }

 
/**
 * guid_v4 ()
 * --------------------------------------------------------------------
 *
 * @return  string
 */
 
public static function guid_v4()
 {
 if (
function_exists('com_create_guid') === true)
 {
 return 
trim(com_create_guid(), '{}');
 }

 
$data openssl_random_pseudo_bytes(16);

 
// set version to 0100
 
$data[6] = chr(ord($data[6]) & 0x0f 0x40);

 
// set bits 6-7 to 10
 
$data[8] = chr(ord($data[8]) & 0x3f 0x80);
 
 return 
vsprintf('%s%s-%s-%s-%s-%s%s%s'str_split(bin2hex($data), 4));
 }

 
/**
 * v5 ()
 * --------------------------------------------------------------------
 *
 * Version 5 UUIDs are named based.  They require a namespace (another
 * Valid UUID) and a value (the name).  Given the same namespace and
 * Name, the output is always the same.
 *
 * @param   Uuid   $namespace
 * @param   String $name
 * @return  bool|string
 */
 
public static function v5($namespace$name)
 {
 if (! 
self::isIdValid($namespace))
 {
 return 
false;
 }

 
// Get hexadecimal components of namespace
 
$nHex str_replace(array('-''{''}'), ''$namespace);

 
// Binary Value
 
   $nStr '';

 
// Convert Namespace UUID to bits
 
for ($i 0$i strlen($nHex); $i += 2)
 {
 
$nStr .= chr(hexdec($nHex[$i].$nHex[$i 1]));
 }

 
// Calculate hash value
 
$hash sha1($nStr.$name);

 return 
sprintf('%08S-04S-%%%04X-%04X-12s',

 
// 32 bits for "time_low"
 
substr($hash08),

 
// 16 bits for "time_mid"
 
substr($hash84),

 
/**
 * 16 bits for "time_hi_and_version",
 * Four most significant bits holds version number 5
 */
 
(hexdec(substr($hash124)) & 0X0Fff) | 0X5000,

 
/**
 * 16 bits, 8 bits for "clk_seq_hi_res", 8 bits for "clk_seq_low",
 * Two most significant bits holds zero and one for variant DCE1.1
 */
 
(hexdec(substr($hash164)) & 0X3Fff) | 0X8000,

 
// 48 bits for "node"
 
substr($hash2012)
 );
 }

 
/**
 * isIdValid ()
 * --------------------------------------------------------------------
 *
 * @param   $uuid
 * @return  bool
 */
 
public static function isIdValid($uuid)
 {
 return 
preg_match ('/^\{?[0-9A-f]{8}\-?[0-9A-f]{4}\-?[0-9A-f]{4}\-?'.
 
                  '[0-9a-f]{4}\-?[0-9a-f]{12}\}?$/i'$uuid) === 1;
 }

  // End of UUID Class.

/**
 * ------------------------------------------------------------------------
 * Filename: UUID.php
 * Location: ./application/libraries/UUID.php
 * ------------------------------------------------------------------------
 */ 

You could slim this down by creating a helper using methods instead.


I'm grateful for your input, but I'm wanting all of the coding to be simple as possible. I've achieved that with the amendments I've made.
Reply

#9
(04-22-2017, 05:25 AM)Paradinight Wrote: http://php.net/manual/en/function.random-bytes.php
https://github.com/paragonie/random_compat


https://www.codeigniter.com/user_guide/l...ndom_bytes
https://github.com/bcit-ci/CodeIgniter/b...y.php#L598

https://paragonie.com/blog/2015/07/commo...generators


I'm grateful for your input. I find most manuals are very difficult to understand. I've achieved simple coding by searching the Internet and amended my coding accordingly.
Reply

#10
Here is a simple helper version.

PHP Code:
<?php
defined
('BASEPATH') OR exit('No direct script access allowed');

/**
 * ----------------------------------------------------------------------------
 * Editor   : PhpStorm 2017.1.2
 * Date     : 4/23/2017
 * Time     : 6:11 AM
 * Authors  : Raymond L King Sr.
 * ----------------------------------------------------------------------------
 *
 * Class        uuid_helper
 *
 * @project     ci3
 * @author      Raymond L King Sr.
 * @link        http://www.procoversfx.com
 * @copyright   Copyright (c) 2009 - 2017 Pro Covers FX, LLC.
 * @license     http://www.procoversfx.com/license
 * ----------------------------------------------------------------------------
 */

// ----------------------------------------------------------------------------

/**
 * guid_v4 ()
 * --------------------------------------------------------------------
 */
if ( ! function_exists('guid_v4'))
{
    
/**
     * guid_v4 ()
     * ---------------------------------------------------------------------------
     *
     * USAGE: $code = guid_v4();
     *
     * @return string
     */
    
function guid_v4()
    {
        if (
function_exists('com_create_guid') === true)
        {
            return 
trim(com_create_guid(), '{}');
        }

        
$data openssl_random_pseudo_bytes(16);

        
// set version to 0100
        
$data[6] = chr(ord($data[6]) & 0x0f 0x40);

        
// set bits 6-7 to 10
        
$data[8] = chr(ord($data[8]) & 0x3f 0x80);

        return 
vsprintf('%s%s-%s-%s-%s-%s%s%s'str_split(bin2hex($data), 4));
    }
}

/**
 * ----------------------------------------------------------------------------
 * Filename: uuid_helper.php
 * Location: ./application/helpers/uuid_helper.php
 * ----------------------------------------------------------------------------
 */ 
What did you Try? What did you Get? What did you Expect?

Joined the CodeIgniter Community in 2009.          ( Skype: insitfx )
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


Users browsing this thread:
1 Guest(s)


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2017 MyBB Group.