<?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>Chris Monnat &#187; CodeIgniter</title>
	<atom:link href="http://www.christophermonnat.com/topics/codeigniter/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.christophermonnat.com</link>
	<description>Programmer Extraordinaire</description>
	<lastBuildDate>Thu, 02 Feb 2012 14:26:37 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>CodeIgniter 2.0: First Look at Reactor</title>
		<link>http://www.christophermonnat.com/2011/02/codeigniter-2-0-first-look-at-reactor/</link>
		<comments>http://www.christophermonnat.com/2011/02/codeigniter-2-0-first-look-at-reactor/#comments</comments>
		<pubDate>Tue, 22 Feb 2011 10:00:43 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[CodeIgniter]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.christophermonnat.com/?p=1222</guid>
		<description><![CDATA[If you are a PHP programmer then you have undoubtedly heard of the CodeIgniter (CI) framework at least once. First released in 2006, by EllisLab, CI has grown into the lightweight, fully functional and easy to use application framework of choice for developers across the web. A big milestone was reached two weeks ago with the release of version 2.0 and there has never been a better time to kick the tires and take it for a spin. Not Just Any Old Framework There are A LOT of open source PHP frameworks on the web today. Some of them are pretty nice tools and some of them aren&#8217;t. When evaluating a framework you need to look at several factors: community, documentation, features, support options and learning curve. Depending on your individual requirements you might have some additional criteria but I think that&#8217;s a decent baseline. Let&#8217;s see how CI stands up: Community Last look at the forums puts registered members at 190,000. Now that&#8217;s not necessarily active users, but that&#8217;s the number of developers who thought enough of the framework to get a forum account and join in on the conversation. EllisLab places a very high premium on their developer community and a number of the additions in 2.0 were added at their request. Documentation I have played around with a number of different PHP frameworks and you will be hard pressed to find a framework with better documentation than CI. The users guide is complete, easy to understand and up to date with all the latest bells and whistles. Any PHP developer with a basic understanding of object oriented programming (OOP) should be able to pick things up pretty easily. It&#8217;s worth noting that with the release of 2.0 some new sections of the users guide are still being fleshed out, but there is enough there to help get you started. Features This is the true question: &#8220;can the framework do what I need it to do?&#8221; This question really depends on what it is you need it to do. But CI has most of the standard framework features including model view controller (MVC) architecture, database abstraction, form validation, session handing, error handling, flexible/scalable architecture and libraries to handle tasks like uploading files, displaying event calendars, implementing carts for e-commerce sites and much more. If that&#8217;s not enough CI also lets you add any additional functionality you want/need by building your own custom library or extending core libraries that are already there. Support Options So you invest all this time and effort into learning a framework and building your business around it, what do you do if things suddenly stop working? While CI doesn&#8217;t offer any kind of commercial support, the community is full of folks on the forum waiting to lend a hand when necessary. There are also a number of bloggers out there who share their CI knowledge and can be tapped for help from time to time. The other thing worth mentioning here is that CI is backed by a successful commercial company in EllisLab (makers of ExpressionEngine CMS). So it&#8217;s a pretty safe bet that it&#8217;s not going anywhere anytime soon. Learning Curve We&#8217;re all on a timeline, so how long will it take to get up to speed? As I mentioned under documentation, CI is very well documented and has an active and vibrant community. With that said, anyone with a fair understanding of OOP should be able to pick things up pretty quickly. New to Version 2.0 So now that I have your attention, let&#8217;s take a look at the exciting new additions to CI in version 2.0: 2 Flavors: Core and Reactor As I mentioned above, CI is backed by a commercial company and is used by that company to develop their commercial products like ExpressionEngine and MojoMotor. That means that the development of the framework was limited to the needs of their products and the community got a little frustrated feeling that the development of the framework had stalled over time. In true EllisLab fashion they listened and in version 2.0 have released two different lines of development: Core and Reactor. You now have the option of working with CI Core (maintained by EllisLab) or CI Reactor (maintained by the community). Core is the version of CI that EllisLab uses and will only change when they need to make a change for their products. This version should be used by those looking for true stability and backward/forward compatibility. Reactor, on the other hand, is maintained by a team of community engineers who collectively monitor community needs/wants and incorporate new features on a more frequent basis. Since all changes made to Core will be incorporated into Reactor and that Reactor will be the more active of the two code bases it&#8217;s recommended that everyone use Reactor from this point forward. PHP5 Support A common point of contention with previous version of CI was that it wasn&#8217;t native PHP5 meaning the framework was backwards compatible with PHP4 and certain PHP5 features didn&#8217;t work or were not used. With the release of 2.0 this is no longer the case. PHP4 is no longer supported and you must be running PHP 5.1.6 or higher in order to use the framework. So feel free to start taking advantage of the OOP improvements of PHP5. Packages Distributing code for reuse or releasing complex libraries (for things like authentication) to the community has always been a somewhat clunky process. You would typically need to copy and paste certain files into certain places within your install in order for everything to work correctly. Config files in the config folder, libraries in their respective folder, etc. CI 2.0 does away with this issue by introducing a new way of collecting and distributing code called packages. Packages are similar in theory to modular development in that all the resources you are distributing are self contained. All packages will have their own libraries, models, helpers, config, and language files collected in their own directory which can then be placed into the application/third_party directory of the framework for use. This provides developers with a much easier way of sharing/releasing code for use by the community. This also opens the doors for more module based application development with CI. Drivers In previous versions of CI there hasn&#8217;t been an elegant way of creating classes that all share a common parent class and not their sibling classes (handy in certain situations). You can now accomplish this with a new type of library called a driver. Drivers allow you to create a parent class with unlimited child classes that have no access to their siblings (for things like DB abstraction). This is a nice architecture for providing the same type of functionality only using different tools or implementation methods. Along with being able to create your own drivers, CI 2.0 identifies three drivers in the documentation: Cacheing, Database and Javascript. Javascript Library Saving the best for last, the item I was most excited about with this release was the Javascript Library. CI 2.0 now gives you the ability to plug your favorite javascript framework into CI using drivers so you can incorporate javascript into your apps more easily. jQuery is being distributed with the framework by default but you can be sure there will be other drivers released shortly for other javascript frameworks. Upgrading So far this post has been mostly about what&#8217;s new and exciting in version 2.0 but there have also been some changes to the framework that might trip up seasoned developers and those of you looking to upgrade from an earlier version. First and foremost, all CI core classes are now prefixed with CI_. This means that all controllers, models, etc. now need to extend CI_Controller, CI_Model, etc. respectively. You will want to be sure to update your code accordingly when upgrading to version 2 (this already tripped me up once). Second, some old features and functionality have finally been removed for good like scaffolding, plugins and the validation library. Plugins never really gained much traction with CI developers and have been deprecated for some time now. The CI core CAPTCHA plugin has been converted to a helper and any plugins you have developed should be converted to helpers also. The validation library, which has been replaced for a while now by form_validation, is gone. So if you have been putting off updating your code to use the new form_validation library now is the time to do it. Finally, a number of improvements have been made to the encryption library which will prevent you from decrypting data that you have encrypted with a previous version. To deal with this, you will have to run an update on your data using the new encode_from_legacy() method which will decode your data and return a re-encrypted string using the new method for storage. Those are the big things to look out for when upgrading from a previous version. Visit the users guide for complete upgrading instructions. Is that it? This is just a quick list of my top 5 changes/additions to the framework that have been released in 2.0. There&#8217;s a lot more where that came from like new cache drivers with APC, memcached, and file-based support, new security library and over 50 bug fixes. You can see the complete list of what&#8217;s new in the change log. So what are you waiting for? Take CodeIgniter 2.0 for a spin today!]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.christophermonnat.com/wp-content/uploads/2011/01/ci-logo.png"><img class="alignright size-full wp-image-1251" title="ci-logo" src="http://www.christophermonnat.com/wp-content/uploads/2011/01/ci-logo.png" alt="" width="183" height="50" /></a>If you are a PHP programmer then you have undoubtedly heard of the <a href="http://codeigniter.com">CodeIgniter</a> (CI) framework at least once. First released in 2006, by <a href="http://ellislab.com">EllisLab</a>, CI has grown into the lightweight, fully functional and easy to use application framework of choice for developers across the web. A big milestone was reached two weeks ago with the release of version 2.0 and there has never been a better time to kick the tires and take it for a spin.</p>
<p><span id="more-1222"></span></p>
<h2>Not Just Any Old Framework</h2>
<p>There are A LOT of open source PHP frameworks on the web today. Some of them are pretty nice tools and some of them aren&#8217;t. When evaluating a framework you need to look at several factors: community, documentation, features, support options and learning curve. Depending on your individual requirements you might have some additional criteria but I think that&#8217;s a decent baseline. Let&#8217;s see how CI stands up:</p>
<p><strong>Community</strong></p>
<p>Last look at the forums puts registered members at 190,000. Now that&#8217;s not necessarily active users, but that&#8217;s the number of developers who thought enough of the framework to get a forum account and join in on the conversation. EllisLab places a very high premium on their developer community and a number of the additions in 2.0 were added at their request.</p>
<p><strong>Documentation</strong></p>
<p>I have played around with a number of different PHP frameworks and you will be hard pressed to find a framework with better documentation than CI. The <a href="http://codeigniter.com/user_guide/index.html" target="_blank">users guide</a> is complete, easy to understand and up to date with all the latest bells and whistles. Any PHP developer with a basic understanding of object oriented programming (OOP) should be able to pick things up pretty easily.</p>
<p>It&#8217;s worth noting that with the release of 2.0 some new sections of the users guide are still being fleshed out, but there is enough there to help get you started.</p>
<p><strong>Features</strong></p>
<p>This is the true question: &#8220;can the framework do what I need it to do?&#8221; This question really depends on what it is you need it to do. But CI has most of the <a href="http://codeigniter.com/user_guide/overview/features.html" target="_blank">standard framework features</a> including model view controller (MVC) architecture, database abstraction, form validation, session handing, error handling, flexible/scalable architecture and libraries to handle tasks like uploading files, displaying event calendars, implementing carts for e-commerce sites and much more. If that&#8217;s not enough CI also lets you add any additional functionality you want/need by building your own custom library or extending core libraries that are already there.</p>
<p><strong>Support Options</strong></p>
<p>So you invest all this time and effort into learning a framework and building your business around it, what do you do if things suddenly stop working? While CI doesn&#8217;t offer any kind of commercial support, the community is full of folks on the <a href="http://codeigniter.com/forums/" target="_blank">forum</a> waiting to lend a hand when necessary. There are also a number of bloggers out there who share their CI knowledge and can be tapped for help from time to time.</p>
<p>The other thing worth mentioning here is that CI is backed by a successful commercial company in EllisLab (makers of <a href="http://www.expressionengine.com" target="_blank">ExpressionEngine CMS</a>). So it&#8217;s a pretty safe bet that it&#8217;s not going anywhere anytime soon.</p>
<p><strong>Learning Curve</strong></p>
<p>We&#8217;re all on a timeline, so how long will it take to get up to speed? As I mentioned under documentation, CI is very well documented and has an active and vibrant community. With that said, anyone with a fair understanding of OOP should be able to pick things up pretty quickly.</p>
<h2>New to Version 2.0</h2>
<p>So now that I have your attention, let&#8217;s take a look at the exciting new additions to CI in version 2.0:</p>
<h3>2 Flavors: Core and Reactor</h3>
<p>As I mentioned above, CI is backed by a commercial company and is used by that company to develop their commercial products like ExpressionEngine and MojoMotor. That means that the development of the framework was limited to the needs of their products and the community got a little frustrated feeling that the development of the framework had stalled over time. In true EllisLab fashion they listened and in version 2.0 have released two different lines of development: Core and Reactor.</p>
<p>You now have the option of working with CI Core (maintained by EllisLab) or CI Reactor (maintained by the community). Core is the version of CI that EllisLab uses and will only change when they need to make a change for their products. This version should be used by those looking for true stability and backward/forward compatibility. Reactor, on the other hand, is maintained by a team of community engineers who collectively monitor community needs/wants and incorporate new features on a more frequent basis.</p>
<p>Since all changes made to Core will be incorporated into Reactor and that Reactor will be the more active of the two code bases it&#8217;s recommended that everyone use Reactor from this point forward.</p>
<h3>PHP5 Support</h3>
<p>A common point of contention with previous version of CI was that it wasn&#8217;t native PHP5 meaning the framework was backwards compatible with PHP4 and certain PHP5 features didn&#8217;t work or were not used. With the release of 2.0 this is no longer the case. PHP4 is no longer supported and you must be running PHP 5.1.6 or higher in order to use the framework. So feel free to start taking advantage of the OOP improvements of PHP5.</p>
<h3>Packages</h3>
<p>Distributing code for reuse or releasing complex libraries (for things like authentication) to the community has always been a somewhat clunky process. You would typically need to copy and paste certain files into certain places within your install in order for everything to work correctly. Config files in the config folder, libraries in their respective folder, etc. CI 2.0 does away with this issue by introducing a new way of collecting and distributing code called packages.</p>
<p><a href="http://codeigniter.com/user_guide/libraries/loader.html" target="_blank">Packages</a> are similar in theory to modular development in that all the resources you are distributing are self contained. All packages will have their own libraries, models, helpers, config, and language files collected in their own directory which can then be placed into the application/third_party directory of the framework for use. This provides developers with a much easier way of sharing/releasing code for use by the community. This also opens the doors for more module based application development with CI.</p>
<h3>Drivers</h3>
<p>In previous versions of CI there hasn&#8217;t been an elegant way of creating classes that all share a common parent class and not their sibling classes (handy in certain situations). You can now accomplish this with a new type of library called a driver. <a href="http://codeigniter.com/user_guide/general/drivers.html" target="_blank">Drivers</a> allow you to create a parent class with unlimited child classes that have no access to their siblings (for things like DB abstraction). This is a nice architecture for providing the same type of functionality only using different tools or implementation methods.</p>
<p>Along with being able to create your own drivers, CI 2.0 identifies three drivers in the documentation: Cacheing, Database and Javascript.</p>
<h3>Javascript Library</h3>
<p>Saving the best for last, the item I was most excited about with this release was the <a href="http://codeigniter.com/user_guide/libraries/javascript.html" target="_blank">Javascript Library</a>. CI 2.0 now gives you the ability to plug your favorite javascript framework into CI using drivers so you can incorporate javascript into your apps more easily. <a href="http://jquery.com" target="_blank">jQuery</a> is being distributed with the framework by default but you can be sure there will be other drivers released shortly for other javascript frameworks.</p>
<h2>Upgrading</h2>
<p>So far this post has been mostly about what&#8217;s new and exciting in version 2.0 but there have also been some changes to the framework that might trip up seasoned developers and those of you looking to upgrade from an earlier version. First and foremost, all CI core classes are now prefixed with CI_. This means that all controllers, models, etc. now need to extend CI_Controller, CI_Model, etc. respectively. You will want to be sure to update your code accordingly when upgrading to version 2 (this already tripped me up once).</p>
<p>Second, some old features and functionality have finally been removed for good like scaffolding, plugins and the validation library. Plugins never really gained much traction with CI developers and have been deprecated for some time now. The CI core CAPTCHA plugin has been converted to a helper and any plugins you have developed should be converted to helpers also. The validation library, which has been replaced for a while now by form_validation, is gone. So if you have been putting off updating your code to use the new form_validation library now is the time to do it.</p>
<p>Finally, a number of improvements have been made to the encryption library which will prevent you from decrypting data that you have encrypted with a previous version. To deal with this, you will have to run an update on your data using the new encode_from_legacy() method which will decode your data and return a re-encrypted string using the new method for storage.</p>
<p>Those are the big things to look out for when upgrading from a previous version. Visit the users guide for <a href="http://codeigniter.com/user_guide/installation/upgrading.html" target="_blank">complete upgrading instructions</a>.</p>
<h2>Is that it?</h2>
<p>This is just a quick list of my top 5 changes/additions to the framework that have been released in 2.0. There&#8217;s a lot more where that came from like new cache drivers with APC, memcached, and file-based support, new security library and over 50 bug fixes. You can see the complete list of what&#8217;s new in the <a href="http://codeigniter.com/user_guide/changelog.html" target="_blank">change log</a>. So what are you waiting for? Take CodeIgniter 2.0 for a spin today!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.christophermonnat.com/2011/02/codeigniter-2-0-first-look-at-reactor/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>CodeIgniter 2.0 Released</title>
		<link>http://www.christophermonnat.com/2011/01/codeigniter-2-0-released/</link>
		<comments>http://www.christophermonnat.com/2011/01/codeigniter-2-0-released/#comments</comments>
		<pubDate>Mon, 31 Jan 2011 14:26:12 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[CodeIgniter]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.christophermonnat.com/?p=1250</guid>
		<description><![CDATA[The wait is over, CodeIgniter 2.0 has been released!! Apparently this happened last Friday and I simply didn&#8217;t notice until now. This release is exciting for 2 reasons, first it brings with it a shit load of new features and fixes and second it introduces CI Reactor which is a community driven branch of the framework. Theres a lot to digest and get excited about so check out the blog post for yourself and get coding!]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.christophermonnat.com/wp-content/uploads/2011/01/ci-logo.png"><img class="alignright size-full wp-image-1251" title="ci-logo" src="http://www.christophermonnat.com/wp-content/uploads/2011/01/ci-logo.png" alt="" width="183" height="50" /></a>The wait is over, CodeIgniter 2.0 has been released!! Apparently this happened last Friday and I simply didn&#8217;t notice until now. This release is exciting for 2 reasons, first it brings with it a shit load of <a href="http://codeigniter.com/user_guide/changelog.html" target="_blank">new features and fixes</a> and second it introduces CI Reactor which is a community driven branch of the framework. Theres a lot to digest and get excited about so check out the <a href="http://codeigniter.com/news/codeigniter_2.0.0_released" target="_blank">blog post</a> for yourself and get coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.christophermonnat.com/2011/01/codeigniter-2-0-released/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Make Phone Calls with Code Using Twilio</title>
		<link>http://www.christophermonnat.com/2010/12/communicate-with-your-users-using-twilio/</link>
		<comments>http://www.christophermonnat.com/2010/12/communicate-with-your-users-using-twilio/#comments</comments>
		<pubDate>Thu, 02 Dec 2010 10:00:53 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[CodeIgniter]]></category>
		<category><![CDATA[How-to]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.christophermonnat.com/?p=1096</guid>
		<description><![CDATA[Web applications are better than old school applications that get installed on your hard drive because you can access them from anywhere using the web. They do however suffer from the same limited communication channel as typical software because they can only interact with users via the computer. Users provide input via the keyboard and the app provides output via the screen. Wouldn&#8217;t it be cool if we could take advantage of other communication channels like phone and text messages to communicate with our users? Well now we can with the help of Twilio. In this post I&#8217;ll walk you through building an application that can make phone calls and send text messages using the Twilio API. Background For those of you who don&#8217;t know, Twilio is a web service API that empowers programmers with the ability to make phone calls and send SMS text messages programmatically. I first came across the service a while back and have been keeping an eye on it ever since because I think it has a lot of potential uses in modern web applications. In the past, having your application make a phone call used to entail a lot of programming and hardware overhead ($$$). Twilio makes it as simple as one single API call (that doesn&#8217;t break the bank) and you&#8217;re done. In this post I&#8217;m going to be building a sample application to illustrate some of what Twilio is capable of. Have you ever used a website or other service that required you to confirm your phone number by receiving a call and then entering a code given to you over the phone? Well that&#8217;s what we&#8217;re going to build. The concept is that a user fills out a generic registration form on your site and includes their phone number. Upon submission we will leverage Twilio to call the user and recite a 4 digit confirmation code that they will then have to enter in step 2 of the registration process. Upon validating the entered code from step 2 we will either send the user a SMS text message confirming a successful activation or display an error. For the purposes of this example I am leveraging the CodeIgniter framework simply for the sake of development speed. The code that actually interacts with the API can easily be transplanted into any application and still work. When it comes to interacting with the API, Twilio has a number of client libraries to choose from. Our weapon of choice is PHP, so I will be using the PHP client library. To make things a little easier I&#8217;m providing two downloads, one is the complete source code with all the code included. The other is just the framework preconfigured with the necessary libraries and helpers. This way, if you want to follow along, we won&#8217;t have to waste a lot of time setting up and configuring CodeIgniter. Step 1 &#8211; Get a Twilio Account Before you can access the Twilio API you first need to create an account to get access information. You typically have to pay to use Twilios service, but they do provide a free trial that comes with $30.00 worth of credit which you can use for the purposes of this example. Visit https://www.twilio.com/try-twilio and fill out the provided form. After creating your account, and logging in for the first time, you will be presented with your account dashboard. Your account dashboard is a collection of all of your account information in one easy to understand and access place. This is where you will find your Account SID and Auth Token. These are the two values you will need in order to make API requests. The dashboard also shows your account balance along with a rough calculation as to how that dollar amount translates into API requests. Your developer sandbox information is also displayed here, however we won&#8217;t be doing anything with the sandbox in this example. The other thing you will need to do before continuing is to setup an outgoing called ID number within Twilio. For obvious reasons you can&#8217;t just go placing calls and sending text messages from any old number. You first need to enter and confirm a caller ID number within your account and then you can use that number when making API requests. Within your Twilio account click Phone Numbers from the sub nav. At the bottom of this screen if where you can manage your called ID numbers. Click the Add Caller ID button and enter your phone number. Twilio will call you and request you enter a confirmation code (similar to the app we are about to build). After entering the code you should be all set. OK, so now that you have your API access information and have setup your caller ID your ready to jump in and get coding. Step 2 &#8211; Setup If you have not done so already, download a copy of the source code (blank or complete) and unzip the archive onto your desktop. For our registration example you will need to create a database and update CodeIgniters database settings (/application/config/database.php) with the appropriate access information. Once you have created your database, use the following SQL statement to create the one table we will be using. Now that you have created your database and updated the code you can upload everything to your development environment. You will notice that if you bring up the application in a browser you will most likely get an error. That&#8217;s because we haven&#8217;t created our default controller yet, but that&#8217;s the next step. Step 3 &#8211; Create the Controller Now that we&#8217;re up and running with our code and database we can get to coding. First thing to do is create a new controller called register.php in /application/controllers. When a user first visits our application we want to display our registration form so let&#8217;s setup our controller to do that by default. The above code leverages CodeIgniters default controller function index() to automatically display our registration form when a user first visits our application. Now we need to create our registration form view file. Create a new folder in /application/views called register and a new file in that folder called index.php. This view file contains just a simple four field registration form the user will complete to begin the registration process. Save and upload your changes and when you visit the application in a browser you should see the following form displayed. But before we go much further be sure to update the class variables at the top of the controller with your Account SID, Auth Token and caller ID number. Please note, the caller ID number should start with a plus sign (+), include the country code and have no hyphens. Step 4 &#8211; Access the API We now have our controller and registration form. You may notice however that when you submit the registration form nothing happens. The form is looking for a controller function called confirm(). This function will begin our user registration process by validating the form input, generating the users confirmation code and contacting the Twilio API to call our user and recite the code. Let&#8217;s go ahead and create this function now in our controller. The majority of this code should be pretty self explanatory (for those familiar with CI) but let&#8217;s review just to be safe. The first 13 lines are all about validation. We are using CodeIgniters form_validation library to validate our form input and ensure we have valid data. If there are any errors we display the form again with error messages. On line 19 we create a random 4 digit number that we will use as our confirmation code. This is the code we will pass to Twilio to recite to our users and then test for in step 2 of our process. This will be stored in our database along with our other user data. Lines 21-31 handle the database insertion for our user record using CIs active record library. 33-38 are where we contact the Twilio API and make our request to call the user (I&#8217;ll review these lines in a moment). The remainder of the function displays step 2 of our registration form which is just a single field asking the user to enter their confirmation code. Before we forget let&#8217;s create this new view file called confirm.php in /application/views/registration. As I mentioned above, lines 33-38 are where we actually make our API request to Twilio. The first thing we do here is determine if we need to make the call or not by checking the $call variable passed to the function. I put this in here to avoid making additional API calls if the user enters a wrong confirmation code (this will make sense later on). Next we create a new instance of TwilioRestClient which is the PHP client library and pass it our Account SID and Auth Token for authentication. Using our new TwilioRestClient object, we make a request to the API using the request() function. This function takes 3 arguments: the path to the API method your calling, the type of request your making (POST, GET, etc.) and any data you are passing along to the API (as an array). Something to make note of here is the path to the API method we are passing. In a rather odd turn of events, each API call must include your Account SID. I find this rather odd and verbose but alas it is required. There are ways to make this easier to use within your code by making a minor modification to their library, but I chose to keep things just the way they provide for the purposes of our example. So we are calling the /Accounts/Calls API method and passing it a &#8220;From&#8221; phone number, &#8220;To&#8221; phone number and &#8220;Url&#8221; to handle the call. The &#8220;From&#8221; number is the phone number the call will be made from (your Twilio called ID number). The &#8220;To&#8221; number is the number Twilio will be calling. It&#8217;s worth noting that this number must inclue the country code and contain no hyphens. The code should probably include some sanitization to ensure this, but I kept it out for simplicity. Finally the URL to handle the call is where Twilio will look for instructions on what to do for this call. This is where we have to provide it with instructions using TwiML or Twilio Markup Language. Step 5 &#8211; TwiML There is an entire section of documentation dedicated to TwiML, so I don&#8217;t intend on spending a tremendous amount of time on it. Suffice it to say it is the XML format that Twilio expects when looking for instructions on what to do when placing a phone call. You have several options to choose from but all we care to do is place a call and read a script. Let&#8217;s go ahead and create a new function in our controller called handle_call() to generate the necessary TwiML. The above code basically creates the following XML document. The first thing we do here is find our user based on ID in the DB. Next we take their confirmation code and put spaces between the numbers. Without doing this Twilio will pronounce the number as a complete number instead of digit by digit which would be a bummer for our users. Finally we put it all together in a script and call the addSay() function adding a loop attribute of 2 to make sure Twilio repeats the message twice. If you were to visit this function in your browser (/registration/handle_call) you would hopefully see the XML I provided above as an example. Step 6 &#8211; Confirmation We now have the majority of our application in place. The only thing we&#8217;re missing is the processing code to handle step 2 of our registration process. Let&#8217;s create a new function in our controller called confirm_code() to handle the final bit of validation. The above code processes the confirmation code submission and checks to see if our user entered the correct code or not. If correct, we send the user a SMS text message using Twilio and display a view called account_activated.php. If incorrect, we simply display a view called account_error.php. Let&#8217;s create those two views now in /application/views/register. The code for sending the text message is very similar to the block we used to make the phone call above. This time we are requesting the /SMS/Messages API method to send a text message and passing along &#8220;From&#8221;, &#8220;To&#8221; and &#8220;Body&#8221; as parameters. Just like above &#8220;From&#8221; is the phone number we are sending from (our Twilio caller ID number), &#8220;To&#8221; is the number we are sending to and &#8220;Body&#8221; is the actual content of the text message. It&#8217;s worth mentioning that text messages don&#8217;t require any TwiML instructions, only phone calls. And there you have it. If you save and upload your changes you should now have a functioning example. Enter your phone number in the phone number field of the registration form (being sure to include the country code and no hyphens) and hit submit. You should shortly receive a phone call reciting your confirmation code. Enter that code in the confirmation code form and submit. You should then see the success message and receive a congratulatory text message. Debugging When I was first building this app I was not having much luck with placing phone calls. Twilio would call me but say there was a system error and then hang up (very frustrating). Come to find out that I had my site password protected and it couldn&#8217;t get to the handle_call() function for the TwiML instructions. The point of this story is I wouldn&#8217;t have been able to figure out what the problem was without the Twilio Debugger available through your Twilio account. The debugger, available when you log-in and click Debugger from the sub nav, is your first stop when trying to deal with Twilio issues. It should give you the information you need to determine what the problem is. There is also some documentation available to help you deal with common issues. And if all else fails you can contact support for additional assistance. Conclusion This is obviously not a complete and well polished application but it does illustrate some of what Twilio is capable of. Some possible enhancements to this code could include adding a country code drop down menu to the registration form so the user doesn&#8217;t have to enter it as part of their phone number, better phone number validation to ensure processing and maybe e-mail integration since we are collecting the users e-mail address. Feel free to experiment on your own and let me know how you make out by leaving a comment. I know this was a long post but thanks for sticking with me. To learn more about what Twilios capable of, be sure to visit their documentation and implementation gallery.]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.christophermonnat.com/wp-content/uploads/2010/11/twilio-logo.png"><img class="alignright size-full wp-image-1137" title="twilio-logo" src="http://www.christophermonnat.com/wp-content/uploads/2010/11/twilio-logo.png" alt="" width="130" height="130" /></a>Web applications are better than old school applications that get installed on your hard drive because you can access them from anywhere using the web. They do however suffer from the same limited communication channel as typical software because they can only interact with users via the computer. Users provide input via the keyboard and the app provides output via the screen. Wouldn&#8217;t it be cool if we could take advantage of other communication channels like phone and text messages to communicate with our users? Well now we can with the help of <a href="http://www.twilio.com" target="_blank">Twilio</a>. In this post I&#8217;ll walk you through building an application that can make phone calls and send text messages using the Twilio API.</p>
<p><span id="more-1096"></span></p>
<h2>Background</h2>
<p>For those of you who don&#8217;t know, Twilio is a web service API that empowers programmers with the ability to make phone calls and send SMS text messages programmatically. I first came across the service a while back and have been keeping an eye on it ever since because I think it has a lot of potential uses in modern web applications. In the past, having your application make a phone call used to entail a lot of programming and hardware overhead ($$$). Twilio makes it as simple as one single API call (that doesn&#8217;t break the bank) and you&#8217;re done.</p>
<p>In this post I&#8217;m going to be building a sample application to illustrate some of what Twilio is capable of. Have you ever used a website or other service that required you to confirm your phone number by receiving a call and then entering a code given to you over the phone? Well that&#8217;s what we&#8217;re going to build. The concept is that a user fills out a generic registration form on your site and includes their phone number. Upon submission we will leverage Twilio to call the user and recite a 4 digit confirmation code that they will then have to enter in step 2 of the registration process. Upon validating the entered code from step 2 we will either send the user a SMS text message confirming a successful activation or display an error.</p>
<p>For the purposes of this example I am leveraging the <a href="http://codeigniter.com" target="_blank">CodeIgniter framework</a> simply for the sake of development speed. The code that actually interacts with the API can easily be transplanted into any application and still work. When it comes to interacting with the API, Twilio has a number of <a href="http://www.twilio.com/docs/libraries/" target="_blank">client libraries to choose from</a>. Our weapon of choice is PHP, so I will be using the PHP client library.</p>
<p>To make things a little easier I&#8217;m providing two downloads, one is the <a href="http://www.christophermonnat.com/wp-content/uploads/2010/12/twilio-complete.zip">complete source code</a> with all the code included. The other is <a href="http://www.christophermonnat.com/wp-content/uploads/2010/12/twilio-blank.zip">just the framework</a> preconfigured with the necessary libraries and helpers. This way, if you want to follow along, we won&#8217;t have to waste a lot of time setting up and configuring CodeIgniter.</p>
<h2>Step 1 &#8211; Get a Twilio Account</h2>
<p>Before you can access the Twilio API you first need to create an account to get access information. You typically have to pay to use Twilios service, but they do provide a free trial that comes with $30.00 worth of credit which you can use for the purposes of this example.</p>
<p>Visit <a href="https://www.twilio.com/try-twilio" target="_blank">https://www.twilio.com/try-twilio</a> and fill out the provided form.</p>
<p><center><a href="http://www.christophermonnat.com/wp-content/uploads/2010/12/twilio-signup.png"><img class="aligncenter size-full wp-image-1183" title="twilio-signup" src="http://www.christophermonnat.com/wp-content/uploads/2010/12/twilio-signup.png" alt="" width="400" height="309" /></a></center>After creating your account, and logging in for the first time, you will be presented with your account dashboard.</p>
<p><a href="http://www.christophermonnat.com/wp-content/uploads/2010/11/twilio-dashboard.png"><img class="aligncenter size-full wp-image-1145" title="twilio-dashboard" src="http://www.christophermonnat.com/wp-content/uploads/2010/11/twilio-dashboard.png" alt="" width="595" height="615" /></a></p>
<p>Your account dashboard is a collection of all of your account information in one easy to understand and access place. This is where you will find your Account SID and Auth Token. These are the two values you will need in order to make API requests. The dashboard also shows your account balance along with a rough calculation as to how that dollar amount translates into API requests. Your developer sandbox information is also displayed here, however we won&#8217;t be doing anything with the sandbox in this example.</p>
<p>The other thing you will need to do before continuing is to setup an outgoing called ID number within Twilio. For obvious reasons you can&#8217;t just go placing calls and sending text messages from any old number. You first need to enter and confirm a caller ID number within your account and then you can use that number when making API requests.</p>
<p><center><a href="http://www.christophermonnat.com/wp-content/uploads/2010/12/twilio-numbers.png"><img class="aligncenter size-full wp-image-1201" title="twilio-numbers" src="http://www.christophermonnat.com/wp-content/uploads/2010/12/twilio-numbers.png" alt="" width="595" height="342" /></a></center>Within your Twilio account click Phone Numbers from the sub nav. At the bottom of this screen if where you can manage your called ID numbers. Click the Add Caller ID button and enter your phone number. Twilio will call you and request you enter a confirmation code (similar to the app we are about to build). After entering the code you should be all set.</p>
<p>OK, so now that you have your API access information and have setup your caller ID your ready to jump in and get coding.</p>
<h2>Step 2 &#8211; Setup</h2>
<p>If you have not done so already, download a copy of the source code (<a href="http://www.christophermonnat.com/wp-content/uploads/2010/12/twilio-blank.zip">blank</a> or <a href="http://www.christophermonnat.com/wp-content/uploads/2010/12/twilio-complete.zip">complete</a>) and unzip the archive onto your desktop. For our registration example you will need to create a database and update CodeIgniters database settings (/application/config/database.php) with the appropriate access information. Once you have created your database, use the following SQL statement to create the one table we will be using.</p>
<pre class="brush: sql; title: ; notranslate">
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL auto_increment,
`fname` varchar(50) NOT NULL,
`lname` varchar(50) NOT NULL,
`email` varchar(200) NOT NULL,
`phone` varchar(12) NOT NULL,
`confirm_code` varchar(4) default NULL,
PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
</pre>
<p>Now that you have created your database and updated the code you can upload everything to your development environment. You will notice that if you bring up the application in a browser you will most likely get an error. That&#8217;s because we haven&#8217;t created our default controller yet, but that&#8217;s the next step.</p>
<h2>Step 3 &#8211; Create the Controller</h2>
<p>Now that we&#8217;re up and running with our code and database we can get to coding. First thing to do is create a new controller called <strong>register.php</strong> in /application/controllers. When a user first visits our application we want to display our registration form so let&#8217;s setup our controller to do that by default.</p>
<pre class="brush: php; title: ; notranslate">
class Register extends Controller
{
private $_account_sid = '';
private $_auth_token  = '';
private $_from_phone  = '';

public function __construct()
{
parent::__construct();

require_once(APPPATH . 'libraries/twilio.php');
}

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

/**
 * Display app registration form.
 *
 * @access public
 * @return void
 */
public function index()
{
$temp_data = array(
'page_title' =&amp;amp;amp;gt; lang('application'),
'content_main' =&amp;amp;amp;gt; $this-&amp;amp;amp;gt;load-&amp;amp;amp;gt;view('register/index', 0, TRUE)
);

$this-&amp;amp;amp;gt;load-&amp;amp;amp;gt;view('_layouts/default', $temp_data);
}
}
</pre>
<p>The above code leverages CodeIgniters default controller function index() to automatically display our registration form when a user first visits our application. Now we need to create our registration form view file. Create a new folder in /application/views called <strong>register</strong> and a new file in that folder called <strong>index.php</strong>.</p>
<pre class="brush: php; title: ; notranslate">
&lt;h1&gt;&lt;?php echo lang('application'); ?&gt;&lt;/h1&gt;
&lt;?php echo display_form_error(validation_errors()); ?&gt;

&lt;?php echo form_open('register/confirm'); ?&gt;

&lt;p&gt;&lt;label for=&quot;fname&quot;&gt;First name: &lt;em&gt;*&lt;/em&gt;&lt;/label&gt;
&lt;input type=&quot;text&quot; name=&quot;fname&quot; id=&quot;fname&quot; value=&quot;&lt;?php echo set_value('fname'); ?&gt;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;label for=&quot;lname&quot;&gt;Last name: &lt;em&gt;*&lt;/em&gt;&lt;/label&gt;
&lt;input type=&quot;text&quot; name=&quot;lname&quot; id=&quot;lname&quot; value=&quot;&lt;?php echo set_value('lname'); ?&gt;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;label for=&quot;email&quot;&gt;Email address: &lt;em&gt;*&lt;/em&gt;&lt;/label&gt;
&lt;input type=&quot;text&quot; name=&quot;email&quot; id=&quot;email&quot; value=&quot;&lt;?php echo set_value('email'); ?&gt;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;label for=&quot;phone&quot;&gt;Phone number: &lt;em&gt;*&lt;/em&gt;&lt;/label&gt;
&lt;input type=&quot;text&quot; name=&quot;phone&quot; id=&quot;phone&quot; maxlength=&quot;12&quot; value=&quot;&lt;?php echo set_value('phone'); ?&gt;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;input type=&quot;submit&quot; value=&quot;Register now&quot; /&gt;&lt;/p&gt;

&lt;?php echo form_close(); ?&gt;
</pre>
<p>This view file contains just a simple four field registration form the user will complete to begin the registration process. Save and upload your changes and when you visit the application in a browser you should see the following form displayed. But before we go much further be sure to update the class variables at the top of the controller with your Account SID, Auth Token and caller ID number. Please note, the caller ID number should start with a plus sign (+), include the country code and have no hyphens.</p>
<p><center><a href="http://www.christophermonnat.com/wp-content/uploads/2010/11/twilio-reg-form.png"><img class="aligncenter size-full wp-image-1161" title="twilio-reg-form" src="http://www.christophermonnat.com/wp-content/uploads/2010/11/twilio-reg-form.png" alt="" width="595" height="270" /></a></center></p>
<h2>Step 4 &#8211; Access the API</h2>
<p>We now have our controller and registration form. You may notice however that when you submit the registration form nothing happens. The form is looking for a controller function called confirm(). This function will begin our user registration process by validating the form input, generating the users confirmation code and contacting the Twilio API to call our user and recite the code. Let&#8217;s go ahead and create this function now in our controller.</p>
<pre class="brush: php; title: ; notranslate">
public function confirm($call = TRUE)
{
$this-&amp;amp;gt;load-&amp;amp;gt;library('form_validation');

$this-&amp;amp;gt;form_validation-&amp;amp;gt;set_error_delimiters('&amp;amp;lt;li&amp;amp;gt;', '&amp;amp;lt;/li&amp;amp;gt;');

$rules = array(
array('field' =&amp;amp;gt; 'fname', 'label' =&amp;amp;gt; 'first name', 'rules' =&amp;amp;gt; 'trim|required|htmlentities'),
array('field' =&amp;amp;gt; 'lname', 'label' =&amp;amp;gt; 'last name', 'rules' =&amp;amp;gt; 'trim|required|htmlentities'),
array('field' =&amp;amp;gt; 'email', 'label' =&amp;amp;gt; 'email address', 'rules' =&amp;amp;gt; 'trim|required|valid_email|htmlentities'),
array('field' =&amp;amp;gt; 'phone', 'label' =&amp;amp;gt; 'phone number', 'rules' =&amp;amp;gt; 'trim|required|htmlentities'),
);

$this-&amp;amp;gt;form_validation-&amp;amp;gt;set_rules($rules);

if($this-&amp;amp;gt;form_validation-&amp;amp;gt;run())
{
// generate random 4 digit confirmation code
$confirm_code = rand(1000,9999);

// add new user to DB
$user_data = array(
'fname' =&amp;amp;gt; $this-&amp;amp;gt;input-&amp;amp;gt;post('fname'),
'lname' =&amp;amp;gt; $this-&amp;amp;gt;input-&amp;amp;gt;post('lname'),
'email' =&amp;amp;gt; $this-&amp;amp;gt;input-&amp;amp;gt;post('email'),
'phone' =&amp;amp;gt; $this-&amp;amp;gt;input-&amp;amp;gt;post('phone'),
'confirm_code' =&amp;amp;gt; $confirm_code
);

$this-&amp;amp;gt;db-&amp;amp;gt;insert('users', $user_data);
$user_id = $this-&amp;amp;gt;db-&amp;amp;gt;insert_id();

if($call)
{
// make call request to Twilio
$twilio = new TwilioRestClient($this-&amp;amp;gt;_account_sid, $this-&amp;amp;gt;_auth_token);
$result = $twilio-&amp;amp;gt;request('2010-04-01/Accounts/' . $this-&amp;amp;gt;_account_sid . '/Calls', 'POST', array('From' =&amp;amp;gt; $this-&amp;amp;gt;_from_phone, 'To' =&amp;amp;gt; $this-&amp;amp;gt;input-&amp;amp;gt;post('phone'), 'Url' =&amp;amp;gt; site_url('register/handle_call/' . $user_id)));
}

// display confirmation form
$page_data = array(
'user_id' =&amp;amp;gt; $this-&amp;amp;gt;db-&amp;amp;gt;insert_id()
);

$temp_data = array(
'page_title' =&amp;amp;gt; lang('application'),
'content_main' =&amp;amp;gt; $this-&amp;amp;gt;load-&amp;amp;gt;view('register/confirm', $page_data, TRUE)
);

$this-&amp;amp;gt;load-&amp;amp;gt;view('_layouts/default', $temp_data);
}
else
{
// display form errors
$this-&amp;amp;gt;index();
}
}
</pre>
<p>The majority of this code should be pretty self explanatory (for those familiar with CI) but let&#8217;s review just to be safe. The first 13 lines are all about validation. We are using CodeIgniters form_validation library to validate our form input and ensure we have valid data. If there are any errors we display the form again with error messages. On line 19 we create a random 4 digit number that we will use as our confirmation code. This is the code we will pass to Twilio to recite to our users and then test for in step 2 of our process. This will be stored in our database along with our other user data. Lines 21-31 handle the database insertion for our user record using CIs active record library. 33-38 are where we contact the Twilio API and make our request to call the user (I&#8217;ll review these lines in a moment). The remainder of the function displays step 2 of our registration form which is just a single field asking the user to enter their confirmation code. Before we forget let&#8217;s create this new view file called <strong>confirm.php</strong> in /application/views/registration.</p>
<pre class="brush: php; title: ; notranslate">
&lt;h1&gt;&lt;?php echo lang('application'); ?&gt;&lt;/h1&gt;

&lt;h2&gt;Confirm Your Identity&lt;/h2&gt;

&lt;p&gt;You will receive a phone call shortly providing a 4 digit confirmation code.
Please enter that code below and click &lt;strong&gt;Confirm&lt;/strong&gt;.&lt;/p&gt;

&lt;?php echo display_form_error(validation_errors()); ?&gt;

&lt;?php echo form_open('register/confirm_code'); ?&gt;

&lt;input type=&quot;hidden&quot; name=&quot;user_id&quot; value=&quot;&lt;?php echo $user_id; ?&gt;&quot; /&gt;

&lt;p&gt;&lt;label for=&quot;confirm_code&quot;&gt;Confirmation code: &lt;em&gt;*&lt;/em&gt;&lt;/label&gt;
&lt;input type=&quot;text&quot; name=&quot;confirm_code&quot; id=&quot;confirm_code&quot; maxlength=&quot;4&quot; value=&quot;&quot; /&gt;
&lt;input type=&quot;submit&quot; value=&quot;Confirm&quot; /&gt;&lt;/p&gt;

&lt;?php echo form_close(); ?&gt;
</pre>
<p>As I mentioned above, lines 33-38 are where we actually make our API request to Twilio.</p>
<pre class="brush: php; title: ; notranslate">
if($call)
{
// make call request to Twilio
$twilio = new TwilioRestClient($this-&amp;amp;gt;_account_sid, $this-&amp;amp;gt;_auth_token);
$result = $twilio-&amp;amp;gt;request('2010-04-01/Accounts/' . $this-&amp;amp;gt;_account_sid . '/Calls', 'POST', array('From' =&amp;amp;gt; $this-&amp;amp;gt;_from_phone, 'To' =&amp;amp;gt; $this-&amp;amp;gt;input-&amp;amp;gt;post('phone'), 'Url' =&amp;amp;gt; site_url('register/handle_call/' . $user_id)));
}
</pre>
<p>The first thing we do here is determine if we need to make the call or not by checking the $call variable passed to the function. I put this in here to avoid making additional API calls if the user enters a wrong confirmation code (this will make sense later on). Next we create a new instance of TwilioRestClient which is the PHP client library and pass it our Account SID and Auth Token for authentication. Using our new TwilioRestClient object, we make a request to the API using the request() function. This function takes 3 arguments: the path to the API method your calling, the type of request your making (POST, GET, etc.) and any data you are passing along to the API (as an array).</p>
<p>Something to make note of here is the path to the API method we are passing. In a rather odd turn of events, each API call must include your Account SID. I find this rather odd and verbose but alas it is required. There are ways to make this easier to use within your code by making a minor modification to their library, but I chose to keep things just the way they provide for the purposes of our example.</p>
<p>So we are calling the <a href="http://www.twilio.com/docs/api/2010-04-01/rest/call" target="_blank">/Accounts/Calls API method</a> and passing it a &#8220;From&#8221; phone number, &#8220;To&#8221; phone number and &#8220;Url&#8221; to handle the call. The &#8220;From&#8221; number is the phone number the call will be made from (your Twilio called ID number). The &#8220;To&#8221; number is the number Twilio will be calling. It&#8217;s worth noting that this number must inclue the country code and contain no hyphens. The code should probably include some sanitization to ensure this, but I kept it out for simplicity. Finally the URL to handle the call is where Twilio will look for instructions on what to do for this call. This is where we have to provide it with instructions using TwiML or Twilio Markup Language.</p>
<h2>Step 5 &#8211; TwiML</h2>
<p>There is an <a href="http://www.twilio.com/docs/api/2010-04-01/twiml/" target="_blank">entire section of documentation</a> dedicated to TwiML, so I don&#8217;t intend on spending a tremendous amount of time on it. Suffice it to say it is the XML format that Twilio expects when looking for instructions on what to do when placing a phone call. You have several options to choose from but all we care to do is place a call and read a script. Let&#8217;s go ahead and create a new function in our controller called <strong>handle_call()</strong> to generate the necessary TwiML.</p>
<pre class="brush: php; title: ; notranslate">
public function handle_call($user_id = NULL)
{
if(!is_null($user_id))
{
$user = $this-&gt;db-&gt;get_where('users', array('id' =&gt; $user_id))-&gt;row();

// put spaces between code so Twilio will pronounce digits instead of the complete number
$confirm_code = '';
for($i=0; $i&lt;=3; ++$i)
{
$confirm_code .= $user-&gt;confirm_code[$i] . ' ';
}

$script = 'Hello your confirmation code is ' . $confirm_code . '.';
}
else
{
$script = 'Im sorry but your account could not be verified.';
}

$twilio = new Response();
$twilio-&gt;addSay($script, array('loop' =&gt; 2));
$twilio-&gt;Respond();
}
</pre>
<p>The above code basically creates the following XML document.</p>
<pre class="brush: xml; title: ; notranslate">
&amp;amp;lt;?xml version=&amp;amp;quot;1.0&amp;amp;quot; encoding=&amp;amp;quot;UTF-8&amp;amp;quot; ?&amp;amp;gt;
&amp;amp;lt;Response&amp;amp;gt;
     &amp;amp;lt;Say loop=&amp;amp;quot;2&amp;amp;quot;&amp;amp;gt;Hello your confirmation code is XXXX.&amp;amp;lt;/Say&amp;amp;gt;
&amp;amp;lt;/Response&amp;amp;gt;
</pre>
<p>The first thing we do here is find our user based on ID in the DB. Next we take their confirmation code and put spaces between the numbers. Without doing this Twilio will pronounce the number as a complete number instead of digit by digit which would be a bummer for our users. Finally we put it all together in a script and call the addSay() function adding a loop attribute of 2 to make sure Twilio repeats the message twice. If you were to visit this function in your browser (/registration/handle_call) you would hopefully see the XML I provided above as an example.</p>
<h2>Step 6 &#8211; Confirmation</h2>
<p>We now have the majority of our application in place. The only thing we&#8217;re missing is the processing code to handle step 2 of our registration process. Let&#8217;s create a new function in our controller called confirm_code() to handle the final bit of validation.</p>
<pre class="brush: php; title: ; notranslate">
function confirm_code()
{
$this-&gt;load-&gt;library('form_validation');

$this-&gt;form_validation-&gt;set_error_delimiters('&lt;li&gt;', '&lt;/li&gt;');

$rules = array(
array('field' =&gt; 'confirm_code', 'label' =&gt; 'confirmation code', 'rules' =&gt; 'trim|numeric|max_length[4]|htmlentities'),
);

$this-&gt;form_validation-&gt;set_rules($rules);

if($this-&gt;form_validation-&gt;run())
{
$user = $this-&gt;db-&gt;get_where('users', array('id' =&gt; $this-&gt;input-&gt;post('user_id')))-&gt;row();

if($user-&gt;confirm_code == $this-&gt;input-&gt;post('confirm_code'))
{
$this-&gt;db-&gt;update('users', array('confirm_code' =&gt; NULL), array('id' =&gt; $user-&gt;id));

// make SMS request to Twilio
$twilio = new TwilioRestClient($this-&gt;_account_sid, $this-&gt;_auth_token);
$result = $twilio-&gt;request('2010-04-01/Accounts/' . $this-&gt;_account_sid . '/SMS/Messages', 'POST', array('From' =&gt; $this-&gt;_from_phone, 'To' =&gt; $user-&gt;phone, 'Body' =&gt; 'Hi ' . $user-&gt;fname . ', Thanks for activating your account.'));

$content_main = $this-&gt;load-&gt;view('register/account_activated', 0, TRUE);
}
else
{
$content_main = $this-&gt;load-&gt;view('register/account_error', 0, TRUE);
}

$temp_data = array(
'page_title' =&gt; lang('application'),
'content_main' =&gt; $content_main
);

$this-&gt;load-&gt;view('_layouts/default', $temp_data);
}
else
{
$this-&gt;confirm(FALSE);
}
}
</pre>
<p>The above code processes the confirmation code submission and checks to see if our user entered the correct code or not. If correct, we send the user a SMS text message using Twilio and display a view called <strong>account_activated.php</strong>. If incorrect, we simply display a view called <strong>account_error.php</strong>. Let&#8217;s create those two views now in /application/views/register.</p>
<pre class="brush: php; title: ; notranslate">
&lt;h1&gt;&lt;?php echo lang('application'); ?&gt;&lt;/h1&gt;

&lt;p&gt;Your account has been activated.&lt;/p&gt;
</pre>
<pre class="brush: php; title: ; notranslate">
&lt;h1&gt;&lt;?php echo lang('application'); ?&gt;&lt;/h1&gt;

&lt;p&gt;Your account could not be verified at this time.&lt;/p&gt;
</pre>
<p>The code for sending the text message is very similar to the block we used to make the phone call above.</p>
<pre class="brush: php; title: ; notranslate">
$twilio = new TwilioRestClient($this-&gt;_account_sid, $this-&gt;_auth_token);
$result = $twilio-&gt;request('2010-04-01/Accounts/' . $this-&gt;_account_sid . '/SMS/Messages', 'POST', array('From' =&gt; $this-&gt;_from_phone, 'To' =&gt; $user-&gt;phone, 'Body' =&gt; 'Hi ' . $user-&gt;fname . ', Thanks for activating your account.'));
</pre>
<p>This time we are requesting the <a href="http://www.twilio.com/docs/api/2010-04-01/rest/sms" target="_blank">/SMS/Messages API method</a> to send a text message and passing along &#8220;From&#8221;, &#8220;To&#8221; and &#8220;Body&#8221; as parameters. Just like above &#8220;From&#8221; is the phone number we are sending from (our Twilio caller ID number), &#8220;To&#8221; is the number we are sending to and &#8220;Body&#8221; is the actual content of the text message. It&#8217;s worth mentioning that text messages don&#8217;t require any TwiML instructions, only phone calls.</p>
<p>And there you have it. If you save and upload your changes you should now have a functioning example. Enter your phone number in the phone number field of the registration form (being sure to include the country code and no hyphens) and hit submit. You should shortly receive a phone call reciting your confirmation code. Enter that code in the confirmation code form and submit. You should then see the success message and receive a congratulatory text message.</p>
<h2>Debugging</h2>
<p>When I was first building this app I was not having much luck with placing phone calls. Twilio would call me but say there was a system error and then hang up (very frustrating). Come to find out that I had my site password protected and it couldn&#8217;t get to the handle_call() function for the TwiML instructions. The point of this story is I wouldn&#8217;t have been able to figure out what the problem was without the Twilio Debugger available through your Twilio account.</p>
<p><center><a href="http://www.christophermonnat.com/wp-content/uploads/2010/12/twilio-debugger.png"><img class="aligncenter size-full wp-image-1198" title="twilio-debugger" src="http://www.christophermonnat.com/wp-content/uploads/2010/12/twilio-debugger.png" alt="" width="595" height="293" /></a></center>The debugger, available when you log-in and click Debugger from the sub nav, is your first stop when trying to deal with Twilio issues. It should give you the information you need to determine what the problem is. There is also <a href="http://www.twilio.com/docs/errors/" target="_blank">some documentation</a> available to help you deal with common issues. And if all else fails you can <a href="http://getsatisfaction.com/twilio/" target="_blank">contact support</a> for additional assistance.</p>
<h2>Conclusion</h2>
<p>This is obviously not a complete and well polished application but it does illustrate some of what Twilio is capable of. Some possible enhancements to this code could include adding a country code drop down menu to the registration form so the user doesn&#8217;t have to enter it as part of their phone number, better phone number validation to ensure processing and maybe e-mail integration since we are collecting the users e-mail address. Feel free to experiment on your own and let me know how you make out by leaving a comment.</p>
<p>I know this was a long post but thanks for sticking with me. To learn more about what Twilios capable of, be sure to visit their <a href="http://www.twilio.com/docs/index" target="_blank">documentation</a> and <a href="http://www.twilio.com/gallery" target="_blank">implementation gallery</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.christophermonnat.com/2010/12/communicate-with-your-users-using-twilio/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Review: CodeIgniter 1.7 Professional Development</title>
		<link>http://www.christophermonnat.com/2010/06/review-codeigniter-1-7-professional-development/</link>
		<comments>http://www.christophermonnat.com/2010/06/review-codeigniter-1-7-professional-development/#comments</comments>
		<pubDate>Mon, 28 Jun 2010 23:17:05 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[Books]]></category>
		<category><![CDATA[CodeIgniter]]></category>

		<guid isPermaLink="false">http://www.christophermonnat.com/?p=1026</guid>
		<description><![CDATA[Along with being a Zend Certified PHP5 engineer I&#8217;m also a strong advocate for application frameworks (CodeIgniter specifically). That&#8217;s why I was pleased when Pact approached me about a month ago to write a review of their new book about CodeIgniter (CI): CodeIgniter 1.7 Professional Development. Aimed at experienced PHP developers with a solid footing in object oriented programming, the book provides a detailed overview of the CI framework from an absolute beginners perspective. Chocked full of code samples and tips/techniques on how to leverage CIs tools this book is a great resource for anyone new to the framework looking to quickly get up to speed. CodeIgniter 1.7 Professional Development is a complete soup to nuts overview of the CI framework. Coming in at 10 chapters and around 260 pages this book is perfect for those new to CI. The book starts out with reviewing CIs MVC architecture, system libraries and form validation techniques. Then the author dedicates 2 chapters to user authentication and walks you through building your own authentication solution (includes details on oAuth and Facebook Connect). Application security, large scale development and extending CIs core is also covered in later chapters. All in all this book provides a very well rounded sampling of topics for complete newbies and experienced developers alike. The one chapter I found most informative was chapter 8 Web Services. Like most developers, I have done quite a bit of work with consuming APIs but never had to write one of my own. Recently however I was charged with the task of writing an API that other developers would be interacting with and I had to stumble along and come up with my own solution. In chapter 8 the author reviews web services in depth and how to create your own REST service using CI. Very helpful for those new to that particular topic. To be honest, when I first received the book I was a little disappointed. I&#8217;m not a CI beginner so I was hoping for a lot more advanced items, answers to questions I&#8217;ve been struggling with myself. But after spending some time with the book and writing this review I think I have changed my tune. The author spends ample time on the basic stuff but also finds time to touch on more advanced topics like user authentication (with oAuth and Facebook Connect), application security and web service development. If you are a professional web worker who uses CI in your day to day activities then you should consider getting this book. There is a little something for everyone.]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.christophermonnat.com/wp-content/uploads/2010/05/codeigniter-book.jpg"><img class="alignright size-full wp-image-1020" title="codeigniter-book" src="http://www.christophermonnat.com/wp-content/uploads/2010/05/codeigniter-book.jpg" alt="" width="125" height="152" /></a>Along with being a Zend Certified PHP5 engineer I&#8217;m also a strong advocate for application frameworks (<a href="http://codeigniter.com">CodeIgniter</a> specifically). That&#8217;s why I was pleased when Pact approached me about a month ago to write a review of their new book about CodeIgniter (CI): <a href="http://www.packtpub.com/codeigniter-1-7-professional-development/book?utm_source=ianwootten.co.uk&amp;utm_medium=bookrev&amp;utm_content=blog&amp;utm_campaign=mdb_003228">CodeIgniter 1.7 Professional Development</a>. Aimed at experienced PHP developers with a solid footing in object oriented programming, the book provides a detailed overview of the CI framework from an absolute beginners perspective. Chocked full of code samples and tips/techniques on how to leverage CIs tools this book is a great resource for anyone new to the framework looking to quickly get up to speed.</p>
<p><span id="more-1026"></span></p>
<p>CodeIgniter 1.7 Professional Development is a complete soup to nuts overview of the CI framework. Coming in at 10 chapters and around 260 pages this book is perfect for those new to CI. The book starts out with reviewing CIs MVC architecture, system libraries and form validation techniques. Then the author dedicates 2 chapters to user authentication and walks you through building your own authentication solution (includes details on oAuth and Facebook Connect). Application security, large scale development and extending CIs core is also covered in later chapters. All in all this book provides a very well rounded sampling of topics for complete newbies and experienced developers alike.</p>
<p>The one chapter I found most informative was chapter 8 Web Services. Like most developers, I have done quite a bit of work with consuming APIs but never had to write one of my own. Recently however I was charged with the task of writing an API that other developers would be interacting with and I had to stumble along and come up with my own solution. In chapter 8 the author reviews web services in depth and how to create your own REST service using CI. Very helpful for those new to that particular topic.</p>
<p>To be honest, when I first received the book I was a little disappointed. I&#8217;m not a CI beginner so I was hoping for a lot more advanced items, answers to questions I&#8217;ve been struggling with myself. But after spending some time with the book and writing this review I think I have changed my tune. The author spends ample time on the basic stuff but also finds time to touch on more advanced topics like user authentication (with oAuth and Facebook Connect), application security and web service development.</p>
<p>If you are a professional web worker who uses CI in your day to day activities then you should consider getting this book. There is a little something for everyone.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.christophermonnat.com/2010/06/review-codeigniter-1-7-professional-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CodeIgniter 1.7 Professional Development</title>
		<link>http://www.christophermonnat.com/2010/05/codeigniter-1-7-professional-development/</link>
		<comments>http://www.christophermonnat.com/2010/05/codeigniter-1-7-professional-development/#comments</comments>
		<pubDate>Mon, 24 May 2010 14:05:30 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[Books]]></category>
		<category><![CDATA[CodeIgniter]]></category>

		<guid isPermaLink="false">http://www.christophermonnat.com/?p=1019</guid>
		<description><![CDATA[For you CodeIgniter fans out there, Packt released a new book last month called CodeIgniter 1.7 Professional Development. I got word this morning that my review copy is in the mail so keep your eyes out for my thoughts on this book in the coming weeks. From the summary it looks like it covers a wide range of topics from beginner to advanced so I&#8217;m excited to take a look. If interested, head on over to the Packt website to read a sample chapter on database interaction.]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.christophermonnat.com/wp-content/uploads/2010/05/codeigniter-book.jpg"><img src="http://www.christophermonnat.com/wp-content/uploads/2010/05/codeigniter-book.jpg" alt="" title="codeigniter-book" width="125" height="152" class="alignright size-full wp-image-1020" /></a>For you CodeIgniter fans out there, Packt released a new book last month called <a href="http://www.packtpub.com/codeigniter-1-7-professional-development/book?utm_source=christophermonnat.com&#038;utm_medium=bookrev&#038;utm_content=blog&#038;utm_campaign=mdb_003457">CodeIgniter 1.7 Professional Development</a>. I got word this morning that my review copy is in the mail so keep your eyes out for my thoughts on this book in the coming weeks. From the summary it looks like it covers a wide range of topics from beginner to advanced so I&#8217;m excited to take a look. If interested, head on over to the Packt website to read a <a href="http://www.packtpub.com/article/database-interaction-with-codeigniter-1.7">sample chapter on database interaction</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.christophermonnat.com/2010/05/codeigniter-1-7-professional-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Facebook Connect Library for CodeIgniter</title>
		<link>http://www.christophermonnat.com/2009/05/facebook-connect-library-for-codeigniter/</link>
		<comments>http://www.christophermonnat.com/2009/05/facebook-connect-library-for-codeigniter/#comments</comments>
		<pubDate>Mon, 18 May 2009 22:00:52 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[CodeIgniter]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.christophermonnat.com/?p=762</guid>
		<description><![CDATA[Just a brief follow-up to the post series I did a while back on Implementing Facebook Connect with CI. Today, Elliot Haughin continued his tradition of releasing helpful CI libraries and published a new library for implementing Facebook Connect using CodeIgniter. Haven&#8217;t had a chance to review it personally yet but I would imagine it&#8217;s just the thing to make implementing Facebook Connect on your CI site easier. Check it out!]]></description>
			<content:encoded><![CDATA[<p>Just a brief follow-up to the post series I did a while back on <a href="http://www.christophermonnat.com/guides">Implementing Facebook Connect with CI</a>. Today, Elliot Haughin continued his tradition of releasing helpful CI libraries and published a <a href="http://www.haughin.com/2009/05/18/new-codeigniter-library-facebook-connect/">new library for implementing Facebook Connect using CodeIgniter</a>. Haven&#8217;t had a chance to review it personally yet but I would imagine it&#8217;s just the thing to make implementing Facebook Connect on your CI site easier. Check it out!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.christophermonnat.com/2009/05/facebook-connect-library-for-codeigniter/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Building Applications using CodeIgniter (Part 4) &#8211; Code Templates</title>
		<link>http://www.christophermonnat.com/2009/05/building-applications-using-codeigniter-part-4-code-templates/</link>
		<comments>http://www.christophermonnat.com/2009/05/building-applications-using-codeigniter-part-4-code-templates/#comments</comments>
		<pubDate>Wed, 13 May 2009 10:00:00 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[CodeIgniter]]></category>

		<guid isPermaLink="false">http://www.christophermonnat.com/?p=601</guid>
		<description><![CDATA[Last July I wrote a post entitled &#8220;What does your code say about you?&#8221; In that post I discuss the importance of writing clean well formatted code. It&#8217;s vitally important, even if you are the only programmer working on a project, that you document and format your code because you may be the only programmer now but who knows about 6 months or a year from now. Plus, as a programmer, the code you write is a direct reflection on you as a professional. So far in this series I&#8217;ve discussed my typical application structure, configuration and helper files when developing apps using CodeIgniter (CI). In this final post I&#8217;ll review creating code templates for quick consistent development. There is nothing really functional/technical about code templates. Templates are a set of simple files that have the basic document structure for the specified file (controller, model, library, etc.) that you use as a common starting point when creating any new file for your app. Your template should contain common elements to all files like the header comment block, class declaration, constructor, etc. There is no need to come up with your own standard when creating your templates because CI has a very nice style guide you should follow. CI Style Guide A few versions ago, CI added a page to their users guide entitled PHP Style Guide. In this section they do a great job at outlining the proper format when declaring variables, writing comments, naming files, etc. This is a great place to start when creating your templates. If you don&#8217;t already, you should think about getting in the habit of following these standards (even if you aren&#8217;t programming with CI) because they will help keep your code clean and consistent. Template Files Before I start coding my app I typically create a template file and place it in the controller and model folders. The templates are different of course, but they both create a nice starting point whenever I need to create a new file. It&#8217;s important to note that you don&#8217;t necessarily have to create physical template files to accomplish clean and well formatted code. Some tools like Coda and TextMate give you the ability to save bits of text and reuse them in your files. So you could create your header comment block and save it in your editor and just call upon that whenever you create a new file. Doesn&#8217;t really matter how you do it, it just matters that you do. That&#8217;s a Wrap OK&#8230; lecture over. That does it for the building applications using CodeIgniter post series. If interested, you can download a copy of the final CI install that we&#8217;ve created over the last 4 posts with helpers, code templates and all. I hope by sheding some light on my process and explaining how I do things you came up with some ideas on how you can improve your own CI apps. As always, feel free to leave any questions or feedback as a comment below.]]></description>
			<content:encoded><![CDATA[<p>Last July I wrote a post entitled &#8220;<a href="http://www.christophermonnat.com/2008/07/what-does-you-code-say-about-you/">What does your code say about you?</a>&#8221; In that post I discuss the importance of writing clean well formatted code. It&#8217;s vitally important, even if you are the only programmer working on a project, that you document and format your code because you may be the only programmer now but who knows about 6 months or a year from now. Plus, as a programmer, the code you write is a direct reflection on you as a professional.</p>
<p>So far in this series I&#8217;ve discussed my typical <a href="http://www.christophermonnat.com/2009/04/building-applications-using-codeigniter-part-1-file-structure/">application structure</a>, <a href="http://www.christophermonnat.com/2009/05/building-applications-using-codeigniter-part-2-configuration/">configuration</a> and <a href="http://www.christophermonnat.com/2009/05/building-applications-using-codeigniter-part-3-helpers/">helper files</a> when developing apps using CodeIgniter (CI). In this final post I&#8217;ll review creating code templates for quick consistent development.<br />
<span id="more-601"></span></p>
<p>There is nothing really functional/technical about code templates. Templates are a set of simple files that have the basic document structure for the specified file (controller, model, library, etc.) that you use as a common starting point when creating any new file for your app. Your template should contain common elements to all files like the header comment block, class declaration, constructor, etc. There is no need to come up with your own standard when creating your templates because CI has a very nice style guide you should follow.</p>
<h2>CI Style Guide</h2>
<p>A few versions ago, CI added a page to their users guide entitled <a href="http://codeigniter.com/user_guide/general/styleguide.html">PHP Style Guide</a>. In this section they do a great job at outlining the proper format when declaring variables, writing comments, naming files, etc. This is a great place to start when creating your templates. If you don&#8217;t already, you should think about getting in the habit of following these standards (even if you aren&#8217;t programming with CI) because they will help keep your code clean and consistent.</p>
<h2>Template Files</h2>
<p>Before I start coding my app I typically create a template file and place it in the controller and model folders. The templates are different of course, but they both create a nice starting point whenever I need to create a new file. It&#8217;s important to note that you don&#8217;t necessarily have to create physical template files to accomplish clean and well formatted code. Some tools like <a href="http://www.panic.com/coda/">Coda</a> and <a href="http://macromates.com/">TextMate</a> give you the ability to save bits of text and reuse them in your files. So you could create your header comment block and save it in your editor and just call upon that whenever you create a new file. Doesn&#8217;t really matter how you do it, it just matters that you do.</p>
<h2>That&#8217;s a Wrap</h2>
<p>OK&#8230; lecture over. That does it for the building applications using CodeIgniter post series. If interested, you can <a href="http://www.christophermonnat.com/wp-content/uploads/2009/04/codeigniter_171.zip">download a copy</a> of the final CI install that we&#8217;ve created over the last 4 posts with helpers, code templates and all.</p>
<p>I hope by sheding some light on my process and explaining how I do things you came up with some ideas on how you can improve your own CI apps. As always, feel free to leave any questions or feedback as a comment below.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.christophermonnat.com/2009/05/building-applications-using-codeigniter-part-4-code-templates/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Building Applications using CodeIgniter (Part 3) &#8211; Helpers</title>
		<link>http://www.christophermonnat.com/2009/05/building-applications-using-codeigniter-part-3-helpers/</link>
		<comments>http://www.christophermonnat.com/2009/05/building-applications-using-codeigniter-part-3-helpers/#comments</comments>
		<pubDate>Fri, 08 May 2009 10:00:23 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[CodeIgniter]]></category>

		<guid isPermaLink="false">http://www.christophermonnat.com/?p=593</guid>
		<description><![CDATA[So far in this series we&#8217;ve discussed framework/application structure and configuration information. The next thing I always add to new applications is some common helper files I&#8217;ve developed and that come in handy in most projects. CodeIgniter (CI) helpers are very flexible tools to assist with common tasks throughout the app. If it doesn&#8217;t belong in a controller and is too small for a custom library then a helper might be just what the programmer ordered. What belongs in a helper? Something I&#8217;ve struggled with in the past is determining when a certain function or process belongs in a helper file and when it would be better off elsewhere. There is no cold hard rule for determining when something belongs in a helper and when it doesn&#8217;t but you do need to be aware of the following: &#8220;Unlike most other systems in CodeIgniter, Helpers are not written in an Object Oriented format. They are simple, procedural functions. Each helper function performs one specific task, with no dependence on other functions.&#8221; - CI Users Guide This means that in order to access libraries and models within your helper functions you will need to get a CI instance: $CI =&#38; get_instance(); With the technicalities out of the way let&#8217;s take a look at the 2 helper files I&#8217;ve developed: display_helper.php and  flash_helper.php. display_helper.php A lot can be accomplished with CI&#8217;s built in templating but there are still some things that require logic and therefore fit nicely within a helper function. The display_helper.php file holds a number of common HTML display functions that I use throughout my program view files. To see what this file looks like, download an example. The functions in this file are pretty self-explanatory but I will briefly describe what each does below: display_error() The display_error() function displays a properly formatted HTML error message. I have this function setup so it can display 2 types of message: standard and form. When using the form_validation library I use the set_error_delimiter() method to wrap my error messages in list item tags and then display form error messages as unordered lists. So, I can easily accomplish displaying both types of messages using this function just by passing some variables. display_msg() This function just displays a properly formatted HTML message. This doesn&#8217;t necessarily need to be in a helper function because it&#8217;s so simple. But, the nice thing about having it here is if I ever decide to change the format of my messages I just need to come here in one place and make the update. So it consolidates my code nicely&#8230; but the same could probably be accomplished by using more generic CSS ID names. req_field() You should always identify required fields on your forms so users know what they need to fill in and what can be left blank. I&#8217;ve put the display of this flag in a helper function again to consolidate my code. As with the display_msg() function, if I ever decide to change my required field flag I just need to come to this one place and change it instead of going into all my view files and going a find and replace. js_confirm() JavaScript confirmation messages come in handy when you want to check with a user to make sure they are sure of something before you do it. You can accomplish the same confirmation by writing more PHP but that takes more work. The js_confirm() function, when used with the default CI URL helper anchor() function, displays a browser pop-up message with whatever text I pass to the function. If I&#8217;m in a hurry and don&#8217;t provide a message the function just returns a generic &#8220;Are you sure?&#8221; message. Your display_helper file might look much different than mine, this is just an example of how I use it. But you want to be on the look out while your coding for repetition and little details here and there that might be changing down the road. If you can consolidate those things in a helper file you will end up saving a lot of time updating down the road. flash_helper.php CI added flashdata to it&#8217;s session library a few versions back and I for one was happy to see it. Flashdata allows you to pass messages for display between pages.  Simple status messages like &#8220;record added&#8221; or &#8220;record not found&#8221; can be placed in a flashdata variable and then displayed after the user is redirected to another page. A very handy tool for letting your users know the results of their actions. While I do like this functionality, writing $this-&#62;session-&#62;set_flashdata(&#8216;item&#8217;, &#8216;value&#8217;) and $this-&#62;session-&#62;flashdata(&#8216;item&#8217;) every time I need to set or get something is a lot of typing. So the flash_helper is a pair of wrapper functions that handle the job of setting and displaying flash messages for me. To see what this file looks like, download an example. display_flash() The display_flash() function displays a selected flash message in a view file. Simply provide the name of the flash variable and it will display it in a properly formatted HTML div. set_flash() This function sets a flash variable with a value I specify. Since I use flash variables for a lot of different messages, which I may need to format differently, I also use this function to store some formatting data along with the message. That way when I display the message it is automatically displayed using the CSS style I intended. The flash_helper file is based on the same concept that Michael Wales posted about a while back. I would link to the post but I can&#8217;t seem to find it anymore. Last up: Code Templates That wraps up the 3rd installment of this series. In the next, and final post, I&#8217;ll discuss creating code templates to help you maintain consistency between your files.]]></description>
			<content:encoded><![CDATA[<p>So far in this series we&#8217;ve discussed <a href="http://www.christophermonnat.com/2009/04/building-applications-using-codeigniter-part-1-file-structure/">framework/application structure</a> and <a href="http://www.christophermonnat.com/2009/05/building-applications-using-codeigniter-part-2-configuration/">configuration information</a>. The next thing I always add to new applications is some common <a href="http://codeigniter.com/user_guide/general/helpers.html">helper files</a> I&#8217;ve developed and that come in handy in most projects. CodeIgniter (CI) helpers are very flexible tools to assist with common tasks throughout the app. If it doesn&#8217;t belong in a controller and is too small for a custom library then a helper might be just what the programmer ordered.</p>
<p><span id="more-593"></span></p>
<h2>What belongs in a helper?</h2>
<p>Something I&#8217;ve struggled with in the past is determining when a certain function or process belongs in a helper file and when it would be better off elsewhere. There is no cold hard rule for determining when something belongs in a helper and when it doesn&#8217;t but you do need to be aware of the following:</p>
<p>&#8220;Unlike most other systems in CodeIgniter, Helpers are not written in an Object Oriented format. They are simple, procedural functions. Each helper function performs one specific task, with no dependence on other functions.&#8221;<br />
- CI Users Guide</p>
<p>This means that in order to access libraries and models within your helper functions you will need to get a CI instance:</p>
<p>$CI =&amp; get_instance();</p>
<p>With the technicalities out of the way let&#8217;s take a look at the 2 helper files I&#8217;ve developed: <strong>display_helper.php</strong> and  <strong>flash_helper.php</strong>.</p>
<h2>display_helper.php</h2>
<p>A lot can be accomplished with CI&#8217;s built in templating but there are still some things that require logic and therefore fit nicely within a helper function. The display_helper.php file holds a number of common HTML display functions that I use throughout my program view files. To see what this file looks like, <a href="http://www.christophermonnat.com/wp-content/uploads/2009/04/display_helper.zip">download an example</a>. The functions in this file are pretty self-explanatory but I will briefly describe what each does below:</p>
<p><strong>display_error()</strong></p>
<p>The display_error() function displays a properly formatted HTML error message. I have this function setup so it can display 2 types of message: standard and form. When using the form_validation library I use the set_error_delimiter() method to wrap my error messages in list item tags and then display form error messages as unordered lists. So, I can easily accomplish displaying both types of messages using this function just by passing some variables.</p>
<p><strong>display_msg()</strong></p>
<p>This function just displays a properly formatted HTML message. This doesn&#8217;t necessarily need to be in a helper function because it&#8217;s so simple. But, the nice thing about having it here is if I ever decide to change the format of my messages I just need to come here in one place and make the update. So it consolidates my code nicely&#8230; but the same could probably be accomplished by using more generic CSS ID names.</p>
<p><strong>req_field()</strong></p>
<p>You should always identify required fields on your forms so users know what they need to fill in and what can be left blank. I&#8217;ve put the display of this flag in a helper function again to consolidate my code. As with the display_msg() function, if I ever decide to change my required field flag I just need to come to this one place and change it instead of going into all my view files and going a find and replace.</p>
<p><strong>js_confirm()</strong></p>
<p>JavaScript confirmation messages come in handy when you want to check with a user to make sure they are sure of something before you do it. You can accomplish the same confirmation by writing more PHP but that takes more work. The js_confirm() function, when used with the default <a href="http://codeigniter.com/user_guide/helpers/url_helper.html">CI URL helper</a> anchor() function, displays a browser pop-up message with whatever text I pass to the function. If I&#8217;m in a hurry and don&#8217;t provide a message the function just returns a generic &#8220;Are you sure?&#8221; message.</p>
<p>Your display_helper file might look much different than mine, this is just an example of how I use it. But you want to be on the look out while your coding for repetition and little details here and there that might be changing down the road. If you can consolidate those things in a helper file you will end up saving a lot of time updating down the road.</p>
<h2>flash_helper.php</h2>
<p>CI added flashdata to it&#8217;s <a href="http://codeigniter.com/user_guide/libraries/sessions.html">session library</a> a few versions back and I for one was happy to see it. Flashdata allows you to pass messages for display between pages.  Simple status messages like &#8220;record added&#8221; or &#8220;record not found&#8221; can be placed in a flashdata variable and then displayed after the user is redirected to another page. A very handy tool for letting your users know the results of their actions.</p>
<p>While I do like this functionality, writing $this-&gt;session-&gt;set_flashdata(&#8216;item&#8217;, &#8216;value&#8217;) and $this-&gt;session-&gt;flashdata(&#8216;item&#8217;) every time I need to set or get something is a lot of typing. So the flash_helper is a pair of wrapper functions that handle the job of setting and displaying flash messages for me. To see what this file looks like, <a href="http://www.christophermonnat.com/wp-content/uploads/2009/04/flash_helper.zip">download an example</a>.</p>
<p><strong>display_flash()</strong></p>
<p>The display_flash() function displays a selected flash message in a view file. Simply provide the name of the flash variable and it will display it in a properly formatted HTML div.</p>
<p><strong>set_flash()</strong></p>
<p>This function sets a flash variable with a value I specify. Since I use flash variables for a lot of different messages, which I may need to format differently, I also use this function to store some formatting data along with the message. That way when I display the message it is automatically displayed using the CSS style I intended.</p>
<p>The flash_helper file is based on the same concept that <a href="http://www.michaelwales.com/">Michael Wales</a> posted about a while back. I would link to the post but I can&#8217;t seem to find it anymore.</p>
<h2>Last up: Code Templates</h2>
<p>That wraps up the 3rd installment of this series. In the next, and final post, I&#8217;ll discuss creating code templates to help you maintain consistency between your files.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.christophermonnat.com/2009/05/building-applications-using-codeigniter-part-3-helpers/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Building Applications using CodeIgniter (Part 2) &#8211; Configuration</title>
		<link>http://www.christophermonnat.com/2009/05/building-applications-using-codeigniter-part-2-configuration/</link>
		<comments>http://www.christophermonnat.com/2009/05/building-applications-using-codeigniter-part-2-configuration/#comments</comments>
		<pubDate>Mon, 04 May 2009 10:00:59 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[CodeIgniter]]></category>

		<guid isPermaLink="false">http://www.christophermonnat.com/?p=578</guid>
		<description><![CDATA[The framework that you use to build your application will end up being the foundation of your program. Everything that your program does will revolve around how that framework works. Things like naming conventions, file paths and settings are dictated by the framework. But if you have chosen a good framework, like CodeIgniter (CI), you will be able to manipulate how that framework works and the tools it makes available to you by modifying it&#8217;s configuration information. In the first post I talked about application file structure. Now that the structure is solid I&#8217;m going to look at how I configure the framework so that it works the way I expect. Config All of CI&#8217;s configuration files are stored in application/config. - config &#8212; autoload.php &#8212; config.php &#8212; constants.php &#8212; database.php &#8212; doctypes.php &#8212; hooks.php &#8212; mimes.php &#8212; routes.php &#8212; smileys.php &#8212; user_agents.php The purpose of each file coincides with it&#8217;s name. To get us up and running we are only going to worry about autoload.php, config.php, database.php and routes.php. config.php The config.php file is the main configuration file for the framework. In this file you can control things like logging, character sets, extension prefixs, etc. The folks over at EllisLab have done a great job at commenting this file so I&#8217;m not going to go through the whole thing. The only thing I&#8217;m going to change here are lines 14 and 26. Line 14 holds the full web path to your CI installation. In the past I used to type this in by hand until I had the need to write portable apps that could be distributed and installed without much configuration on the users end. Since then I have resorted to using this code I found on the CI wiki. By replacing line 14 with that code you can set this variable and forget about it. Wherever your program ends up this config variable will be set automatically so you don&#8217;t have to worry about it. Line 26 of the config file holds the name of the index file. Since I use search engine friendly URLs where ever possible I just delete the value and leave it blank (just like the comment tells you to do). autoload.php Now that the config.php file is taken care of we turn our attention to the tools we need to build out app. What libraries, models, helpers, etc. are we going to need on a regular basis throughout the entire app? The answer to this question will probably differ based on what app your building, but I have found there are a number of common files I always load throughout any application: Libraries &#8211; database, session Helper &#8211; form, url, display, flash Config &#8211; program The libraries above, database and session, are the default CI libraries to handle database abstraction and user sessions (note, if your app doesn&#8217;t use a database consistently throughout the whole app you might not want to autoload this library). The form and url helpers are both default CI helpers but display and flash are two custom helper files I&#8217;ve developed to assist with some common tasks. I will discuss helpers in the next post. Finally, program is a custom config file that I create for all my applications which I will discuss shortly. database.php If you are app is interacting with a database then you need to update the database.php config file. This file stores the access information for the database or databases that your app will be interacting with. This file is pretty self-explanitory so I&#8217;m wont go to delve into it. routes.php The routes.php file allows you to define custom URLs and map them to specfic controllers and methods. This is a very powerful tool that comes built into the CI framework. The only thing we want to update in this file to get started is line 43. Right now it&#8217;s set for the default welcome message we saw before. I usually set this variable to home just because it&#8217;s pretty generic and tends to work well in URLs but you can set it to whatever makes sense to you and your app. program.php Now that I&#8217;ve discussed all the default CI files, I&#8217;m going to create a custom config file called program.php (the same one we auto-loaded above) and place it in the config folder. This file will store all the application wide configuration settings and information that I will be referring to both programmtically and manually. To see what this file looks like you can dowload an example for reference. At the very least this file will always have 2 variables: ci_version and program_version. Both are pretty straight forward in purpose, ci_version stores the current version of CI that I&#8217;ve used to build the app and program_version is the current version of my app. I&#8217;ll typically call upon the program_version and display it in the footer of the app and knowing the version of CI running comes in handy when updating or making any framework modifications. When building an app of any size you always want to build in a quick and easy way of taking the app offline. I accomplish this with the status variable. If the status is true then the program is online and everything is operational but if it&#8217;s false then things are offline. By creating a config variable for this I can easily refer to this flag throughout the program to determine whether or not input should be accepted and processed. Another thing I commonly store in the program config file is e-mail settings that will be used whenever an e-mail is sent from the app. This commonly consists of the from and reply-to address and names. Again, by storing this information here it&#8217;s easily accessed whenever sending an e-mail. Your program config file can store any type of system wide configuration information that your app will need to reference from many places. You could theoretically store this configuration information in a database but then you wouldn&#8217;t be able to take advantage of the native CI config tools available. In the end it&#8217;s up to you. Next up: Helpers That wraps up configuration. In the next post I will review some custom helper files I&#8217;ve developed and autoload in most of my applications.]]></description>
			<content:encoded><![CDATA[<p>The framework that you use to build your application will end up being the foundation of your program. Everything that your program does will revolve around how that framework works. Things like naming conventions, file paths and settings are dictated by the framework. But if you have chosen a good framework, like CodeIgniter (CI), you will be able to manipulate how that framework works and the tools it makes available to you by modifying it&#8217;s configuration information. In the <a href="http://www.christophermonnat.com/2009/04/building-applications-using-codeigniter-part-1-file-structure">first post</a> I talked about application file structure. Now that the structure is solid I&#8217;m going to look at how I configure the framework so that it works the way I expect.<br />
<span id="more-578"></span></p>
<h2>Config</h2>
<p>All of CI&#8217;s configuration files are stored in application/config.</p>
<p>- config<br />
&#8212; autoload.php<br />
&#8212; config.php<br />
&#8212; constants.php<br />
&#8212; database.php<br />
&#8212; doctypes.php<br />
&#8212; hooks.php<br />
&#8212; mimes.php<br />
&#8212; routes.php<br />
&#8212; smileys.php<br />
&#8212; user_agents.php</p>
<p>The purpose of each file coincides with it&#8217;s name. To get us up and running we are only going to worry about autoload.php, config.php, database.php and routes.php.</p>
<h2>config.php</h2>
<p>The config.php file is the main configuration file for the framework. In this file you can control things like logging, character sets, extension prefixs, etc. The folks over at <a href="http://www.ellislab.php">EllisLab</a> have done a great job at commenting this file so I&#8217;m not going to go through the whole thing. The only thing I&#8217;m going to change here are lines 14 and 26.</p>
<p>Line 14 holds the full web path to your CI installation. In the past I used to type this in by hand until I had the need to write portable apps that could be distributed and installed without much configuration on the users end. Since then I have resorted to using <a href="http://codeigniter.com/wiki/Automatic_configbase_url/">this code</a> I found on the CI wiki. By replacing line 14 with that code you can set this variable and forget about it. Wherever your program ends up this config variable will be set automatically so you don&#8217;t have to worry about it.</p>
<p>Line 26 of the config file holds the name of the index file. Since I use search engine friendly URLs where ever possible I just delete the value and leave it blank (just like the comment tells you to do).</p>
<h2>autoload.php</h2>
<p>Now that the config.php file is taken care of we turn our attention to the tools we need to build out app. What libraries, models, helpers, etc. are we going to need on a regular basis throughout the entire app? The answer to this question will probably differ based on what app your building, but I have found there are a number of common files I always load throughout any application:</p>
<p><strong>Libraries</strong> &#8211; database, session</p>
<p><strong>Helper</strong> &#8211; form, url, display, flash</p>
<p><strong>Config</strong> &#8211; program</p>
<p>The libraries above, database and session, are the default CI libraries to handle database abstraction and user sessions (note, if your app doesn&#8217;t use a database consistently throughout the whole app you might not want to autoload this library). The form and url helpers are both default CI helpers but display and flash are two custom helper files I&#8217;ve developed to assist with some common tasks. I will discuss helpers in the next post. Finally, program is a custom config file that I create for all my applications which I will discuss shortly.</p>
<h2>database.php</h2>
<p>If you are app is interacting with a database then you need to update the database.php config file. This file stores the access information for the database or databases that your app will be interacting with. This file is pretty self-explanitory so I&#8217;m wont go to delve into it.</p>
<h2>routes.php</h2>
<p>The routes.php file allows you to define custom URLs and map them to specfic controllers and methods. This is a very powerful tool that comes built into the CI framework. The only thing we want to update in this file to get started is line 43. Right now it&#8217;s set for the default welcome message we saw before. I usually set this variable to <strong>home</strong> just because it&#8217;s pretty generic and tends to work well in URLs but you can set it to whatever makes sense to you and your app.</p>
<h2>program.php</h2>
<p>Now that I&#8217;ve discussed all the default CI files, I&#8217;m going to create a custom config file called program.php (the same one we auto-loaded above) and place it in the config folder. This file will store all the application wide configuration settings and information that I will be referring to both programmtically and manually. To see what this file looks like you can <a href="http://www.christophermonnat.com/wp-content/uploads/2009/04/program.zip">dowload an example</a> for reference.</p>
<p>At the very least this file will always have 2 variables: <strong>ci_version</strong> and <strong>program_version</strong>. Both are pretty straight forward in purpose, ci_version stores the current version of CI that I&#8217;ve used to build the app and program_version is the current version of my app. I&#8217;ll typically call upon the program_version and display it in the footer of the app and knowing the version of CI running comes in handy when updating or making any framework modifications.</p>
<p>When building an app of any size you always want to build in a quick and easy way of taking the app offline. I accomplish this with the <strong>status</strong> variable. If the status is true then the program is online and everything is operational but if it&#8217;s false then things are offline. By creating a config variable for this I can easily refer to this flag throughout the program to determine whether or not input should be accepted and processed.</p>
<p>Another thing I commonly store in the program config file is e-mail settings that will be used whenever an e-mail is sent from the app. This commonly consists of the from and reply-to address and names. Again, by storing this information here it&#8217;s easily accessed whenever sending an e-mail.</p>
<p>Your program config file can store any type of system wide configuration information that your app will need to reference from many places. You could theoretically store this configuration information in a database but then you wouldn&#8217;t be able to take advantage of the native <a href="http://codeigniter.com/user_guide/libraries/config.html">CI config tools</a> available. In the end it&#8217;s up to you.</p>
<h2>Next up: Helpers</h2>
<p>That wraps up configuration. In the next post I will review some custom helper files I&#8217;ve developed and autoload in most of my applications.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.christophermonnat.com/2009/05/building-applications-using-codeigniter-part-2-configuration/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>How-to Ensure a Secure Connection Using PHP</title>
		<link>http://www.christophermonnat.com/2009/05/how-to-ensure-a-secure-connection/</link>
		<comments>http://www.christophermonnat.com/2009/05/how-to-ensure-a-secure-connection/#comments</comments>
		<pubDate>Fri, 01 May 2009 10:00:04 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[CodeIgniter]]></category>
		<category><![CDATA[How-to]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.christophermonnat.com/?p=636</guid>
		<description><![CDATA[Image via Wikipedia When submitting sensitive information over the web it&#8217;s important to ensure that the requested page is being accessed via an HTTPS encrypted connection. I&#8217;ve come across some forms that don&#8217;t check whether a secure connection has been made or not. In other words, you can delete the S from HTTP and instead of redirecting the user back to the HTTPS connection the form is just displayed unsecured. This is a BIG NO NO&#8230; as a programmer you cannot rely on the visitor, or even other developers who would be linking to the form, to request a form securely. In this post I will review how you can ensure that your users are accessing certain pages using a secure connection. The Server Superglobal How can you tell if your user is requesting a certain page using a secure connection (HTTPS)? Enter the PHP server surperglobal. &#8220;$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server.&#8221; - PHP Manual (http://www.php.net) There are 2 elements within this array that you can check that will tell you whether the user has made a secure request or not: https and server_port. Programmer Beware Something to keep in mind is that each web server will provide or not provide certain information in the $_SERVER array depending on their configuration. The PHP manual also points this out: &#8220;There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here.&#8221; - PHP Manual (http://www.php.net) So I guess that brings us back to the original question: how can you tell if your user is requesting a certain page using a secure connection (HTTPS)? Of the 2 elements mentioned above, server_port is part of the CGI 1.1 specification so the chances are good that element will be available in most servers. You can check for the availability of the https element if you wish but you should also include a check of the server_port as a fallback. The Code There is a good code example in the comments of the PHP manual of a function that checks whether or not the user has made a secure request: This example function makes use of both the https and server_port elements of the superglobal array and also takes into account the different values that might be provided based on the web server. The only thing I will mention about using the server_port element is to make sure you know what port your server is using for HTTPS connections. I believe 443 is the standard, but ports can be changed so you just want to make sure you are checking the correct port for your server. What about CodeIgniter (CI)? If your programming using CI, you could certainly put the function above in a helper and call it whenever necessary. Or, a technique I&#8217;ve used successfully in the past, is to put the check in a custom library and auto load it. When you do it this way the connection is tested every time a page is loaded automatically without you having to make any additional function calls. And instead of returning TRUE or FALSE you can simply redirect the user to the requested page using HTTPS instead of HTTP which truly automates the process. One thing that can trip you up when making secure connections using CI is the address you&#8217;ve entered on line 14 of application/config/config.php. If you enter just a static address starting with HTTP then HTTP will be used when calling any URL helper function like site_url() or anchor(). To avoid this issue,&#160; you can replace line 14 with the following code from the CI wiki: This code will automatically set the base_url config element so you don&#8217;t have to. This also comes in real handy when writing portable code that you want to distribute to other users or clients for installation on their own servers. That&#8217;s a wrap That does it for making sure your files are being accessed securely. If you have any questions or use a different technique for checking secure connections please share them by posting a comment.]]></description>
			<content:encoded><![CDATA[<div class="zemanta-img" style="margin: 1em; display: block;">
<div>
<dl class="wp-caption alignright" style="width: 171px;">
<dt class="wp-caption-dt"><a href="http://en.wikipedia.org/wiki/Image:SympaticoSecurityManagerSafe.png"><img title="‎Sympatico Security Manager" src="http://upload.wikimedia.org/wikipedia/en/9/99/SympaticoSecurityManagerSafe.png" alt="‎Sympatico Security Manager" width="161" height="131"></a></dt>
<dd class="wp-caption-dd zemanta-img-attribution" style="font-size: 0.8em;">Image via <a href="http://en.wikipedia.org/wiki/Image:SympaticoSecurityManagerSafe.png">Wikipedia</a></dd>
</dl>
</div>
</div>
<p>When submitting sensitive information over the web it&#8217;s important to <strong>ensure</strong> that the requested page is being accessed via an HTTPS encrypted connection. I&#8217;ve come across some forms that don&#8217;t check whether a secure connection has been made or not. In other words, you can delete the S from HTTP and instead of redirecting the user back to the HTTPS connection the form is just displayed unsecured. This is a BIG NO NO&#8230; as a programmer you cannot rely on the visitor, or even other developers who would be linking to the form, to request a form securely. In this post I will review how you can ensure that your users are accessing certain pages using a secure connection.<br />
<span id="more-636"></span></p>
<h2>The Server Superglobal</h2>
<p>How can you tell if your user is requesting a certain page using a secure connection (HTTPS)? Enter the <a href="http://www.php.net/manual/en/reserved.variables.server.php">PHP server surperglobal</a>.</p>
<p>&#8220;<var class="varname">$_SERVER</var> is an array containing information    such as headers, paths, and script locations. The entries in this    array are created by the web server.&#8221;<br />
- PHP Manual (http://www.php.net)</p>
<p>There are 2 elements within this array that you can check that will tell you whether the user has made a secure request or not: <strong>https</strong> and <strong>server_port</strong>.</p>
<h2>Programmer Beware</h2>
<p>Something to keep in mind is that each web server will provide or not provide certain information in the $_SERVER array depending on their configuration. The PHP manual also points this out:</p>
<p>&#8220;There is no guarantee that    every web server will provide any of these; servers may omit some,    or provide others not listed here.&#8221;<br />
- PHP Manual (http://www.php.net)</p>
<p>So I guess that brings us back to the original question: how can you tell if your user is requesting a certain page using a secure connection (HTTPS)? Of the 2 elements mentioned above, server_port is part of the CGI 1.1 specification so the chances are good that element will be available in most servers. You can check for the availability of the https element if you wish but you should also include a check of the server_port as a fallback.</p>
<h2>The Code</h2>
<p>There is a good code example in the <a href="http://www.php.net/manual/en/reserved.variables.server.php#89306">comments of the PHP manual</a> of a function that checks whether or not the user has made a secure request:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
function isSSL(){

if($_SERVER['https'] == 1) /* Apache */ {
return TRUE;
} elseif ($_SERVER['https'] == 'on') /* IIS */ {
return TRUE;
} elseif ($_SERVER['SERVER_PORT'] == 443) /* others */ {
return TRUE;
} else {
return FALSE; /* just using http */
}

}
?&gt;
</pre>
<p>This example function makes use of both the https and server_port elements of the superglobal array and also takes into account the different values that might be provided based on the web server. The only thing I will mention about using the server_port element is to make sure you know what port your server is using for HTTPS connections. I believe 443 is the standard, but ports can be changed so you just want to make sure you are checking the correct port for your server.</p>
<h2>What about CodeIgniter (CI)?</h2>
<p>If your programming using CI, you could certainly put the function above in a helper and call it whenever necessary. Or, a technique I&#8217;ve used successfully in the past, is to put the check in a custom library and auto load it. When you do it this way the connection is tested every time a page is loaded automatically without you having to make any additional function calls. And instead of returning TRUE or FALSE you can simply redirect the user to the requested page using HTTPS instead of HTTP which truly automates the process.</p>
<p>One thing that can trip you up when making secure connections using CI is the address you&#8217;ve entered on line 14 of application/config/config.php. If you enter just a static address starting with HTTP then HTTP will be used when calling any URL helper function like site_url() or anchor(). To avoid this issue,&nbsp; you can replace line 14 with the following code from the <a href="http://codeigniter.com/wiki/Automatic_configbase_url/">CI wiki</a>:</p>
<pre class="brush: php; title: ; notranslate">

$config['base_url'] = ((isset($_SERVER['HTTPS']) &amp;amp;&amp;amp; $_SERVER['HTTPS'] == &quot;on&quot;) ? &quot;https&quot; : &quot;http&quot;);
$config['base_url'] .= &quot;://&quot;.$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),&quot;&quot;,$_SERVER['SCRIPT_NAME']); 
</pre>
<p>This code will automatically set the base_url config element so you don&#8217;t have to. This also comes in real handy when writing portable code that you want to distribute to other users or clients for installation on their own servers.</p>
<h2>That&#8217;s a wrap</h2>
<p>That does it for making sure your files are being accessed securely. If you have any questions or use a different technique for checking secure connections please share them by posting a comment.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.christophermonnat.com/2009/05/how-to-ensure-a-secure-connection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

