<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Codeigniter Archives - Michael Soriano</title>
	<atom:link href="https://michaelsoriano.com/tag/codeigniter/feed/" rel="self" type="application/rss+xml" />
	<link>https://michaelsoriano.com/tag/codeigniter/</link>
	<description>I turn code into captivating user experiences for the web</description>
	<lastBuildDate>Fri, 01 Dec 2023 00:56:46 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.4</generator>
	<item>
		<title>Building a user registration system – Part 3: The Password Reset Form</title>
		<link>https://michaelsoriano.com/building-a-user-registration-system-part-3-password-reset/</link>
					<comments>https://michaelsoriano.com/building-a-user-registration-system-part-3-password-reset/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Sat, 10 Oct 2015 20:27:47 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Bootstrap]]></category>
		<category><![CDATA[Codeigniter]]></category>
		<category><![CDATA[MVC]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=5243</guid>

					<description><![CDATA[<p>So now we&#8217;ve come to the last part of this series. We need a way to let users back in when they forget their passwords. So we&#8217;re going to need a form, a mechanism to notify them with a unique token, as well as another form to actually do the resetting of the password. Plenty [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/building-a-user-registration-system-part-3-password-reset/">Building a user registration system – Part 3: The Password Reset Form</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>So now we&#8217;ve come to the last part of this series. We need a way to let users back in when they forget their passwords. So we&#8217;re going to need a form, a mechanism to notify them with a unique token, as well as another form to actually do the resetting of the password. Plenty of going on here, so let&#8217;s start coding.</p>



<p><strong>Update 9/5/2016: </strong> Updated flaw in token creation and token checking for better security. Thanks to <a href="https://michaelsoriano.com/building-a-user-registration-system-part-3-password-reset/#comment-36867">comment by Mohammad</a> and his findings.</p>



<p><strong>Update 7/20/2016: </strong> Added index.php file to the views directory. This is the view that is being used once a successful login is processed.</p>



<p><a href="https://github.com/michaelsoriano/user-registration-codeigniter">View in Github</a></p>



<h3 class="wp-block-heading">The Forgot your Password form</h3>



<p>In our controller &#8220;Main.php&#8221;, let&#8217;s add a new action called &#8220;forgot&#8221;. The code is below and I&#8217;ll explain what is inside:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">public function forgot()
        {
            $this-&gt;form_validation-&gt;set_rules('email', 'Email', 'required|valid_email');
            if($this-&gt;form_validation-&gt;run() == FALSE) {
                $this-&gt;load-&gt;view('header');
                $this-&gt;load-&gt;view('forgot');
                $this-&gt;load-&gt;view('footer');
            }else{
                $email = $this-&gt;input-&gt;post('email');
                $clean = $this-&gt;security-&gt;xss_clean($email);
                $userInfo = $this-&gt;user_model-&gt;getUserInfoByEmail($clean);
                if(!$userInfo){
                    $this-&gt;session-&gt;set_flashdata('flash_message', 'We cant find your email address');
                    redirect(site_url().'main/login');
                }
                if($userInfo-&gt;status != $this-&gt;status[1]){ //if status is not approved
                    $this-&gt;session-&gt;set_flashdata('flash_message', 'Your account is not in approved status');
                    redirect(site_url().'main/login');
                }
                //build token
                $token = $this-&gt;user_model-&gt;insertToken($userInfo-&gt;id);
                $qstring = $this-&gt;base64url_encode($token);
                $url = site_url() . 'main/reset_password/token/' . $qstring;
                $link = '<a href="' . $url . '">' . $url . '</a>';
                $message = '';
                $message .= '<strong>A password reset has been requested for this email account</strong>
';
                $message .= '<strong>Please click:</strong> ' . $link;
                echo $message; //send this through mail
                exit;
            }
        }
</code></pre>



<p>The action opens up the same way we have with our other forms. We have our validation rules for our &#8220;email&#8221; input field. In our form, all we&#8217;re really asking for our user is to enter their password. So we just need to run a couple of rules against this value: valid email and required. Once our validation passes, we also clean the data with our xss_clean() method which is loaded automatically. </p>



<p>To learn more about the Security Helper click <a href="https://www.codeigniter.com/user_guide/helpers/security_helper.html">here</a>.</p>



<p>Now we check if the email submitted exists in our database through our Model method: getUserInfoByEmail(). So add the code below to our Model (User_Model.php). This method returns the record on success and false on fail.</p>



<pre class="wp-block-code"><code lang="php" class="language-php">public function getUserInfoByEmail($email)
    {
        $q = $this-&gt;db-&gt;get_where('users', array('email' =&gt; $email), 1);
        if($this-&gt;db-&gt;affected_rows() &gt; 0){
            $row = $q-&gt;row();
            return $row;
        }else{
            error_log('no user found getUserInfo('.$email.')');
            return false;
        }
    }
</code></pre>



<p>We also need another method that checks grabs the user information. This method called &#8220;getUserInfo()&#8221; simply returns the row and false if none is found:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">public function getUserInfo($id)
    {
        $q = $this-&gt;db-&gt;get_where('users', array('id' =&gt; $id), 1);
        if($this-&gt;db-&gt;affected_rows() &gt; 0){
            $row = $q-&gt;row();
            return $row;
        }else{
            error_log('no user found getUserInfo('.$id.')');
            return false;
        }
    }
</code></pre>



<p>So back in our &#8220;<em>forgot</em>&#8221; action, we simply set a couple of error messages when we receive a false from our model, or proceed with the token creation &#8220;<em>insertToken</em>()&#8221; on success. Note that we are reusing this method from our previous action when creating a new user.</p>



<p>The code for our view is below. Just some messaging our form and input fields. Notice we&#8217;re using <a href="https://www.codeigniter.com/user_guide/helpers/form_helper.html">CodeIgniter&#8217;s Form class</a>.</p>



<pre class="wp-block-code"><code lang="php" class="language-php">&lt;div class="col-lg-4 col-lg-offset-4">
&lt;h2>Forgot Password&lt;/h2>
&lt;p>Please enter your email address and we'll send you instructions on how to reset your password&lt;br>
&lt;?php 
$fattr = array('class' =--> 'form-signin'); 
echo form_open(site_url().'main/forgot/', $fattr); ?>
&lt;/p>
&lt;div class="form-group">
&lt;?php echo form_input(array(
          'name'=-->'email', 'id'=&amp;gt; 'email', 'placeholder'=&amp;gt;'Email', 'class'=&amp;gt;'form-control', 'value'=&amp;gt; set_value('email'))); ?>
&lt;?php echo form_error('email');?>
&lt;/div>
&lt;p>&lt;?php echo form_submit(array('value'=-->'Submit', 'class'=&amp;gt;'btn btn-lg btn-primary btn-block')); ?>
&lt;?php echo form_close(); ?>&lt;/p>
&lt;/div>

</code></pre>



<p><br>Now go ahead and try out your form. Try an email that doesn&#8217;t exist &#8211; and try one that does. With our unique token code in our action, we continue to construct the link and &#8220;echo&#8221; to the browser. </p>



<p><img fetchpriority="high" decoding="async" width="608" height="365" class="alignnone size-full wp-image-5251" src="https://michaelsoriano.com/wp-content/uploads/2015/10/forgot-password.png" alt="forgot-password" srcset="https://michaelsoriano.com/wp-content/uploads/2015/10/forgot-password.png 608w, https://michaelsoriano.com/wp-content/uploads/2015/10/forgot-password-300x180.png 300w" sizes="(max-width: 608px) 100vw, 608px" /></p>



<p>Remember that this is to be emailed to the user but we are simply echoing it out for demo purposes. The link should look like below:<br><img decoding="async" width="731" height="140" class="alignnone size-full wp-image-7104" src="https://michaelsoriano.com/wp-content/uploads/2015/10/token-1.jpg" alt="" srcset="https://michaelsoriano.com/wp-content/uploads/2015/10/token-1.jpg 731w, https://michaelsoriano.com/wp-content/uploads/2015/10/token-1-300x57.jpg 300w" sizes="(max-width: 731px) 100vw, 731px" /></p>



<h3 class="wp-block-heading">The Reset Password Form</h3>



<p>So now we have a unique link that we&#8217;ve sent to our forgetful user. Once they click on this link &#8211; they better have a page to land on, with a way to reset their password. So let&#8217;s build that now.<br>Let&#8217;s create another action in our controller, name it &#8220;reset_password()&#8221; and add the code below:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">public function reset_password()
        {
            $token = $this-&gt;base64url_decode($this-&gt;uri-&gt;segment(4));
            $cleanToken = $this-&gt;security-&gt;xss_clean($token);
            $user_info = $this-&gt;user_model-&gt;isTokenValid($cleanToken); //either false or array();
            if(!$user_info){
                $this-&gt;session-&gt;set_flashdata('flash_message', 'Token is invalid or expired');
                redirect(site_url().'main/login');
            }
            $data = array(
                'firstName'=&gt; $user_info-&gt;first_name,
                'email'=&gt;$user_info-&gt;email,
                'token'=&gt;base64_encode($token)
            );
            $this-&gt;form_validation-&gt;set_rules('password', 'Password', 'required|min_length[5]');
            $this-&gt;form_validation-&gt;set_rules('passconf', 'Password Confirmation', 'required|matches[password]');
            if ($this-&gt;form_validation-&gt;run() == FALSE) {
                $this-&gt;load-&gt;view('header');
                $this-&gt;load-&gt;view('reset_password', $data);
                $this-&gt;load-&gt;view('footer');
            }else{
                $this-&gt;load-&gt;library('password');
                $post = $this-&gt;input-&gt;post(NULL, TRUE);
                $cleanPost = $this-&gt;security-&gt;xss_clean($post);
                $hashed = $this-&gt;password-&gt;create_hash($cleanPost['password']);
                $cleanPost['password'] = $hashed;
                $cleanPost['user_id'] = $user_info-&gt;id;
                unset($cleanPost['passconf']);
                if(!$this-&gt;user_model-&gt;updatePassword($cleanPost)){
                    $this-&gt;session-&gt;set_flashdata('flash_message', 'There was a problem updating your password');
                }else{
                    $this-&gt;session-&gt;set_flashdata('flash_message', 'Your password has been updated. You may now login');
                }
                redirect(site_url().'main/login');
            }
        }
</code></pre>



<p>So our users will land in our page called &#8220;reset_password&#8221;, with a token in the url. First we need to process that and determine if its a good token. This is accomplished by our model&#8217;s isTokenValid() method. This method is the same method we had in our &#8220;complete&#8221; action when we are registering a new user &#8211; so this is nothing new. </p>



<p>And if you remember, this method returns user information on success &#8211; so we go on with our setup for the form. We pass this information using $data array straight to our view, reset_password.php:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">&lt;div class="col-lg-4 col-lg-offset-4">
&lt;h2>Reset your password&lt;/h2>
&lt;h5>Hello &lt;?php echo $firstName; ?>, Please enter your password 2x below to reset&lt;/h5>
&lt;p>&lt;?php
    $fattr = array('class' =--> 'form-signin'); echo form_open(site_url().'main/reset_password/token/'.$token, $fattr); ?>&lt;/p>
&lt;div class="form-group">
&lt;?php echo form_password(array('name'=-->'password', 'id'=&amp;gt; 'password', 'placeholder'=&amp;gt;'Password', 'class'=&amp;gt;'form-control', 'value' =&amp;gt; set_value('password'))); ?&amp;gt; &lt;?php echo form_error('password') ?>&lt;/div>
&lt;div class="form-group">
&lt;?php echo form_password(array('name'=-->'passconf', 'id'=&amp;gt; 'passconf', 'placeholder'=&amp;gt;'Confirm Password', 'class'=&amp;gt;'form-control', 'value'=&amp;gt; set_value('passconf'))); ?> &lt;?php echo form_error('passconf') ?>&lt;/div>
&lt;p>&lt;?php echo form_hidden('user_id', $user_id);?>
&lt;?php echo form_submit(array('value'=-->'Reset Password', 'class'=&amp;gt;'btn btn-lg btn-primary btn-block')); ?>
&lt;?php echo form_close(); ?>&lt;/p>
&lt;/div></code></pre>



<p>Clicking the link with the token will run our view. And if you did it correctly, it should render like below:</p>



<p><br><img decoding="async" width="606" height="412" class="alignnone size-full wp-image-5255" src="https://michaelsoriano.com/wp-content/uploads/2015/10/reset-password.png" alt="reset-password" srcset="https://michaelsoriano.com/wp-content/uploads/2015/10/reset-password.png 606w, https://michaelsoriano.com/wp-content/uploads/2015/10/reset-password-300x204.png 300w" sizes="(max-width: 606px) 100vw, 606px" /></p>



<p>Finally, we do some validation and sanitation on the passwords entered. Once passed, we continue to encrypt our user&#8217;s password through the create_hash() method. Remember this method is from our <a href="https://defuse.ca/php-pbkdf2.htm">Password class</a> that we&#8217;ve also used when creating new users. Then we update the user&#8217;s password on success.</p>



<h3 class="wp-block-heading">Conclusion</h3>



<p>So there you have our basic user registration system, explained in detail. Remember that this is mainly to get a grasp on what goes on behind the scenes of such a system as well as learning the ropes of <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a>. It is also important to know that this is not production code. There are plenty of improvements to be made. But this should be enough to get you started.</p>
<p>The post <a href="https://michaelsoriano.com/building-a-user-registration-system-part-3-password-reset/">Building a user registration system – Part 3: The Password Reset Form</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/building-a-user-registration-system-part-3-password-reset/feed/</wfw:commentRss>
			<slash:comments>46</slash:comments>
		
		
			</item>
		<item>
		<title>Building a user registration system – Part 2: The Set Password and Login Forms</title>
		<link>https://michaelsoriano.com/building-a-user-registration-system-part-2-login-form/</link>
					<comments>https://michaelsoriano.com/building-a-user-registration-system-part-2-login-form/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Thu, 10 Sep 2015 10:01:52 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Bootstrap]]></category>
		<category><![CDATA[Codeigniter]]></category>
		<category><![CDATA[MVC]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=5108</guid>

					<description><![CDATA[<p>So let&#8217;s continue with our registration system. We left off at the point where we have the registration page setup. So let&#8217;s try it out and fill in some information. Add your name and an email address. The fields should have validation, so you should see an error if you missed a field, or the [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/building-a-user-registration-system-part-2-login-form/">Building a user registration system – Part 2: The Set Password and Login Forms</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>So let&#8217;s continue with our registration system. We left off at the point where we have the registration page setup. So let&#8217;s try it out and fill in some information. Add your name and an email address. The fields should have validation, so you should see an error if you missed a field, or the email is invalid. We also check if the email is duplicate &#8211; so you should see an error for that as well.</p>



<p><strong>Update 9/5/2016: </strong> Updated flaw in token creation and token checking for better security. Thanks to <a href="https://michaelsoriano.com/building-a-user-registration-system-part-3-password-reset/#comment-36867">comment by Mohammad</a> and his findings.</p>



<p><strong>Update 7/20/2016: </strong> Added index.php file to the views directory. This is the view that is being used once a successful login is processed.</p>



<p><a href="https://github.com/michaelsoriano/user-registration-codeigniter">View in GitHub</a><br></p>



<p><img decoding="async" width="600" height="368" class="alignnone size-full wp-image-5109" src="https://michaelsoriano.com/wp-content/uploads/2015/09/user-reg-0.jpg" alt="user-reg-0" srcset="https://michaelsoriano.com/wp-content/uploads/2015/09/user-reg-0.jpg 600w, https://michaelsoriano.com/wp-content/uploads/2015/09/user-reg-0-300x184.jpg 300w" sizes="(max-width: 600px) 100vw, 600px" /></p>



<p>Once you fill out the fields, check your database for the new entries. The user table should look like below:</p>



<p><img decoding="async" width="600" height="154" class="alignnone size-full wp-image-5113" src="https://michaelsoriano.com/wp-content/uploads/2015/09/user-reg-1a.jpg" alt="user-reg-1a" srcset="https://michaelsoriano.com/wp-content/uploads/2015/09/user-reg-1a.jpg 600w, https://michaelsoriano.com/wp-content/uploads/2015/09/user-reg-1a-300x77.jpg 300w" sizes="(max-width: 600px) 100vw, 600px" /></p>



<p>Note that we have the status set to &#8220;pending&#8221; as well as the role set to &#8220;subscriber&#8221;. We also have the password blank at the moment. Open the &#8220;tokens&#8221; table and you should see a new entry as well:</p>



<p><br><img decoding="async" width="600" height="154" class="alignnone size-full wp-image-5111" src="https://michaelsoriano.com/wp-content/uploads/2015/09/user-reg-2.jpg" alt="user-reg-2" srcset="https://michaelsoriano.com/wp-content/uploads/2015/09/user-reg-2.jpg 600w, https://michaelsoriano.com/wp-content/uploads/2015/09/user-reg-2-300x77.jpg 300w" sizes="(max-width: 600px) 100vw, 600px" /><br></p>



<p>Notice our user ids match in both tables. You should also be seeing our message in the browser &#8211; which is the message we will be sending through email to our user:<br></p>



<p><img decoding="async" width="600" height="154" class="alignnone size-full wp-image-5115" src="https://michaelsoriano.com/wp-content/uploads/2015/09/user-reg-3.jpg" alt="user-reg-3" srcset="https://michaelsoriano.com/wp-content/uploads/2015/09/user-reg-3.jpg 600w, https://michaelsoriano.com/wp-content/uploads/2015/09/user-reg-3-300x77.jpg 300w" sizes="(max-width: 600px) 100vw, 600px" /><br>Now we&#8217;re ready to code the 2nd part of the registration process.</p>



<h3 class="wp-block-heading">The &#8220;Complete&#8221; your registration page</h3>



<p>So our user gets an email to complete the registration. This email has a link with a &#8220;token&#8221; that ties the user id and the time created. So the code below is for our &#8220;complete&#8221; action. imply add to our Main controller:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">public function complete()
        {
            $token = base64_decode($this-&gt;uri-&gt;segment(4));
            $cleanToken = $this-&gt;security-&gt;xss_clean($token);
            $user_info = $this-&gt;user_model-&gt;isTokenValid($cleanToken); //either false or array();
            if(!$user_info){
                $this-&gt;session-&gt;set_flashdata('flash_message', 'Token is invalid or expired');
                redirect(site_url().'main/login');
            }
            $data = array(
                'firstName'=&gt; $user_info-&gt;first_name,
                'email'=&gt;$user_info-&gt;email,
                'user_id'=&gt;$user_info-&gt;id,
                'token'=&gt;$this-&gt;base64url_encode($token)
            );
            $this-&gt;form_validation-&gt;set_rules('password', 'Password', 'required|min_length[5]');
            $this-&gt;form_validation-&gt;set_rules('passconf', 'Password Confirmation', 'required|matches[password]');
            if ($this-&gt;form_validation-&gt;run() == FALSE) {
                $this-&gt;load-&gt;view('header');
                $this-&gt;load-&gt;view('complete', $data);
                $this-&gt;load-&gt;view('footer');
            }else{
                $this-&gt;load-&gt;library('password');
                $post = $this-&gt;input-&gt;post(NULL, TRUE);
                $cleanPost = $this-&gt;security-&gt;xss_clean($post);
                $hashed = $this-&gt;password-&gt;create_hash($cleanPost['password']);
                $cleanPost['password'] = $hashed;
                unset($cleanPost['passconf']);
                $userInfo = $this-&gt;user_model-&gt;updateUserInfo($cleanPost);
                if(!$userInfo){
                    $this-&gt;session-&gt;set_flashdata('flash_message', 'There was a problem updating your record');
                    redirect(site_url().'main/login');
                }
                unset($userInfo-&gt;password);
                foreach($userInfo as $key=&gt;$val){
                    $this-&gt;session-&gt;set_userdata($key, $val);
                }
                redirect(site_url().'main/');
            }
        }
</code></pre>



<p>First order of business is to validate the token. We grab it from the url with CI&#8217;s <a href="http://www.codeigniter.com/user_guide/general/urls.html">uri helper</a>: &#8220;segment(4)&#8221;. The code below &#8220;isTokenValid()&#8221; resides in our model, which checks the validity of the token and returns the user information on success and false on no. </p>



<p>Note that I&#8217;m only using a weak time check &#8211; which compares to strings to be equal. You should implement your own mechanism which does a dateDiff or something like that.</p>



<pre class="wp-block-code"><code lang="php" class="language-php">public function isTokenValid($token)
    {
       $tkn = substr($token,0,30);
       $uid = substr($token,30);
        $q = $this-&gt;db-&gt;get_where('tokens', array(
            'tokens.token' =&gt; $tkn,
            'tokens.user_id' =&gt; $uid), 1);
        if($this-&gt;db-&gt;affected_rows() &gt; 0){
            $row = $q-&gt;row();
            $created = $row-&gt;created;
            $createdTS = strtotime($created);
            $today = date('Y-m-d');
            $todayTS = strtotime($today);
            if($createdTS != $todayTS){
                return false;
            }
            $user_info = $this-&gt;getUserInfo($row-&gt;user_id);
            return $user_info;
        }else{
            return false;
        }
    }
</code></pre>



<p>Going back to our action, we simply create the &#8220;$data&#8221; array which we&#8217;ll need in our form. We&#8217;re also loading a &#8220;<a href="https://defuse.ca/php-pbkdf2.htm">Password</a>&#8221; class &#8211; which does the heavy lifting for our passwords. The class creates a dynamic salt appended to the password. The default hash is &#8220;sha256&#8221; and is fully configurable.<br></p>



<p>So token is good, validation passes &#8211; we then move on to updating our user information: &#8220;updateUserInfo()&#8221;. This goes in our model:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">public function updateUserInfo($post)
    {
        $data = array(
               'password' =&gt; $post['password'],
               'last_login' =&gt; date('Y-m-d h:i:s A'),
               'status' =&gt; $this-&gt;status[1]
            );
        $this-&gt;db-&gt;where('id', $post['user_id']);
        $this-&gt;db-&gt;update('users', $data);
        $success = $this-&gt;db-&gt;affected_rows();
        if(!$success){
            error_log('Unable to updateUserInfo('.$post['user_id'].')');
            return false;
        }
        $user_info = $this-&gt;getUserInfo($post['user_id']);
        return $user_info;
    }
</code></pre>



<p>The above simply updates our table with the new password, login time and the status to &#8220;active&#8221;. We have enough to complete our registration process.</p>



<p>Our view called &#8220;complete&#8221; will contain our HTML:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">&lt;div class="col-lg-4 col-lg-offset-4">
&lt;h2>Almost There!&lt;/h2>
&lt;h5>Hello &lt;?php echo $firstName; ?>. Your username is &lt;?php echo $email;?>&lt;/h5>
&lt;small>Please enter a password to begin using the site.&lt;/small> &lt;?php 
    $fattr = array('class' =&amp;gt; 'form-signin');
    echo form_open(site_url().'main/complete/token/'.$token, $fattr); ?>
&lt;div class="form-group">&amp;nbsp;&lt;/div>
&lt;div class="form-group">&amp;nbsp;&lt;/div>
&lt;?php echo form_submit(array('value'=&amp;gt;'Complete', 'class'=&amp;gt;'btn btn-lg btn-primary btn-block')); ?> 
&lt;?php echo form_close(); ?>&lt;/div></code></pre>



<p>Note that I&#8217;m using <a href="http://getbootstrap.com/">Bootstrap</a>, so our form automatically looks nice. I&#8217;m also using CI&#8217;s <a href="http://www.codeigniter.com/user_guide/helpers/form_helper.html">form helper</a> which makes our form building faster</p>



<p>Our form should look like below:</p>



<p><img decoding="async" width="600" height="366" class="alignnone size-full wp-image-5118" src="https://michaelsoriano.com/wp-content/uploads/2015/09/user-reg-4.jpg" alt="user-reg-4" srcset="https://michaelsoriano.com/wp-content/uploads/2015/09/user-reg-4.jpg 600w, https://michaelsoriano.com/wp-content/uploads/2015/09/user-reg-4-300x183.jpg 300w" sizes="(max-width: 600px) 100vw, 600px" /></p>



<p>On success you will notice that we set the session with the user data that we&#8217;ve fetched from the back end &#8220;<a href="http://www.codeigniter.com/user_guide/libraries/sessions.html?highlight=set_userdata#CI_Session::set_userdata">set_userdata()</a>&#8220;. We&#8217;re also redirecting them to the homepage of our site. On failure, we user CI&#8217;s &#8220;<a href="http://www.codeigniter.com/user_guide/libraries/sessions.html">set_flashdata()</a>&#8221; to set an error message temporarily in session, and displaying it above our form.</p>



<h3 class="wp-block-heading">The Login Form</h3>



<p>With what we&#8217;ve done above &#8211; it&#8217;s now possible to create a login form. See, we&#8217;re using an encryption technology that only our application can process. So it is important that we create our registration system first, before we can create a login form. </p>



<p>This way &#8211; we can test it properly.</p>



<p>The code below is our controller logic for our login form:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">public function login()
        {
            $this-&gt;form_validation-&gt;set_rules('email', 'Email', 'required|valid_email');
            $this-&gt;form_validation-&gt;set_rules('password', 'Password', 'required');
            if($this-&gt;form_validation-&gt;run() == FALSE) {
                $this-&gt;load-&gt;view('header');
                $this-&gt;load-&gt;view('login');
                $this-&gt;load-&gt;view('footer');
            }else{
                $post = $this-&gt;input-&gt;post();
                $clean = $this-&gt;security-&gt;xss_clean($post);
                $userInfo = $this-&gt;user_model-&gt;checkLogin($clean);
                if(!$userInfo){
                    $this-&gt;session-&gt;set_flashdata('flash_message', 'The login was unsucessful');
                    redirect(site_url().'main/login');
                }
                foreach($userInfo as $key=&gt;$val){
                    $this-&gt;session-&gt;set_userdata($key, $val);
                }
                redirect(site_url().'main/');
            }
        }
</code></pre>



<p>Nothing new in the code above. Again, we&#8217;re setting validation rules for our 2 fields. We grab the post array and clean it via <a href="http://www.codeigniter.com/user_guide/helpers/security_helper.html">xss_clean()</a>. Then we get to our model which has the checkLogin() method below:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">public function checkLogin($post)
    {
        $this-&gt;load-&gt;library('password');
        $this-&gt;db-&gt;select('*');
        $this-&gt;db-&gt;where('email', $post['email']);
        $query = $this-&gt;db-&gt;get('users');
        $userInfo = $query-&gt;row();
        if(!$this-&gt;password-&gt;validate_password($post['password'], $userInfo-&gt;password)){
            error_log('Unsuccessful login attempt('.$post['email'].')');
            return false;
        }
        $this-&gt;updateLoginTime($userInfo-&gt;id);
        unset($userInfo-&gt;password);
        return $userInfo;
    }
    public function updateLoginTime($id)
    {
        $this-&gt;db-&gt;where('id', $id);
        $this-&gt;db-&gt;update('users', array('last_login' =&gt; date('Y-m-d h:i:s A')));
        return;
    }
</code></pre>



<p>The above selects all columns where the user id and password match. Note that we&#8217;re using the validate_password() method from our Password class. We then update the login time and return the user information back to our controller.</p>



<p>Our login form view contains the code below:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">&lt;div class="col-lg-4 col-lg-offset-4">
&lt;h2>Please login&lt;/h2>
&lt;?php $fattr = array('class' =&amp;gt; 'form-signin');
         echo form_open(site_url().'main/login/', $fattr); ?>
&lt;div class="form-group">&amp;nbsp;&lt;/div>
&lt;div class="form-group">&amp;nbsp;&lt;/div>
&lt;?php echo form_submit(array('value'=&amp;gt;'Let me in!', 'class'=&amp;gt;'btn btn-lg btn-primary btn-block')); ?>
&lt;?php echo form_close(); ?>
&lt;p>Don't have an account? Click to &lt;a href="&lt;?php echo site_url();?>main/register">Register&lt;/a>&lt;/p>
&lt;p>Click &lt;a href="&lt;?php echo site_url();?>main/forgot">here&lt;/a> if you forgot your password.&lt;/p>
&lt;/div></code></pre>



<p>Again, using CI&#8217;s form helper along with Bootstrap classes to make our form nice. We also have a link back to the &#8220;<a href="https://michaelsoriano.com/building-a-user-registration-system-using-the-codeigniter-framework-part-1/">Register</a>&#8221; page, which we covered in the first part of this tutorial. Finally, we have another link to the &#8220;Forgot&#8221; password link &#8211; which I&#8217;ll cover in Part 3.</p>



<p>Stay tuned.</p>
<p>The post <a href="https://michaelsoriano.com/building-a-user-registration-system-part-2-login-form/">Building a user registration system – Part 2: The Set Password and Login Forms</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/building-a-user-registration-system-part-2-login-form/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Building a user registration system &#8211; Part 1: The New User Form</title>
		<link>https://michaelsoriano.com/building-a-user-registration-system-part-1-new-user-form/</link>
					<comments>https://michaelsoriano.com/building-a-user-registration-system-part-1-new-user-form/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Fri, 21 Aug 2015 04:31:40 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Bootstrap]]></category>
		<category><![CDATA[Codeigniter]]></category>
		<category><![CDATA[MVC]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=5091</guid>

					<description><![CDATA[<p>Almost every website will have some form of public and restricted area. WordPress for instance, has the admin side where you can create posts, manage plugins, install themes etc. For this tutorial, we are going to create a similar mechanism. One that will restrict users from accessing sections of the site. We will create a [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/building-a-user-registration-system-part-1-new-user-form/">Building a user registration system &#8211; Part 1: The New User Form</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Almost every website will have some form of public and restricted area. WordPress for instance, has the admin side where you can create posts, manage plugins, install themes etc. For this tutorial, we are going to create a similar mechanism. </p>



<p>One that will restrict users from accessing sections of the site. We will create a system that will allow them to create their own account, reset their password and even update their profile.</p>



<p><strong>Update 8/13/2018:&nbsp;</strong>Added the entire CI application in the repo, allowing faster setup and debug. CI version is 3.0.2 The setup steps below might not be necessary for usage.</p>



<p><strong>Update 9/5/2016: </strong> Updated flaw in token creation and token checking for better security. Thanks to <a href="https://michaelsoriano.com/building-a-user-registration-system-part-3-password-reset/#comment-36867">comment by Mohammad</a> and his findings.</p>



<p><strong>Update 7/20/2016: </strong> Added index.php file to the views directory. This is the view that is being used once a successful login is processed.</p>



<p><a href="https://github.com/michaelsoriano/user-registration-codeigniter">View in Github</a></p>



<p><img decoding="async" width="659" height="400" class="alignnone size-full wp-image-5974" src="https://michaelsoriano.com/wp-content/uploads/2015/08/user-reg.gif" alt="user-reg"><br></p>



<p>I&#8217;m going to assume that you are familiar with CodeIgniter, or other MVC frameworks. You don&#8217;t have to be an expert &#8211; just know enough that you will be able to follow along without me having to explain too much. We are also going to utilize Bootstrap &#8211; so our pages will look nice. Finally, the focus of this tutorial is learning how the process works. We&#8217;re not really here to look at design patterns, performance or database design.</p>



<p>So ready to get started? Roll up your sleeves and let&#8217;s start writing.</p>



<h3 class="wp-block-heading">Get things setup</h3>



<p>So obviously we&#8217;re going to need to store data &#8211; so we need a database. We will need a table that will house our users. Below is the SQL code to get you up and running. I&#8217;m calling the database &#8220;user-registration&#8221; &#8211; which is a stupid name actually. Name yours anything you want.</p>



<pre class="wp-block-code"><code lang="sql" class="language-sql">CREATE DATABASE IF NOT EXISTS `user-registration` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `user-registration`;

CREATE TABLE IF NOT EXISTS `ci_sessions` (
  `id` varchar(40) NOT NULL,
  `ip_address` varchar(45) NOT NULL,
  `timestamp` int(10) unsigned NOT NULL DEFAULT '0',
  `data` blob NOT NULL,
  PRIMARY KEY (`id`),
  KEY `ci_sessions_timestamp` (`timestamp`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `tokens` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `token` varchar(255) NOT NULL,
  `user_id` int(10) NOT NULL,
  `created` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=26 ;

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `email` varchar(100) NOT NULL,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `role` varchar(10) NOT NULL,
  `password` text NOT NULL,
  `last_login` varchar(100) NOT NULL,
  `status` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=42 ;
</code></pre>



<p>We&#8217;re going to use <a href="https://github.com/bcit-ci/CodeIgniter/archive/3.0.2.zip">CodeIgniter 3.0.2</a>. Download and install in your web server.<br>In config &gt; config.php add the two lines below. I&#8217;ll explain these later.</p>



<pre class="wp-block-code"><code lang="php" class="language-php">$config['roles'] = array('subscriber', 'admin');
$config['status'] = array('pending', 'approved');</code></pre>



<p>Open database.php, and add your database credentials. It would be something like:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">$db['default'] = array(
	'dsn'	=&gt; '',
	'hostname' =&gt; 'localhost',
	'username' =&gt; 'root',
	'password' =&gt; '',
	'database' =&gt; 'user-registration',
	... //additional stuff here...
);</code></pre>



<p>Create a new controller named Main.php and a model, name it User_model.php. In the next sections, we will tie these things together.</p>



<p>But first let&#8217;s look at the workflow of our system:<br><img decoding="async" width="383" height="500" class="alignnone size-full wp-image-5099" src="https://michaelsoriano.com/wp-content/uploads/2015/08/process-user-reg.jpg" alt="process-user-reg" srcset="https://michaelsoriano.com/wp-content/uploads/2015/08/process-user-reg.jpg 383w, https://michaelsoriano.com/wp-content/uploads/2015/08/process-user-reg-230x300.jpg 230w" sizes="(max-width: 383px) 100vw, 383px" /><br></p>



<p>So our first step is the registration form. Users fill out this form which will only consist of their name and email. This will write a record to our database &#8211; but the account will only be in &#8220;pending&#8221; status. This will also trigger an email containing a token (which expires in a day), when clicked &#8211; will allow the user to finish the registration process. This form will have a password and password confirmation. This will update the record &#8211; and make the account &#8220;active&#8221;.</p>



<p>We will automatically login the user, but now that they have an account &#8211; they can actually utilize the login and reset password form.</p>



<p>It also makes sense for us to build the pages in this exact order. So we got: 1) register 2) complete 3) login 4) forgot password.</p>



<p>So inside our routes.php, add the default controller to ours:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">$route['default_controller'] = 'main';</code></pre>



<p>Also, let&#8217;s setup our autoload.php:</p>



<pre class="wp-block-code"><code lang="JavaScript" class="language-JavaScript">$autoload['helper'] = array('url');
$autoload['libraries'] = array('session');</code></pre>



<p>Now we can move forward.</p>



<h3 class="wp-block-heading">The Registration</h3>



<p>So the very first thing we need is the HTML that contains our form. Let&#8217;s create a new file called &#8220;register.php&#8221; and put it in our &#8220;views&#8221; folder. Add the code below:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">&lt;div class="col-lg-4 col-lg-offset-4">
    &lt;h2>Hello There&lt;/h2>
    &lt;h5>Please enter the required information below.&lt;/h5>
&lt;?php
    $fattr = array('class' => 'form-signin');
    echo form_open('/main/register', $fattr); ?>
    &lt;div class="form-group">
      &lt;?php echo form_input(array('name'=>'firstname', 'id'=> 'firstname', 'placeholder'=>'First Name', 'class'=>'form-control', 'value' => set_value('firstname'))); ?>
      &lt;?php echo form_error('firstname');?>
    &lt;/div>
    &lt;div class="form-group">
      &lt;?php echo form_input(array('name'=>'lastname', 'id'=> 'lastname', 'placeholder'=>'Last Name', 'class'=>'form-control', 'value'=> set_value('lastname'))); ?>
      &lt;?php echo form_error('lastname');?>
    &lt;/div>
    &lt;div class="form-group">
      &lt;?php echo form_input(array('name'=>'email', 'id'=> 'email', 'placeholder'=>'Email', 'class'=>'form-control', 'value'=> set_value('email'))); ?>
      &lt;?php echo form_error('email');?>
    &lt;/div>
    &lt;?php echo form_submit(array('value'=>'Sign up', 'class'=>'btn btn-lg btn-primary btn-block')); ?>
    &lt;?php echo form_close(); ?>
&lt;/div></code></pre>



<p>Note that I&#8217;m not going to go through what goes in our header and footer template because it&#8217;s irrelevant to this tutorial. Just know that it&#8217;s basic HTML, along with a link to Bootstrap CSS. Our markup above is a mix of PHP and HTML. This is using CodeIgniter&#8217;s Form Class &#8211; which makes it real easy to do validation and data filter and sanitation.</p>



<p>So in our Main controller, let&#8217;s add a constructor and include the necessary components for our class. We&#8217;ll also set up our status and roles arrays inside this constructor:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">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('&lt;div class="error">', '&lt;/div>');
            $this->status = $this->config->item('status');
            $this->roles = $this->config->item('roles');</code></pre>



<p>So we&#8217;re loading our model &#8220;User_model&#8221; by default, the &#8220;form_validation&#8221; library and setting some HTML for our form errors. You&#8217;ll also notice the 2 properties (status and roles) &#8211; which grabs it from &#8220;$this->config&#8221;. Remember in our config file &#8211; we created 2 arrays? We&#8217;re simply outputting it here for easy access.</p>



<p>Now I know you&#8217;re saying this is better if these entries was in their own table in the database. Again, this is not a tutorial on database design. We&#8217;re simply doing it this way because it is not our focus. Let&#8217;s continue with our &#8220;register&#8221; method:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">public function register()
        {
            $this->form_validation->set_rules('firstname', 'First Name', 'required');
            $this->form_validation->set_rules('lastname', 'Last Name', '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', 'User email already exists');
                    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 = $this->base64url_encode($token);
                    $url = site_url() . 'main/complete/token/' . $qstring;
                    $link = '' . $url . '';
                    $message = '';
                    $message .= 'You have signed up with our website
';
                    $message .= 'Please click: ' . $link;
                    echo $message; //send this in email
                    exit;
                };
            }
        }</code></pre>



<p>Alright, plenty of going on up there. So the validation rules are setup initially. Our form contains 3 fields: Last name, First name and email. They&#8217;re all required fields, plus the email address must be in valid format.</p>



<p>You will notice in the block where our form is validated, we&#8217;re checking &#8220;isDuplicate()&#8221; from our model: $this->user_model. This is so that we won&#8217;t have duplicate records of the same email. Remember, we are using their email address as their username. </p>



<p>So if it&#8217;s a duplicate &#8211; we simply use CodeIgniter&#8217;s set_flashdata() and redirect them to the login page (which is not built yet).</p>



<p>If the email address is good, we continue by cleaning up the $_POST array. Notice that we have 2 methods right after the cleaning: insertUser() and insertToken(). So we write the record to our database, then we create a new token (let&#8217;s quickly run this SQL so we have this token table).</p>



<pre class="wp-block-code"><code lang="sql" class="language-sql">CREATE TABLE IF NOT EXISTS `tokens` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `token` varchar(255) NOT NULL,
  `user_id` int(10) NOT NULL,
  `created` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=26 ;</code></pre>



<p>Another thing, you will also see that we&#8217;re using a local method called &#8220;<a href="http://php.net/manual/en/function.base64-encode.php#103849">base64url_encode()</a>&#8221; &#8211; which is a way of outputting base64 code &#8211; that is in a web safe format. So in our controller, you can add these two methods in the bottom. Think of them as local &#8220;helper&#8221; methods.</p>



<pre class="wp-block-code"><code lang="php" class="language-php">public function base64url_encode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
public function base64url_decode($data) {
    return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}</code></pre>



<p>I am not putting them in a the &#8220;helpers&#8221; for CI &#8211; because these methods are only to be used in controllers &#8211; since they are &#8220;URL&#8221; related. And as you can see, we only have one controller. But as your application grows, and you have many controllers, it&#8217;s best to move this into a real CI Helper.<br>Finally, we create our final URL, to our &#8220;complete&#8221; action and echo it out.&nbsp;<strong>In production, this will be done through an email, in HTML format.</strong></p>



<h3 class="wp-block-heading"><strong>Some Back-end Stuff</strong></h3>



<p>Our model &#8220;User_model&#8221; is empty. Let&#8217;s go ahead and fill it up. We need 3 methods for our register to work remember? It&#8217;s 1) isDuplicate(), 2) insertUser() and insertToken(). First let&#8217;s create a constructor with our roles and status arrays:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">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 . $user_id;
    }</code></pre>



<p>So judging from the method names &#8211; they&#8217;re pretty self explanatory correct? Also, if you&#8217;ve worked with CodeIgniter before, you&#8217;ll notice the syntax of interacting with the database. It used to be called &#8220;active record&#8221;, which is now the <a href="http://www.codeigniter.com/user_guide/database/query_builder.html">Query Builder</a> class. Makes it real easy for non DBA&#8217;s like me to write queries.</p>



<p>The three methods all return either an array or a string on success, and &#8220;false&#8221; on failure. The return values are handled accordingly in our controller methods discussed previously. Pay token is simply a random number that we create and insert into the database. This token has an accompanying user id and a time stamp in the same row. This makes it possible for us to fetch the user, and find if it&#8217;s a valid request, in the appropriate time frame.</p>



<p>Let&#8217;s break it here for now. We have plenty more to come in the next part(s).</p>
<p>The post <a href="https://michaelsoriano.com/building-a-user-registration-system-part-1-new-user-form/">Building a user registration system &#8211; Part 1: The New User Form</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/building-a-user-registration-system-part-1-new-user-form/feed/</wfw:commentRss>
			<slash:comments>54</slash:comments>
		
		
			</item>
		<item>
		<title>Let&#8217;s create a wrapper for the Captcha helper in Codeigniter</title>
		<link>https://michaelsoriano.com/lets-create-a-wrapper-for-captcha-in-codeigniter/</link>
					<comments>https://michaelsoriano.com/lets-create-a-wrapper-for-captcha-in-codeigniter/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Fri, 08 Mar 2013 04:09:55 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Codeigniter]]></category>
		<category><![CDATA[OOP]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=3176</guid>

					<description><![CDATA[<p>I needed to create a couple of forms for my latest project using the Codeigniter (CI) framework. For those who have worked with CI before, it has many neat classes built in &#8211; including Captcha. Captcha is the bot prevention mechanism you see in many web forms. Bot prevention meaning &#8211; you have to be [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/lets-create-a-wrapper-for-captcha-in-codeigniter/">Let&#8217;s create a wrapper for the Captcha helper in Codeigniter</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I needed to create a couple of forms for my latest project using the Codeigniter (CI) framework. For those who have worked with CI before, it has many neat classes built in &#8211; including Captcha. Captcha is the bot prevention mechanism you see in many web forms. Bot prevention meaning &#8211; you have to be human to actually read the letters in the image.</p>
<p><img decoding="async" class="alignnone size-full wp-image-7759" src="https://michaelsoriano.com/wp-content/uploads/2022/07/codeigniter.png" alt="" width="419" height="190" srcset="https://michaelsoriano.com/wp-content/uploads/2022/07/codeigniter.png 419w, https://michaelsoriano.com/wp-content/uploads/2022/07/codeigniter-300x136.png 300w" sizes="(max-width: 419px) 100vw, 419px" /></p>
<p>These letters have to be submitted to the web server, check if the values match. If it does, then process the information&#8230; or else, you must be a bot.<br />
As mentioned, CI has already done the leg work in creating the fuzzy image with the letters. This is called the <a href="http://ellislab.com/codeigniter/user-guide/helpers/captcha_helper.html">Captcha helper</a>. All you need to do is pass an array of options then voila! Your image is created. This tutorial will teach you how to wrap this functionality in our own class, so additional methods can be hooked up to it. This will make our wrapper encapsulated and reusable for as many forms as we need within our application.<br />
Note that I&#8217;m assuming that you&#8217;ve worked with CI before, or have experience with MVC, or even just object oriented programming. Ready to get started? Let&#8217;s begin:<br />
In our application/libraries folder, create a new file and name it <strong>Mycaptcha.php</strong>. Let&#8217;s create our class and name it Mycaptcha. Inside, let&#8217;s define a couple of variables for later use, add our constructor method which creates $CI. $CI is to ensure that we&#8217;re dealing with the same object we use from within our controllers.</p>
<pre>class Mycaptcha {
    public $word = '';
    public $ci = '';
    public function __construct() {
        $CI = &amp; get_instance();
        $CI-&gt;load-&gt;helper('captcha');
        $this-&gt;ci = $CI;
    }
}
</pre>
<p>Next, let&#8217;s create a method to create the random words in the image.</p>
<pre>public function createWord(){
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $word = '';
        for ($a = 0; $a &lt;= 5; $a++) {
            $b = rand(0, strlen($chars) - 1);
            $word .= $chars[$b];
        }
        $this-&gt;word = $word;
        return $this;
}
</pre>
<p>Now we have 2 properties accessible throughout our class (ci and word). Let&#8217;s go ahead and create the Captcha image using CI&#8217;s helper:</p>
<pre>public function createCaptcha(){
        $cap = array(
            'word' =&gt; $this-&gt;word,
            'img_path' =&gt; './httpdocs/captcha/', //this is your directory
            'img_url' =&gt; base_url() . 'httpdocs/captcha/',
            'img_width' =&gt; '150',
            'img_height' =&gt; '30',
            'expiration' =&gt; '7200'
        );
        $captchaOutput = create_captcha($cap);
        $this-&gt;ci-&gt;session-&gt;set_userdata(array('word'=&gt;$this-&gt;word, 'image' =&gt; $captchaOutput['time'].'.jpg')); //set data to session for compare
        return $captchaOutput['image'];
    }
</pre>
<p>Notice that we&#8217;re using the 2 properties that I mentioned. Also, make sure you have a folder with write permissions somewhere in your application. Above &#8211; I have it in &#8216;./httpdocs/captcha/&#8217; &#8211; which goes outside of our application folder. This is where the images will be saved. Another thing to notice here &#8211; I&#8217;m saving the word and the jpg name in session using CI&#8217;s session class (line 13 above). This will make it easier for us to check the value for form submission and have the image name as well (for cleanup).<br />
Our last method is to delete the image that we&#8217;ve created. The code is below:</p>
<pre>public function deleteImage(){
        if(isset($this-&gt;ci-&gt;session-&gt;userdata['image'])){
            $lastImage = FCPATH . "httpdocs/captcha/" . $this-&gt;ci-&gt;session-&gt;userdata['image'];
            if(file_exists($lastImage)){
                unlink($lastImage);
            }
        }
        return $this;
    }
</pre>
<h3>Adding Captcha to Form Validation</h3>
<p>Now we have our class, we need a way to check the values against our form field. Let&#8217;s create a new file and call it <strong>MY_Form_validation.php</strong> and save it in libraries folder. Here, we are extending the form validation class in CI.</p>
<pre>class MY_Form_validation extends CI_Form_validation {
public function validate_captcha($word)
    {
         $CI = &amp; get_instance();
         if(empty($word) || $word != $CI-&gt;session-&gt;userdata['word']){
            $CI-&gt;form_validation-&gt;set_message('validate_captcha', 'The letters you entered do not match the image.');
            return FALSE;
         }else{
             return TRUE;
         }
    }
}
</pre>
<p>The method above simply checks the parameter ($word) against the value set in our session (from our class). It also set an error message so we can present it nicely. Finally, let&#8217;s get to our controller to make it all stick.</p>
<pre>$this-&gt;form_validation
        -&gt;set_rules('captcha', 'Captcha', 'required|validate_captcha');
        //above is our custom validation
$this-&gt;load-&gt;library('mycaptcha'); //this is our wrapper
if ($this-&gt;form_validation-&gt;run() == FALSE) {
            $data['captcha'] = $this-&gt;mycaptcha
                    -&gt;deleteImage() //these are the 3 methods
                    -&gt;createWord()
                    -&gt;createCaptcha();
            $this-&gt;load-&gt;view('YOURVIEW.php', $data);
        } else {
            $this-&gt;mycaptcha-&gt;deleteImage(); //delete image again
            $this-&gt;session-&gt;set_flashdata(array('message' =&gt; 'Your message was sent successfully', 'type' =&gt; 'success'));
            redirect('YOURSUCCESSPAGE.php');
        }
</pre>
<p>As you see, we kept our controller straight to the point. We pass our &#8216;validate_captcha&#8217; in CI&#8217;s set rules, along with the input field name (line 1). We load our wrapper, runs the validation and the 3 methods from our class. Notice deleteImage() runs in the else clause as well? That&#8217;s because we delete the image even if it&#8217;s successful to keep our directory clean.<br />
All we have to do is call it in our form like so:</p>
<pre><label for="captcha">Enter the Letters Below:</label>
<!--?php echo $captcha; ?-->
<input name="captcha" type="text" />
<!--?php echo form_error('captcha'); ?-->
</pre>
<h3>Conclusion</h3>
<p>Our wrapper can be now reused in all our forms. I especially like that in our controller, all we need to do is:<br />
<strong>$this-&gt;mycaptcha-&gt;deleteImage()-&gt;createWord()-&gt;createCaptcha()</strong> &#8211; which will run all our methods fluently.<br />
Questions? Please feel free to leave them below.</p>
<p>The post <a href="https://michaelsoriano.com/lets-create-a-wrapper-for-captcha-in-codeigniter/">Let&#8217;s create a wrapper for the Captcha helper in Codeigniter</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/lets-create-a-wrapper-for-captcha-in-codeigniter/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
	</channel>
</rss>
