<?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>PHP Archives - Michael Soriano</title>
	<atom:link href="https://michaelsoriano.com/category/php/feed/" rel="self" type="application/rss+xml" />
	<link>https://michaelsoriano.com/category/php/</link>
	<description>I turn code into captivating user experiences for the web</description>
	<lastBuildDate>Mon, 08 Jul 2024 18:28:35 +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>Laracasts.com: a gold mine of content for Web Developers</title>
		<link>https://michaelsoriano.com/laracasts-com-a-gold-mine-of-content-for-web-developers/</link>
					<comments>https://michaelsoriano.com/laracasts-com-a-gold-mine-of-content-for-web-developers/#respond</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Mon, 08 Jul 2024 18:26:44 +0000</pubDate>
				<category><![CDATA[General]]></category>
		<category><![CDATA[PHP]]></category>
		<guid isPermaLink="false">https://michaelsoriano.com/?p=8127</guid>

					<description><![CDATA[<p>I&#8217;ve been a Software Engineer for many years. And for the past few, JavaScript has been emerging with newer, better and shinier things. But like many others, I&#8217;ve been having a little bit of JavaScript fatigue. Lately, I&#8217;ve been looking to other frameworks with more stability. Something that I rely on &#8211; that will work [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/laracasts-com-a-gold-mine-of-content-for-web-developers/">Laracasts.com: a gold mine of content for Web Developers</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>I&#8217;ve been a Software Engineer for many years. And for the past few, JavaScript has been emerging with newer, better and shinier things. But like many others, I&#8217;ve been having a little bit of <a href="https://auth0.com/blog/how-to-manage-javascript-fatigue/">JavaScript fatigue</a>. Lately, I&#8217;ve been looking to other frameworks with more stability. Something that I rely on &#8211; that will work for years to come. </p>



<h3 class="wp-block-heading">Back to Roots</h3>



<p>PHP was my first real programming language. And Laravel is built with PHP. I&#8217;ve always heard of Laravel, but never used it. I&#8217;ve watched many videos about how good it is, installed a sample application &#8211; and was sold. </p>



<p>I want to learn more &#8211; so I signed up for <a href="https://laracasts.com/referral/Michaelsoriano" rel="nofollow">Laracasts</a>. If you’re a web developer, suffering from JS Fatigue, and want to learn Laravel &#8211; Laracasts.com is like striking gold.</p>



<figure class="wp-block-image size-large"><a href="https://laracasts.com/referral/Michaelsoriano" rel="nofollow"><img fetchpriority="high" decoding="async" width="1024" height="584" src="https://michaelsoriano.com/wp-content/uploads/2024/07/image-1024x584.jpg" alt="Power to the modern developer" class="wp-image-8140" srcset="https://michaelsoriano.com/wp-content/uploads/2024/07/image-1024x584.jpg 1024w, https://michaelsoriano.com/wp-content/uploads/2024/07/image-300x171.jpg 300w, https://michaelsoriano.com/wp-content/uploads/2024/07/image-768x438.jpg 768w, https://michaelsoriano.com/wp-content/uploads/2024/07/image.jpg 1117w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></figure>



<p>Top-notch tutorials and lessons. I, for one have signed up on many premium bootcamps and tutorial websites. So far, Laracasts is the best I&#8217;ve seen. Let me explain. </p>



<h3 class="wp-block-heading"><strong>Talented Instructors &#8211; <strong>Jeffrey Way</strong></strong></h3>



<p>Jeffrey Way, the main instructor, has a unique gift for making complex topics easy to understand. His explanations are clear and straightforward, making even the most daunting subjects feel manageable. He has a way of teaching &#8211; that reminds me of how elementary school was &#8211; but for a modern, experienced developer. </p>



<p>Plus, he presents everything in such an engaging way that you’re hooked from the first video. I especially like how he organizes his content &#8211; from inception to conception. Jeffrey Way is as good as it gets.</p>



<p>In addition, I&#8217;ve seen a couple of series on Inertia, React and APIs &#8211; and the instructors were also pretty good. Not the same style as Jeffrey &#8211; but good nonetheless. </p>



<h3 class="wp-block-heading"><strong>Structured Learning Paths for Laravel and More</strong></h3>



<p>One of my favorite features is the structured learning paths. These pathways are like having a personal guide through the vast world of web development. They ensure you build a solid foundation before moving on to more advanced topics. This is incredibly helpful if you’re new to coding or trying to learn a new framework like Laravel.</p>



<p>There is also small bits of lessons called &#8220;<strong><a href="https://laracasts.com/referral/Michaelsoriano" rel="nofollow">Larabits</a></strong>&#8220;. These are quick how-to videos, that&#8217;s not necessarily tied to a learning path. Just fast paced watch and go type of tut. </p>



<h3 class="wp-block-heading"><strong>Supportive Community</strong></h3>



<p>The community at Laracasts is fantastic. The forums are buzzing with activity and full of people ready to help out with any questions you might have about Laravel tutorials or other topics. It&#8217;s great to be part of a community where you can share knowledge and get support from fellow learners. </p>



<p>Plus, Jeffrey Way is actively involved, which adds a personal touch to the experience.</p>



<p>In addition, each video has a comments area &#8211; where you can post comments &#8211; and the community is also very responsive. This helps when you&#8217;re stuck in part of the video, commenting will get you &#8220;unstuck&#8221; real quick.</p>



<h3 class="wp-block-heading"><strong>Diverse Range of Topics Beyond Laravel</strong></h3>



<p>While Laracasts is famous for its Laravel tutorials, it doesn’t stop there. The site offers in-depth tutorials on JavaScript, Vue, React, testing, and general web development practices. As mentioned above &#8211; the instructors and the way they teach the course is paramount. So the topics can vary &#8211; and you get the same high quality tutorial &#8211; which is a good deal.</p>



<figure class="wp-block-image size-full"><a href="https://laracasts.com/referral/Michaelsoriano" rel="nofollow"><img decoding="async" width="851" height="810" src="https://michaelsoriano.com/wp-content/uploads/2024/07/image-1.png" alt="Laracasts Topics" class="wp-image-8137" srcset="https://michaelsoriano.com/wp-content/uploads/2024/07/image-1.png 851w, https://michaelsoriano.com/wp-content/uploads/2024/07/image-1-300x286.png 300w, https://michaelsoriano.com/wp-content/uploads/2024/07/image-1-768x731.png 768w" sizes="(max-width: 851px) 100vw, 851px" /></a></figure>



<p>So whether you&#8217;re looking to dive deep into a specific framework or broaden your overall skill set, Laracasts has you covered. I was even surprised to see GraphQL, CSS and Webpack in there &#8211; its not just backend stuff!</p>



<h3 class="wp-block-heading"><strong>Final Thoughts</strong></h3>



<p>Laracasts.com is a must-have resource for anyone serious about web development, especially if you want to master Laravel tutorials. Its combination of excellent instructors that produce high-quality content. The strong community that you become part of &#8211; is truly indispensable. You get to learn everything about Laravel, but also other skills as well. In addition, the library is constantly updated, with new paths, technologies and lessons.  </p>



<p>Whether you’re aiming to become a Laravel expert, improve your JavaScript skills, or just become a better developer overall, <a href="https://laracasts.com/referral/Michaelsoriano" rel="nofollow">Laracasts</a> is an investment you won’t regret.</p>
<p>The post <a href="https://michaelsoriano.com/laracasts-com-a-gold-mine-of-content-for-web-developers/">Laracasts.com: a gold mine of content for Web Developers</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/laracasts-com-a-gold-mine-of-content-for-web-developers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to create an Accordion Block using React and WordPress&#8217; Block API</title>
		<link>https://michaelsoriano.com/how-to-create-an-accordion-block-using-react-and-wordpress-block-api/</link>
					<comments>https://michaelsoriano.com/how-to-create-an-accordion-block-using-react-and-wordpress-block-api/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Mon, 06 Nov 2023 23:03:50 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[WordPress]]></category>
		<guid isPermaLink="false">https://michaelsoriano.com/?p=7969</guid>

					<description><![CDATA[<p>I was tasked with creating a custom component for our public website which runs on WordPress. Most commonly known as an &#8220;Accordion&#8220;, it is a section of a page where you can have a title and an expandable and collapsible directly underneath it. Usually a list of these items are blocked together &#8211; forming an [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/how-to-create-an-accordion-block-using-react-and-wordpress-block-api/">How to create an Accordion Block using React and WordPress&#8217; Block API</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>I was tasked with creating a custom component for our public website which runs on WordPress. Most commonly known as an &#8220;<em>Accordion</em>&#8220;, it is a section of a page where you can have a title and an expandable and collapsible directly underneath it. Usually a list of these items are blocked together &#8211; forming an &#8220;accordion&#8221; like pattern. </p>



<p>In HTML, this is easily achieved by the &#8220;<a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details"><strong>Details</strong></a>&#8221; element. But of course, our users cannot write HTML. Similarly, a default block already exists in WordPress called &#8220;<em>details</em>&#8220;. The problem with this one is that our users do not find it intuitive. Also, they want to limit the formatting of the contents for each item. </p>



<figure class="wp-block-image size-large border"><img decoding="async" width="1024" height="510" src="https://michaelsoriano.com/wp-content/uploads/2023/11/image-1024x510.png" alt="" class="wp-image-7973" srcset="https://michaelsoriano.com/wp-content/uploads/2023/11/image-1024x510.png 1024w, https://michaelsoriano.com/wp-content/uploads/2023/11/image-300x149.png 300w, https://michaelsoriano.com/wp-content/uploads/2023/11/image-768x383.png 768w, https://michaelsoriano.com/wp-content/uploads/2023/11/image-1536x765.png 1536w, https://michaelsoriano.com/wp-content/uploads/2023/11/image.png 1662w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>You see how each item is contained within a big block. A button will add a title/content pair to the list &#8211; along with a checkbox that allows for the section to be expanded or collapsed by default. </p>



<h3 class="wp-block-heading">Register the Block </h3>



<p>This is the &#8220;housekeeping&#8221; part of the codebase. There is a PHP part of this process &#8211; and it really depends if you&#8217;re putting this in a plugin or a theme. But main function is below:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">register_block_type(
    'namepsace/my-blocks-accordion',  // Block name with namespace
    [
        'style' => 'accordion-style',  
        'editor_style' => 'accordion-edit-style', 
        'editor_script' => 'accordion-js'  
    ]
);
...</code></pre>



<p>Also, there are other parts of this such as enqueuing the styles and scripts for your blocks &#8211; which I&#8217;m not going to cover here. We&#8217;re mostly focusing on the &#8220;client&#8221; or JS side of things. </p>



<p>To read more about registering blocks in WordPress &#8211; see the <a href="https://developer.wordpress.org/reference/functions/register_block_type/">codex</a>.  </p>



<p>For the JavaScript, create a file called <em>index.js</em> and start with the <strong>registerBlockType</strong>() function. If you&#8217;re not familiar with how to build blocks for WP &#8211; this is a good start <a href="https://developer.wordpress.org/block-editor/getting-started/create-block/block-anatomy/">Anatomy of a Block | Block Editor Handbook | WordPress Developer Resources</a>.</p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx">registerBlockType(
    'namespace/accordion', {
      title: __('Accordion'),  
      icon: 'list-view',
      category: 'my-blocks', 
      attributes : {
        items : { 
         type: 'array',
         default : []
     }
    ...
}</code></pre>



<p>Pay extra attention to the &#8220;<em>attributes</em>&#8221; object. This is the main &#8220;context&#8221; of our application. Notice that we want an array called &#8220;items&#8221; inside attributes &#8211; this is where we&#8217;ll manage our data.  </p>



<h3 class="wp-block-heading">The &#8220;Edit&#8221; Component</h3>



<p>So in Gutenberg Blocks, the two major components that we have to worry about is the &#8220;Edit&#8221; and &#8220;Save&#8221;. Edit is what you see during the editing of Posts or Pages. Let&#8217;s look at how to build this first &#8211; particularly the JSX section:</p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx">const { RichText } = wp.editor;  
const { __ } = wp.i18n;

...

title: __('Accordion'),  
icon: 'list-view',
category: 'my-blocks', 
attributes : {
   items : { 
     type: 'array',
     default : []
   }
},
edit ( {className, attributes, setAttributes} ) {

... 

return (
&lt;div>
{attributes.items &amp;&amp; attributes.items.length > 0 ? attributes.items.map((item,i) => {
return (
&lt;div>
    &lt;div className={`${className}-item-title-wrap`}>
    &lt;RichText   
        allowedFormats={[]}   
        tagName="div"     
        placeholder="Enter Title"               
        className={ `${className}-item-title` }
        value={ item.title }
        disableLineBreaks={ true }
        onChange={ val => updateItemTitle(val,i)}
    />
    &lt;label>
    &lt;input type="checkbox" data-index={i}
        checked={item.expand} 
        onChange={e=>updateItemExpand(e)} />
        Expanded
    &lt;/label>
    &lt;/div>
    &lt;RichText  
        placeholder="Enter Content"  
        allowedFormats={ ['core/bold','core/italic','core/link'] }    
        multiline="p"
        tagName="div"                    
        className={ `${className}-item-content` }
        value={item.content}
        onChange={ val => updateItemContent(val,i)}
    />
&lt;/div>
)
}) : null}
&lt;button 
    className={ `${className}-add-btn` } 
    onClick={addEmptyItem}>Add Accordion Item&lt;/button>
&lt;/div>
);

} //END EDIT</code></pre>



<p>The HTML above is the UI for our editors. Notice that we&#8217;re going through out &#8220;<em>items</em>&#8221; and outputting it for action. We&#8217;re using the built-in <strong>RichText</strong> component for our editable sections (title and content). RichText is awesome &#8211; <a href="https://developer.wordpress.org/block-editor/reference-guides/richtext/">find out</a> more about it. We&#8217;re also including a checkbox called <em>expanded</em> &#8211; that will allow our users to show the item expanded or collapsed. </p>



<h3 class="wp-block-heading">Adding Items</h3>



<p>When first using the block &#8211; all you see is a button that says &#8220;<em>Add Accordion Item</em>&#8220;. Clicking this button will execute below:</p>



<pre class="wp-block-code"><code lang="JavaScript" class="language-JavaScript">const addEmptyItem = () =&gt; {
    const items = [...attributes.items, {
      title : '', 
      content : '', 
      expand : true
    }];
   setAttributes({items})
}</code></pre>



<p>This will add an empty object to our Attributes Items array, allowing our users to be able to edit our RichText components. </p>



<h3 class="wp-block-heading">Click and Change Handlers</h3>



<p>If you look in our JSX, we&#8217;ve mapped our inputs to event handlers. Add the code below&#8221;</p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx">const updateItemExpand= (e) => {
    const items = attributes.items.slice();
    const index = e.target.attributes.getNamedItem('data-index').value;
    items[index].expand = e.target.checked;
    setAttributes({items})
}
const updateItemTitle = (title,i) => {
    const items = attributes.items.slice();
    items[i].title = title;
    setAttributes({items})
}
const updateItemContent = (content,i) => {
    const items = attributes.items.slice();
    items[i].content = content;
    setAttributes({items})
}</code></pre>



<p>The function names are pretty self explanatory. All we&#8217;re doing is manipulating the data in our Attributes. Also notice the <strong>setAttributes</strong>() function we&#8217;re using in each function. This is a &#8220;setter&#8221; that is very similar to React&#8217;s <em>useState</em> setters.  </p>



<p>With all that in place, our Accordion block is ready for editing:</p>



<figure class="wp-block-image size-full border wp-duotone-unset-1"><img decoding="async" width="923" height="520" src="https://michaelsoriano.com/wp-content/uploads/2023/11/accordion-block-edit.gif" alt="" class="wp-image-7971"/></figure>



<p>Typing &#8220;<em>/accordion</em>&#8221; will insert our block &#8211; ready for editing. </p>



<h3 class="wp-block-heading">The &#8220;Save&#8221; Component</h3>



<p>This is simply JSX that outputs our HTML for the public users. The code for this is quite simple &#8211; we&#8217;re simply using &#8220;<strong>details</strong>&#8221; and &#8220;<strong>summary</strong>&#8220;. This automatically has the expand and collapse functionality out of the box.</p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx">save( { attributes } ) {
    return (
        &lt;div>
        {attributes.items &amp;&amp; attributes.items.length > 0 ? (
            attributes.items.map(item => {
                return (
                    &lt;details open={item.expand}>
                    &lt;summary>{item.title}&lt;/summary>
                    &lt;div dangerouslySetInnerHTML={
                       {__html: item.content}
                    } /> 
                    &lt;/details>
                )
            })
        ) : null}
        &lt;/div>
        )
    } 
}</code></pre>



<p>Notice the use of <em>dangerouslySetInnerHTML</em> &#8211; because we&#8217;re outputting HTML content from WordPress. If this can be done in other ways leave a comment below. </p>



<p>Styling the output with some CSS:</p>



<pre class="wp-block-code"><code lang="css" class="language-css">.wp-block-my-blocks-accordion {
    margin-bottom: 25px;
}

.wp-block-my-blocks-accordion details > summary {
    background:url('/images/arrow-down.png') no-repeat;
    background-size: 13px;
    background-position-x: right;
    background-position-y: 10px;
    font-weight: 500;
    border-bottom:1px solid #ebebeb;
    margin-bottom: 10px;
    padding-bottom: 6px;
    cursor:pointer;
}
.wp-block-my-blocks-accordion details[open] > summary {
    background:url('images/arrow-up.png') no-repeat;
    background-size: 13px;
    background-position-x: right;
    background-position-y: 10px;
} 
.wp-block-my-blocks-accordion details > summary:hover {
    opacity: 0.6;
}  
.wp-block-my-blocks-accordion details > summary > * {
    display: inline;
}</code></pre>



<p>We&#8217;re simply overriding the default look of the details component &#8211; specifically the arrows. I prefer to see them in the right instead of left. Also, adding a subtle border to make it look better. </p>



<p>And with that in place &#8211; it should look like below when the post is saved:</p>



<figure class="wp-block-image size-full border"><img decoding="async" width="788" height="494" src="https://michaelsoriano.com/wp-content/uploads/2023/11/accordion-block-view.gif" alt="" class="wp-image-7972"/></figure>



<p>There you have it. We&#8217;ve just made our own custom Gutenberg block. This was pretty fun to build &#8211; and learning about the Block API is quite straightforward. It&#8217;s very much like classic React &#8211; but simpler.</p>



<p>Be sure to leave your thoughts below.</p>
<p>The post <a href="https://michaelsoriano.com/how-to-create-an-accordion-block-using-react-and-wordpress-block-api/">How to create an Accordion Block using React and WordPress&#8217; Block API</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/how-to-create-an-accordion-block-using-react-and-wordpress-block-api/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Get all posts from WordPress REST API</title>
		<link>https://michaelsoriano.com/get-all-posts-from-wordpress-rest-api/</link>
					<comments>https://michaelsoriano.com/get-all-posts-from-wordpress-rest-api/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Thu, 22 Jun 2017 16:18:40 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[WordPress]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=6293</guid>

					<description><![CDATA[<p>As you may know, WP REST API has a limit of 100 records per call. This is what it says in the API Docs:Now this may be enough for some people, but what if you need to get ALL of them. Here are two solutions that I came up with. 1. Using PHP We&#8217;re using [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/get-all-posts-from-wordpress-rest-api/">Get all posts from WordPress REST API</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>As you may know, WP REST API has a limit of 100 records per call. This is what it says in the <a href="https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/">API Docs</a>:<br><img decoding="async" class="alignnone size-full wp-image-6361" src="https://michaelsoriano.com/wp-content/uploads/2017/06/wp-cap.png" alt="cap" width="643" height="209" srcset="https://michaelsoriano.com/wp-content/uploads/2017/06/wp-cap.png 643w, https://michaelsoriano.com/wp-content/uploads/2017/06/wp-cap-300x98.png 300w" sizes="(max-width: 643px) 100vw, 643px" /><br>Now this may be enough for some people, but what if you need to get ALL of them. Here are two solutions that I came up with.</p>



<h3 class="wp-block-heading">1. Using PHP</h3>



<p>We&#8217;re using PHP&#8217;s <a href="https://www.phpied.com/simultaneuos-http-requests-in-php-with-curl/">multi cURL</a>. This means that we are doing multiple REST calls, but doing them simultaneously. Meaning, the amount of time to do the requests &#8211; is not dependent on the number of calls you make (because they&#8217;re asynchronous).<br>So let&#8217;s begin. First in your functions.php, create a function:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">function getAllRecordsFromRest(){
   //ADD ALL CODE IN HERE...
}</code></pre>



<p>Inside your new function, is where we put the rest of our code.<br>Let&#8217;s figure out how many calls we need to make:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">$totalItems = wp_count_posts()-&gt;publish;
$callsToMake = ceil($totalItems/100);</code></pre>



<p>Let&#8217;s create an empty array and stuff it with the curl options:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">$ch = array();
for($i=0;$i&lt;$callsToMake;$i++){
    $page = $i + 1;
    $ch[$i] = curl_init(get_bloginfo('url').'/wp-json/wp/v2/posts?_embed&amp;per_page=100&amp;page='.$page);
    curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch[$i], CURLOPT_SSL_VERIFYPEER,  0);
}</code></pre>



<p>As you can see above, we&#8217;re simply looping through the $<strong>callsToMake</strong> variable, to add a $page as part of our querystring. Similar to a paging system. As part of our loop, we are passing the options for curl through <em>curl_setopt</em>().</p>



<p>Now for the calls:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">$mh = curl_multi_init();
        for($i=0;$i&lt;$callsToMake;$i++){
            curl_multi_add_handle($mh, $ch[$i]);
        }
        $running = null;
        do {
            curl_multi_exec($mh, $running);
        } while ($running);
        for($i=0;$i&lt;$callsToMake;$i++){
             if (!curl_errno($ch[$i])) {
                 $info = curl_getinfo($ch[$i]);
                 //error_log(print_r($info,true));
             }
            curl_multi_remove_handle($mh, $ch[$i]);
        }
        curl_multi_close($mh);
        $responses = array(); //array
        for($x=0;$x&lt;$callsToMake;$x++){
            $responses[$x] = json_decode(curl_multi_getcontent($ch[$x]));
        }
</code></pre>



<p>First we create a handle $mh &#8211; this is what curl uses to execute and initialize the class. We loop through our $callstoMake once more to add the handles to curl_multi_add_handle().<br>We do a do while, and execute curl. Now if if there is an error in any of the calls, we will get them in curl_getinfo().</p>



<p>Finally, we get all of the contents of our calls through curl_multi_getcontent(), and we stuff it in our newly created $responses array.</p>



<p>Now our $responses will look something like:</p>



<pre class="wp-block-code"><code lang="php" class="language-php">$responses[$response[0], $response[1], $response[2]]</code></pre>



<p>So we need to loop through them to create a big array of responses (in order).</p>



<p>So we do a final loop and do an <strong>array_push</strong>().</p>



<pre class="wp-block-code"><code lang="php" class="language-php">$final = array();
for($i=0;$i&lt;count($responses);$i++){
    for($x=0;$x&lt;count($responses[$i]);$x++){
       array_push($final,$responses[$i][$x] );
     }
}
return json_encode($final);</code></pre>



<p>Then, we return our array as a JSON string by doing json_encode($final).</p>



<p>Now all we have to do is call our PHP function &#8220;<strong>getAllRecordsFromRest</strong>()&#8221; and we should have all of our posts.</p>



<h3 class="wp-block-heading">2. Using JavaScript</h3>



<p>We also have the option of using JavaScript for our multiple calls. Let&#8217;s start by getting the number of calls in our functions.php file:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function getNumCalls(){
    $totalItems = wp_count_posts('posts')-&gt;publish;
    $callsToMake = ceil($totalItems/100);
    return $callsToMake;
}</code></pre>



<p>Now, in our header.php &#8211; let&#8217;s create a JavaScript variable that stores the number of calls to make &#8211; from the function that we created above:</p>



<pre class="wp-block-code"><code lang="markup" class="language-markup">&lt;script&gt;
    var numOfCalls = "&lt;?php echo getNumCalls(); ?&gt;";
&lt;/script&gt;</code></pre>



<p>Now, let&#8217;s create an array, that houses all of the responses, from our AJAX calls.</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript"> var requests = Array();
 for(var i=0; i&lt;numOfCalls; i++){
     var request = $.get('/wp-json/wp/v2/posts?_embed&amp;per_page=100&amp;page='+(i+1));
     requests.push(request);
 }</code></pre>



<p>We then to a &#8220;.when()&#8221; to fire our calls. And doing a console.log() on the arguments, we see the responses. This technique is described in my previous post <a href="https://michaelsoriano.com/working-with-jquerys-ajax-promises-and-deferred-objects/">Working with Promise and Deferred</a>.</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">$.when.apply($,requests).done(function(){
   console.log(arguments);
})</code></pre>



<p><img decoding="async" width="450" height="350" class="alignnone size-full wp-image-6355" src="https://michaelsoriano.com/wp-content/uploads/2017/06/using-js.png" alt="Using JS" srcset="https://michaelsoriano.com/wp-content/uploads/2017/06/using-js.png 450w, https://michaelsoriano.com/wp-content/uploads/2017/06/using-js-300x233.png 300w" sizes="(max-width: 450px) 100vw, 450px" /></p>



<p>Finally, let&#8217;s do a couple of for loops to merge the contents into one big array.</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">$.when.apply($,requests).done(function(){
    for(var i=0; i&lt;arguments.length; i++){
       for(var x=0; x&lt;arguments[i][0].length; x++){
            final.push(arguments[i][0][x]);
        }
    }
    console.log(final); //HERE ARE OUR RECORDS
}</code></pre>



<p>And that should do it. Using either of these techniques should overcome the 100 record limitation of pulling records from WordPress REST api.<br>&nbsp;</p>
<p>The post <a href="https://michaelsoriano.com/get-all-posts-from-wordpress-rest-api/">Get all posts from WordPress REST API</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/get-all-posts-from-wordpress-rest-api/feed/</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
			</item>
		<item>
		<title>Show number of posts out of total records  in WordPress</title>
		<link>https://michaelsoriano.com/show-number-of-posts-out-of-total-records-in-wordpress/</link>
					<comments>https://michaelsoriano.com/show-number-of-posts-out-of-total-records-in-wordpress/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Tue, 15 Mar 2016 02:59:48 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[WordPress]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=5540</guid>

					<description><![CDATA[<p>From time to time, I just look at my blogs and see what I can add to it to make it more appealing to the user. I&#8217;ve always admired those sites that tell you what number of posts a certain category has, and what number of posts it is currently showing. So I set out [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/show-number-of-posts-out-of-total-records-in-wordpress/">Show number of posts out of total records  in WordPress</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>From time to time, I just look at my blogs and see what I can add to it to make it more appealing to the user. I&#8217;ve always admired those sites that tell you what number of posts a certain category has, and what number of posts it is currently showing. So I set out to do just that.<br />
Since I haven&#8217;t written anything WordPress related for a while, I figured this would be good practice. What we&#8217;re writing is something like below:<br />
<img decoding="async" class="alignnone size-full wp-image-5542" src="https://michaelsoriano.com/wp-content/uploads/2016/03/numposts1.png" alt="numposts1" width="651" height="389" srcset="https://michaelsoriano.com/wp-content/uploads/2016/03/numposts1.png 651w, https://michaelsoriano.com/wp-content/uploads/2016/03/numposts1-300x179.png 300w" sizes="(max-width: 651px) 100vw, 651px" /><br />
You see, we want to show what posts are currently showing &#8211; out of how many total records. It&#8217;s not a hard task &#8211; since all we really need are 2 variables: the current total showing and the total number found.</p>
<h3>The $wp_query Object</h3>
<p>According to the <a href="https://codex.wordpress.org/Class_Reference/WP_Query">codex</a>, the WP_Query class &#8220;deals with the intricacies of a post&#8217;s (or page&#8217;s) request to a WordPress blog&#8221;. This means that WordPress has already done the heavy lifting when it comes to information needed when you query your posts. Information needed when building stuff like paging, queries, templates and meta data.<br />
In our case, we need the meta data &#8211; of the posts returned. So first off, open the index.php file in your theme directory and just outside the loop, add the code below:</p>
<pre>print_r($wp_query);exit;
</pre>
<p>What we&#8217;re doing is seeing what the <strong>$wp_query</strong> is holding. $wp_query is the object that is derived from the WP_Query class that we talked about above. You will see a long array of information that pertains to the current request. So say you&#8217;re in a certain category, this object will contain information about that category and the posts that it contains.<br />
So somewhere in this object lies the information we need. Let&#8217;s grab &#8220;post_count&#8221; and &#8220;found_posts&#8221;.<br />
<img decoding="async" class="alignnone size-full wp-image-5545" src="https://michaelsoriano.com/wp-content/uploads/2016/03/numposts2.png" alt="numposts2" width="466" height="592" srcset="https://michaelsoriano.com/wp-content/uploads/2016/03/numposts2.png 466w, https://michaelsoriano.com/wp-content/uploads/2016/03/numposts2-236x300.png 236w" sizes="(max-width: 466px) 100vw, 466px" /><br />
Now that we know the property names, we can go ahead and remove the print_r that we have.</p>
<h3>The Output</h3>
<p>This is as simple as it gets. All we need is to check if &#8220;post_count&#8221; is more than 0 and we can echo out our sentence. We can hard code the &#8220;1&#8221; since we&#8217;re always going to be showing at least 1 record.</p>
<pre><!--?php if($wp_query-&gt;post_count &gt; 0): ?-->
    Showing 1 through <!--?php echo $wp_query-&gt;post_count ?--> out of <!--?php echo $wp_query-&gt;found_posts; ?--> articles..
<!--?php endif; ?-->
</pre>
<p>The code above should work anywhere in your theme. It&#8217;s especially useful in your archive templates &#8211; so users can tell how many articles are in a specific category etc. It&#8217;s a good addition to your paging in the footer as well.<br />
To test it, try searching for something, or click on a category. The &#8220;found_posts&#8221; should depend on the current request, while the &#8220;post_count&#8221; depends on the limit that you have in your WordPress settings.<br />
And that&#8217;s it. Hopefully you can find this snippet useful in your theme somewhere. Please leave your comments below.</p>
<p>The post <a href="https://michaelsoriano.com/show-number-of-posts-out-of-total-records-in-wordpress/">Show number of posts out of total records  in WordPress</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/show-number-of-posts-out-of-total-records-in-wordpress/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<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 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 make a WordPress Widget that displays our Custom Post Types</title>
		<link>https://michaelsoriano.com/wordpress-widget-custom-post-types/</link>
					<comments>https://michaelsoriano.com/wordpress-widget-custom-post-types/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Fri, 23 Aug 2013 03:38:10 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[WordPress]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=3529</guid>

					<description><![CDATA[<p>So I had a question from one my readers: &#8220;How can I add a Latest Listing widget in the sidebar&#8220;, which really translates to &#8220;How do we create a WordPress Widget?&#8221; Well, a widget that pulls our Custom Post Types. So I did a bit of research, and it turns out &#8211; that it&#8217;s not [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/wordpress-widget-custom-post-types/">Let&#8217;s make a WordPress Widget that displays our Custom Post Types</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So I had a question from one my readers: &#8220;<em>How can I add a Latest Listing widget in the sidebar</em>&#8220;, which really translates to &#8220;<em>How do we create a WordPress Widget</em>?&#8221; Well, a widget that pulls our Custom Post Types. So I did a bit of research, and it turns out &#8211; that it&#8217;s not hard at all. We just need to know the basics of the <a href="http://codex.wordpress.org/Widgets_API">Widgets API</a>, plus a bit of PHP.<br />
This tutorial was written using <a href="http://fearlessflyer.com/manage-your-listings-with-realty-theme">Realty</a>, since it&#8217;s already using Custom Post Types for the House Listings. So I am trying to shoot 3 birds in one stone: 1) To answer my reader&#8217;s question, 2) to add some functionality to the theme, as well as 3) learn something new. Oh and to write this tutorial &#8211; I guess that would be 4 birds then.<br />
So ready to start coding? Also keep in mind that this will work with regular posts &#8211; not just custom post types. You will see what I&#8217;m talking about as we dive deeper. Let&#8217;s begin.</p>
<h6>Create the basic Widget</h6>
<p>In your functions.php file, write the following code:</p>
<pre>class Realty_Widget extends WP_Widget{
function __construct() {
	parent::__construct(
		'realty_widget', // Base ID
		'Realty Widget', // Name
		array('description' =&gt; __( 'Displays your latest listings. Outputs the post thumbnail, title and date per listing'))
	   );
}
function update($new_instance, $old_instance) {
	$instance = $old_instance;
	$instance['title'] = strip_tags($new_instance['title']);
	$instance['numberOfListings'] = strip_tags($new_instance['numberOfListings']);
	return $instance;
}
} //end class Realty_Widget
register_widget('Realty_Widget');
</pre>
<p>The above code sets up our widget class. It&#8217;s extending an already built class &#8211; called WP_Widget, which have methods that we need to override. These methods are: update(), form() and widget(). Don&#8217;t worry if you don&#8217;t know what that means exactly. It&#8217;s just the rules of creating widgets.<br />
Now, notice above that we have a method __construct() &#8211; which just register&#8217;s our widget id, a name and a description. We overrode another method update() &#8211; which just makes ensures that we&#8217;re passing the right values to our $instance array (also makes sure we&#8217;re using the correct calculated instance).<br />
So all we need to create is 2 more methods: form() and widget(). Let&#8217;s take care of that next.</p>
<h6>The form() method</h6>
<p>The method form() builds the form that we have in the admin section. What we&#8217;re building is a very simple form with 2 fields: a text field for the Widget title, and a drop down list for the number of listings we want to show:</p>
<pre>function form($instance) {
	if( $instance) {
		$title = esc_attr($instance['title']);
		$numberOfListings = esc_attr($instance['numberOfListings']);
	} else {
		$title = '';
		$numberOfListings = '';
	}
</pre>
<p><em>[code above has been truncated &#8211; due to syntax highlighting error]</em><br />
We can now also save this widget &#8211; because we have an update() method. Notice that our title and selection saves on click. Now let&#8217;s move to the widget() method.</p>
<h6>The widget() method</h6>
<p>This is the method that actually outputs our widget. This method accepts a couple of arguments &#8211; one of them is our $instance array.</p>
<pre>function widget($args, $instance) {
	extract( $args );
	$title = apply_filters('widget_title', $instance['title']);
	$numberOfListings = $instance['numberOfListings'];
	echo $before_widget;
	if ( $title ) {
		echo $before_title . $title . $after_title;
	}
	$this-&gt;getRealtyListings($numberOfListings);
	echo $after_widget;
}
</pre>
<p>One thing to note is the <strong>$before_widget</strong> and <strong>$after_widget</strong> variables. These are, markups that appear &#8211; you guessed it: before and after the widget. You will also see <strong>$this-&gt;getRealtyListings()</strong> &#8211; which we&#8217;ll cover next.</p>
<h6>Pull our Custom Posts</h6>
<p>This method will do a query of our custom posts. It will only return the number of posts that we&#8217;ve saved in our widget. Add this code to our class:</p>
<pre class="">function getRealtyListings($numberOfListings) { //html
	global $post;
	add_image_size( 'realty_widget_size', 85, 45, false );
	$listings = new WP_Query();
	$listings-&gt;query('post_type=listings&amp;posts_per_page=' . $numberOfListings );
	if($listings-&gt;found_posts &gt; 0) {
</pre>
<p class=""><em>[code above has been truncated &#8211; due to syntax highlighting error]</em></p>
<p>So we have the above code which takes 1 parameter: $numberOfListings. We do an <a href="http://codex.wordpress.org/Function_Reference/add_image_size">add_image_size()</a> so we can get a custom size for our thumbnails. Also note where we&#8217;re querying the post_type of &#8220;listings&#8221;, you can change this value to your own post type (or not even use it for default).<br />
The code then continues building the HTML output of list items containing our post thumbnail, title and date added.</p>
<h6>Add some CSS</h6>
<p>Our CSS is pretty straightforward, just keeping the elements in the right place. You also might want to use your own styles, so I&#8217;ll just post the code that I used, without further explanation.</p>
<pre>.noThumb{
  width:85px;
  height:45px;
  background-color:#000;
  float:left;
  margin:0 12px 0 0;
}
ul.realty_widget {
  margin-top:10px;
}
ul.realty_widget li {
  margin:0 0 15px 0;
  list-style:none;
  min-height:45px;
  line-height:19px;
}
ul.realty_widget li img{
  float:left;
  margin:0 12px 0 0;
}
ul.realty_widget li a {
  font-weight:bold;
}
ul.realty_widget li span {
  display:block;
  font-size:11px;
}
</pre>
<p>So with the above styling, our final output looks like below:<br />
<img decoding="async" class="alignnone size-full wp-image-5703" src="https://michaelsoriano.com/wp-content/uploads/2013/08/widget-tut2-1.jpg" alt="widget-tut2" width="512" height="505" srcset="https://michaelsoriano.com/wp-content/uploads/2013/08/widget-tut2-1.jpg 512w, https://michaelsoriano.com/wp-content/uploads/2013/08/widget-tut2-1-300x296.jpg 300w" sizes="(max-width: 512px) 100vw, 512px" /></p>
<h6>Conclusion</h6>
<p>So there you have it. We have added a widget to our WordPress theme that pulls our custom post types. As mentioned, this technique will work with regular posts as well. I have updated the Realty theme files to include this code &#8211; so you can go ahead and <a href="https://app.box.com/s/ozy8oczmb6erqqjrijtq">download</a> it if you like. Please let me know in the comments if this tutorial helped your development in any way.</p>
<p>The post <a href="https://michaelsoriano.com/wordpress-widget-custom-post-types/">Let&#8217;s make a WordPress Widget that displays our Custom Post Types</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/wordpress-widget-custom-post-types/feed/</wfw:commentRss>
			<slash:comments>23</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>
		<item>
		<title>How to create an Email Opt in Box for your Downloads &#8211; Part 2</title>
		<link>https://michaelsoriano.com/opt-in-box-2/</link>
					<comments>https://michaelsoriano.com/opt-in-box-2/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Wed, 04 Apr 2012 03:59:38 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=2436</guid>

					<description><![CDATA[<p>So you&#8217;re giving away free material from your site. And now you need a way to capture your users&#8217; information. An Opt in box may be the perfect solution for you. From my previous post, we already have a working box that shows us some static messages, along with a link that takes them to [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/opt-in-box-2/">How to create an Email Opt in Box for your Downloads &#8211; Part 2</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So you&#8217;re giving away free material from your site. And now you need a way to capture your users&#8217; information. An Opt in box may be the perfect solution for you.<br />
From my <a href="https://michaelsoriano.com/create-opt-in-box/">previous post</a>, we already have a working box that shows us some static messages, along with a link that takes them to the Feedburner sign up process. This box is automatically shown to all links with a .zip extension. The problem is &#8211; people may not want to sign up with Feedburner. So let’s take things a step further.<br />
This tutorial will add a form to our subscribe box, store the email addresses in a database and send the download link to their inbox. This way, you can target only people who want to download. At the same time, we can use this information for future marketing endeavors such as newsletters, updates or what not.<br />
<img decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2012/03/ouroptinbox.jpg" alt="" title="ouroptinbox" width="576" height="255" class="alignnone size-full wp-image-2439" /><br />
Note that this will require a bit of PHP and MySQL. Are you ready to begin? Roll up your sleeves and lets start a codin&#8217;.</p>
<h3>1. Add The Form</h3>
<p>Our form will be a simple one. All we need is to grab their email address, and a submit button. Add the code below to our existing opt in box:<br />
<script src="https://gist.github.com/michaelsoriano/adb1bf052150c55a6be4.js"></script><br />
Note that our form’s method is “Post”, while our action is “process.php”. This is the file that will handle our processing. Also, we added a hidden field to add our file link. If you recall in <a href="https://michaelsoriano.com/opt-in-box/">part 1</a> of the tutorial, we are prompting this form to people who want to download our files. This hidden field will contain the value of the link to our file.<br />
Next up is to add some Javascript to validate our form. This will prevent the form from being submitted if the email is invalid or empty. Note that this only our client side check – we will validate the submission once again in the server side. Wrap the code below inside script tags:</p>
<h6>Client Side Validation:</h6>
<p><script src="https://gist.github.com/michaelsoriano/64ccce5212d36c787dab.js"></script><br />
Remember from our first exercise, we have the jQuery library in our pages. So the selector $(&#8216;input.submitbutton&#8217;) targets our submit button and it’s click event. The code checks the entry if its empty and if it looks like a good email address. This is achieved using <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expressions</a>. The code returns false if the matches are met – meaning the submit button won’t work.</p>
<h3>The Database</h3>
<p>Let’s setup the database so we can store the email addresses that we will collect. I use MySql – which is free and comes with <a href="http://www.apachefriends.org/en/xampp.html">XAMPP</a>. I’m using  XAMPP to develop locally. You might want to create directly on your hosting – so you can use phpMyAdmin. The process is the same.<br />
Create a database:<br />
<img decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2012/03/create-db.jpg" alt="" title="create-db" width="420" height="153" class="alignnone work size-full wp-image-2437" /><br />
In your database, create a table named “email” with 2 columns: 1) id – make sure you this is the primary key, and check “auto-increment”, 2) email – this you can set as “VARCHAR” and with 255 length.<br />
<img decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2012/03/create-columns.jpg" alt="" title="create-columns" width="420" height="353" class="alignnone work size-full wp-image-2438" /><br />
You can add extra columns such as name and date – but for the purpose of this tutorial, I’m keeping it to a minimum. Now for the next step – the processing page.</p>
<h3>3. The Processing Page</h3>
<p>This page will be the one that will store the submitted information to our database. It will also be the one that will send the user the link to the file that they’re downloading.<br />
Create a file – name it “process.php” and store it in the same directory as your opt in form. First we use this brilliant <a href="http://www.linuxjournal.com/article/9585?page=0,0">function</a> from Douglas Lovell, which will be our server side validation of the email address from our form.<br />
But why do we need to validate the email again – when we’ve already done so using Javascript in our code above? That is simple – users can disable Javascript and submit all sorts of things in our form. They can also inspect our source code and see our form action and method. This allows them to go directly to our processing page with POST values of their own. This is a big no – no. So client and server side validation is necessary. Add the code below to our new page:</p>
<h6>Server Side Validation:</h6>
<p><script src="https://gist.github.com/michaelsoriano/668b3afb3df6ccc73f5d.js"></script><br />
Then we add the code below to continue our processing code:<br />
<script src="https://gist.github.com/michaelsoriano/26e5b564f55a1a78f129.js"></script><br />
Explanation: First we check if our POST data is set and is not empty and if it is a valid email (we pass our POST variable to the function “validEmail”. If everything looks good – we start our database code. We make sure the email is safe to enter in our database by using mysql_escape_string , and assigning it to a new variable “$cleanEmail”. Then we setup the database connection and credentials, we select the database and prepare our sql statement – appending the $cleanEmail variable. Finally, we execute the query.<br />
Continue with the code below to process the email that goes out to our user:</p>
<h6>Sending the Link to the Subscriber:</h6>
<p><script src="https://gist.github.com/michaelsoriano/1865094069a7f5a50b5a.js"></script><br />
The above sets up a few more variables : $to is the user’s submitted email address, $link is the hidden field from our form – which contained $subject and $message  comprise of our message. The mail function sends our mail and header sends our user to a new page. Notice the else statement – which contains another header function – but to a different page.</p>
<h3>4. The Redirect Pages</h3>
<p>This part is just a couple of static landing pages to capture the user when a) there’s a problem and b) if their submission is successful:<br />
Create a page called “thank-you.php” and enter the HTML below with a success message. Also, a page called “problem.php” with a problematic message.</p>
<h3>Conclusion</h3>
<p>At this point you should have a working form, a processing page and a database table expecting some data. Test your form and enter a valid email address. If you&#8217;re developing locally, chances are you will run into this error: &#8220;<em>mail() [function.mail]: Failed to connect to mailserver at &#8220;localhost</em>&#8220;. Dont&#8217; worry &#8211; this is due to your local server is not configured to send emails. Verify that your table has the email address you entered. Important &#8211; you also must test the validation code. Put in some bogus characters, and malformed email addresses to do this. It is important that you keep bad data from being injected into your db.<br />
Finally, be aware that this code may not be optimal data wise. Things to keep in mind are ways to prevent spam, duplicate entries and maybe add cookies to prevent &#8220;re-popping up&#8221; to the same user. Please feel free to share your comments below.</p>
<p>The post <a href="https://michaelsoriano.com/opt-in-box-2/">How to create an Email Opt in Box for your Downloads &#8211; Part 2</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/opt-in-box-2/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
	</channel>
</rss>
