<?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>Nettuts+ &#187; PHP</title>
	<atom:link href="http://net.tutsplus.com/category/tutorials/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://net.tutsplus.com</link>
	<description>Web Development &#38; Design Tutorials</description>
	<lastBuildDate>Fri, 20 Nov 2009 19:56:34 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Build an RSS 2.0 Feed with CodeIgniter</title>
		<link>http://net.tutsplus.com/tutorials/php/building-an-rss-2-0-feed-with-codeigniter/</link>
		<comments>http://net.tutsplus.com/tutorials/php/building-an-rss-2-0-feed-with-codeigniter/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 19:19:04 +0000</pubDate>
		<dc:creator>Drazen Mokic</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[code igniter]]></category>
		<category><![CDATA[codeigniter]]></category>
		<category><![CDATA[framework]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=7811</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/496_ci/ci.jpg" alt="Build an RSS 2.0 Feed with CodeIgniter" width="200" height="200"/>]]></description>
			<content:encoded><![CDATA[<p>
	In this tutorial, we will build a RSS 2.0 Feed with the PHP framework <a href="http://www.codeigniter.com">CodeIgniter</a>. After this tutorial, you will be able to build a feed for any custom website in no time at all.
</p>
<p><span id="more-7811"></span></p>
<h3>Tutorial Details</h3>
<ul>
<li><b>Program</b>: CodeIgniter PHP Framework</li>
<li><b>Version</b>: 1.7.1</li>
<li><b>Difficulty:</b> Easy</li>
<li><b>Estimated Completion Time:</b> 30 minutes</li>
</ul>
<h3>Step 1: What we Need</h3>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/496_ci/img7.jpg" alt="Finished Product" />
</div>
<p>
	First, we&#8217;ll take a look at the tools needed to get started. Besides an installation of <a href="http://codeigniter.com/">CodeIgniter</a>, we need a running MySQL database with some content from which we can build our feed.
</p>
<p>
	For this purpose, here are some dummy entries you can import. Create a database called <b>tut_feeds</b>. Then,  copy the following code, and import it into your MySQL database.
</p>
<pre name="code" class="sql">
    CREATE TABLE IF NOT EXISTS `posts` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `title` varchar(120) NOT NULL,
      `text` text NOT NULL,
      `date` date NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM;

    INSERT INTO `posts` (`id`, `title`, `text`, `date`) VALUES
    (1, 'Some great article', 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using ''Content here, content here'', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for ''lorem ipsum'' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).', '2009-08-10'),
    (2, 'Another great article', 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using ''Content here, content here'', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for ''lorem ipsum'' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).', '2009-08-10'),
    (3, 'News from myfeed', 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using ''Content here, content here'', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for ''lorem ipsum'' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).', '2009-08-10');
</pre>
<p>This is how it should appear in phpmyadmin. After you have pasted the code in, press the <b>Ok</b> button on the right side.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/496_ci/img1.jpg" border="0" /></div>
<p>If everything works correctly, you should see have something like this:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/496_ci/img2.jpg" border="0" /></div>
<p><!-- Step 2 --></p>
<h3>Step 2: Setting up CodeIgniter</h3>
<p>Before we start writing code, we need to configure CodeIgniter.</p>
<p>Browse to your CI folder, and then into <b>system/application/config</b>. We will need to edit the following files:</p>
<ul>
<li>autoload.php</li>
<li>config.php</li>
<li>database.php</li>
<li>routes.php</li>
</ul>
<p><strong>Edit the autoload.php like so:</strong></p>
<pre name="code" class="php">
	$autoload['libraries'] = array('database');
</pre>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/496_ci/img3.jpg" border="0" /></div>
<p>This will tell CI to load the database automatically; so we don&#8217;t need to load it every time.</p>
<p><strong>Edit the config.php like so:</strong></p>
<pre name="code" class="php">
	$config['base_url'] = "http://localhost/YOUR DIRECTORY";
</pre>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/496_ci/img4.jpg" border="0" /></div>
<p>You need to replace <b>tutorials/ci_feeds</b> with your directory and CI folder.</p>
<p><strong>Edit the database.php like so:</strong></p>
<pre name="code" class="php">
	$db['default']['hostname'] = "localhost"; // your host
    $db['default']['username'] = "root";
    $db['default']['password'] = "";
    $db['default']['database'] = "tut_feeds";
</pre>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/496_ci/img5.jpg" border="0" /></div>
<p>
	With these settings, we tell CI which database to use. Here you also have to replace <i>hostname</i>, <i>username</i> and<br />
	<i>password</i> with your personal database info.
</p>
<p><strong>Edit the routes.php like this:</strong></p>
<pre name="code" class="php">
	$route['default_controller'] = "Feed";
</pre>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/496_ci/img6.jpg" border="0" /></div>
<p>
	The default controller is the <i>&#8220;index&#8221;</i> controller for your application. Every time you open<br />
    <i>localhost/YOUR DIRECTORY</i>, this default controller will be loaded first. We&#8217;ll create the <i>feed</i> in the next step.
</p>
<p><!-- Step 3 --></p>
<h3>Step 3: Creating the Feed Controller</h3>
<p>
	In this controller, all the magic happens. Browse to <b>system/application/controllers</b> and create a new file<br />
	called <b>feed.php</b>. Next, create the <i>Feed</i> controller and have it extend the parent CI Controller.
</p>
<pre name="code" class="php">
	class Feed extends Controller {

      function Feed()
      {
		parent::Controller();
      }
}
</pre>
<p>
	If you are already confused please have a look at Jeffrey&#8217;s<br />
    <a href="http://net.tutsplus.com/videos/screencasts/easy-development-with-codeigniter/">Easy Development with CodeIgniter</a> tutorial.<br />
    After you&#8217;ve learned the basics, return to continue this tutorial! <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />
</p>
<p>
	Before the next step, we&#8217;ll make use of CI&#8217;s great helpers. Load the <i>xml</i> and <i>text</i> helper.
</p>
<pre name="code" class="php">
class Feed extends Controller {

      function Feed()
      {
        parent::Controller();

        $this->load->helper('xml');
		$this->load->helper('text');
      }
}
</pre>
<p><!-- Step 4 --></p>
<h3>Step 4: Creating the Model</h3>
<p>
	Next, will create a model to receive data from the database. If you don&#8217;t know what models are, have a look at the CI<br />
	<a href="http://codeigniter.com/user_guide/general/models.html">userguide</a>. Browse to <b>system/application/models</b><br />
    and create a file called <b>posts_model.php</b>.
</p>
<pre name="code" class="php">
class Posts_model extends Model {

	// get all postings
	function getPosts($limit = NULL)
	{
		return $this->db->get('posts', $limit);
	}
}
</pre>
<p>
	We are using <a href="http://codeigniter.com/user_guide/database/active_record.html">active records</a> to receive data<br />
    from the database. The first parameter declares the table we want to use and with the second we can set a limit &#8211; so we<br />
    can tell CI how many records we want to retrieve.
</p>
<p>
	Perhaps you&#8217;ve noticed that <i>$limit</i> is set to NULL by default. This makes it possible to set a limit, but <b>you don&#8217;t have to</b>.<br />
    If you don&#8217;t set a second parameter, this function will simply return all records.
</p>
<p><!-- Step 5 --></p>
<h3>Step 5: Back to the Feed Controller</h3>
<p>
	Now that we&#8217;ve created our model, we can continue with our <i>feed controller</i>. We&#8217;ll load the <i>posts_model</i> that we just created.
</p>
<pre name="code" class="php">
class Feed extends Controller {

      function Feed()
      {
        parent::Controller();

        $this->load->helper('xml');
		$this->load->helper('text');
        $this->load->model('posts_model', 'posts');
      }
}
</pre>
<p>
	With the second parameter, we assign our model to a different object name &#8211; so we have less to type <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> . Now we create the <i>index</i><br />
    method which is the method called by default. Let&#8217;s set up some information for the feed view later too.
</p>
<pre name="code" class="php">
	function index()
	{
		$data['feed_name'] = 'MyWebsite.com'; // your website
		$data['encoding'] = 'utf-8'; // the encoding
        $data['feed_url'] = 'http://www.MyWebsite.com/feed'; // the url to your feed
        $data['page_description'] = 'What my site is about comes here'; // some description
        $data['page_language'] = 'en-en'; // the language
        $data['creator_email'] = 'mail@me.com'; // your email
        $data['posts'] = $this->posts->getPosts(10);
        header("Content-Type: application/rss+xml"); // important!
	}
</pre>
<p>
	While the majority of the information above is easy to understand, we will have a look at two of them.<br />
    <i>header(&#8221;Content-Type: application/rss+xml&#8221;);</i> is a very important part. This tells the browser to parse it as<br />
     an RSS Feed. Otherwise the browser will try to parse it as plain text or html.
</p>
<p>
	With <i>$data['posts'] = $this->posts->getPosts(10);</i> we are using our model and are storing all records in the <i>$posts</i> array.<br />
    I set the limit to 10; so it will return, at most, 10 records. You can set this value higher or lower if you want. If we leave it<br />
    blank, like <i>$data['posts'] = $this->posts->getPosts();</i>, it would return all records.
</p>
<p>
	Finally, we need to load the <i>view</i> which we will create in the next step.
</p>
<pre name="code" class="php">
	function index()
	{
		$data['feed_name'] = 'MyWebsite.com';
		$data['encoding'] = 'utf-8'; // the encoding
        $data['feed_url'] = 'http://www.MyWebsite.com/feed';
        $data['page_description'] = 'What my site is about comes here';
        $data['page_language'] = 'en-en';
        $data['creator_email'] = 'mail@me.com';
        $data['posts'] = $this->posts->getPosts(10);
        header("Content-Type: application/rss+xml"); 

        $this->load->view('rss', $data);
	}
</pre>
<p>
	Our <i>$data</i> array is passed as the second parameter to the view file, so we can access it in the view.<br />
    Your feed controller should now look like this:
</p>
<pre name="code" class="php">
class Feed extends Controller {

	function Feed()
	{
		parent::Controller();

		$this->load->helper('xml');
		$this->load->helper('text');
        $this->load->model('posts_model', 'posts');
	}

	function index()
	{
		$data['feed_name'] = 'MyWebsite.com';
		$data['encoding'] = 'utf-8';
        $data['feed_url'] = 'http://www.MyWebsite.com/feed';
        $data['page_description'] = 'What my site is about comes here';
        $data['page_language'] = 'en-en';
        $data['creator_email'] = 'mail@me.com';
        $data['posts'] = $this->posts->getPosts(10);
        header("Content-Type: application/rss+xml");

		$this->load->view('rss', $data);
	}

}
</pre>
<p><!-- Step 6 --></p>
<h3>Step 6: Creating the View</h3>
<p>
	Finally we have to create the view file &#8211; our output. Browse to <b>system/application/views</b> and crate a file called<br />
    <b>rss.php</b>.
</p>
<p>
	First we set the <i>xml version</i> and the <i>encoding</i> within the head.
</p>
<pre name="code" class="php">
	&lt;?php  echo '&lt;?xml version="1.0" encoding="' . $encoding . '"?>' . "\n"; ?>
</pre>
<p>
	Followed by some rss meta information.
</p>
<pre name="code" class="php">
    <rss version="2.0"
        xmlns:dc="http://purl.org/dc/elements/1.1/"
        xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
        xmlns:admin="http://webns.net/mvcb/"
        xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
        xmlns:content="http://purl.org/rss/1.0/modules/content/">

        <channel>
</pre>
<p>
	Now we will access the array <i>$data</i> from the previous step. We can access this data via the array keys, like so:
</p>
<pre name="code" class="php">
<link><?php echo $feed_url; ?></link>
    <description><?php echo $page_description; ?></description>
    <dc:language><?php echo $page_language; ?></dc:language>
    <dc:creator><?php echo $creator_email; ?></dc:creator>

    <dc:rights>Copyright <?php echo gmdate("Y", time()); ?></dc:rights>
    <admin:generatorAgent rdf:resource="http://www.codeigniter.com/" />
</pre>
<p>
	Now we need to loop, with <i>foreach</i>, to get all records.
</p>
<pre name="code" class="php">
    <?php foreach($posts->result() as $post): ?>

       <item>
<link><?php echo site_url('YOUR URL' . $post->id) ?></link>
          <guid><?php echo site_url('YOUR URL' . $post->id) ?></guid>

          	<description><![CDATA[ <?php echo character_limiter($post->text, 200); ?> ]]&gt;</description>
<pubDate><?php echo $post->date; ?></pubDate>
        </item>

    <?php endforeach; ?>

    	</channel>
	<</rss>
</pre>
<p>
	For <i>link</i> and <i>guide</i>, you have to set a link to your controller where the posts are fetched. For example: <i>my/posts/$post->id</i>.
</p>
<p>
	I hope you noticed CDATA. This is used for text-output (content). Remember how we learned in the head that this is <i>xml</i>;<br />
    so it has to be xml valid. If we don&#8217;t set CDATA we&#8217;ll potentially end up with invalid markup.</p>
<p><!-- Step 7 --></p>
<h3>Step 7: Overview</h3>
<p>
	Now your files should look like this:
</p>
<p><b>system/application/controllers/feed.php</b></p>
<pre name="code" class="php">
class Feed extends Controller {

	function Feed()
	{
		parent::Controller();

		$this->load->helper('xml');
		$this->load->helper('text');
        $this->load->model('posts_model', 'posts');
	}

	function index()
	{
		$data['feed_name'] = 'MyWebsite.com';
		$data['encoding'] = 'utf-8';
        $data['feed_url'] = 'http://www.MyWebsite.com/feed';
        $data['page_description'] = 'What my site is about comes here';
        $data['page_language'] = 'en-en';
        $data['creator_email'] = 'mail@me.com';
        $data['posts'] = $this->posts->getPosts(10);
        header("Content-Type: application/rss+xml");

		$this->load->view('rss', $data);
	}

}
</pre>
<p><b>system/application/models/posts_model.php</b></p>
<pre name="code" class="php">
class Posts_model extends Model {

	// get all postings
	function getPosts($limit = NULL)
	{
		return $this->db->get('posts', $limit);
	}
}
</pre>
<p><b>system/application/views/rss.php</b></p>
<pre name="code" class="php">
	<?php  echo '<?xml version="1.0" encoding="' . $encoding . '"?>' . "\n"; ?>
    <rss version="2.0"
        xmlns:dc="http://purl.org/dc/elements/1.1/"
        xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
        xmlns:admin="http://webns.net/mvcb/"
        xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
        xmlns:content="http://purl.org/rss/1.0/modules/content/">

        <channel>
<link><?php echo $feed_url; ?></link>
        <description><?php echo $page_description; ?></description>
        <dc:language><?php echo $page_language; ?></dc:language>
        <dc:creator><?php echo $creator_email; ?></dc:creator>

        <dc:rights>Copyright <?php echo gmdate("Y", time()); ?></dc:rights>
        <admin:generatorAgent rdf:resource="http://www.codeigniter.com/" />

        <?php foreach($posts->result() as $post): ?>

            <item>
<link><?php echo site_url('blog/posting/' . $post->id) ?></link>
              <guid><?php echo site_url('blog/posting/' . $post->id) ?></guid>

                <description><![CDATA[ <?php echo character_limiter($post->text, 200); ?> ]]&gt;</description>
<pubDate><?php echo $post->date; ?></pubDate>
            </item>

        <?php endforeach; ?>

        </channel>
    </rss>
</pre>
<p>And our feed looks like this, just with other content <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/496_ci/img7.jpg" border="0" /></div>
<p><!-- Step 7 --></p>
<h3>Conclusion</h3>
<p>
	I hope you&#8217;ve learned how easy it is to build an RSS 2.0 Feed with the power of CodeIgniter. For more tutorials and screencasts on CodeIgniter, check out Jeffrey`s <a href="http://net.tutsplus.com/videos/screencasts/codeigniter-from-scratch-day-7-pagination/">CodeIgniter from Scratch</a> series.
</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for the best web development tutorials on the web.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/php/building-an-rss-2-0-feed-with-codeigniter/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>How to Create a Photo Gallery using the Flickr API</title>
		<link>http://net.tutsplus.com/tutorials/php/how-to-create-a-photo-gallery-using-the-flickr-api/</link>
		<comments>http://net.tutsplus.com/tutorials/php/how-to-create-a-photo-gallery-using-the-flickr-api/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 18:22:34 +0000</pubDate>
		<dc:creator>Paul Burgess</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[flickr]]></category>
		<category><![CDATA[gallery]]></category>
		<category><![CDATA[photo gallery]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=7708</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/491_flickr/200x200.jpg" alt="How to Create a Photo Gallery using the Flickr API " />]]></description>
			<content:encoded><![CDATA[<p>Flickr is, without doubt, the biggest and best photography website on the internet. There are lots of widgets, badges and plugins which allow you to display your latest Flickr photos on your website, but we&#8217;ll take it a step further by tapping straight into Flickr and integrating your photostream into your website, giving you a photo gallery that is a breeze to update.
</p>
<p><span id="more-7708"></span></p>
<div class="tutorial_image">
<a href="http://nettuts.s3.amazonaws.com/491_flickr/Flickr_API-sample files.zip"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg"></a><br />
<a href="http://nettuts-fd.iampaulburgess.co.uk/"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_demo_nm.jpg"></a>
</div>
<p>We&#8217;ll be creating <a title="this photo gallery" href="http://nettuts-fd.iampaulburgess.co.uk">this photo gallery</a> using the Flickr API and <a title="phpFlickr" href="http://phpflickr.com/">phpFlickr</a> . If the letters &#8216;A,P &amp; I&#8217; are enough to strike fear into your  heart, don&#8217;t worry, we will take it slow and give full code examples  that you can copy.</p>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/491_flickr/finalproject.jpg" alt="Final Project" />
</div>
<p>Flickr have also recently launched <a href="http://www.flickr.com/services/">The App Garden</a>, which is a showcase of tools, toys and sites which use the Flickr API to offer something useful or fun. Once you get to grips with using the API, you can let your imagination conjure up a new way to use it and submit your app. </p>
<p>
  For this tutorial I am presuming that you already have a Flickr account, and access to a server that runs PHP and PEAR.</p>
<h3>The Outline</h3>
<ul>
<li> Get a Flickr API key </li>
<li> Download the phpFlickr files </li>
<li> Build a gallery page to display our thumbnails (with pagination)</li>
<li> Make a photo page to show our photos (with previous and next navigation)</li>
</ul>
<h3>Step 1 &#8211; Get a Flickr API key</h3>
<p>
Your API key is your own unique series of numbers and letters which grant you access to Flickr&#8217;s services. Go here:  http://www.flickr.com/services/apps/create/apply/
</p>
<p>
Here you must decide if you are going to use Flickr for commercial or non-commercial purposes. Flickr provide good explanations as to which  you should choose, chances are you&#8217;ll need a non-commercial API key,  which is what I am choosing for this demo.</p>
<p>
Follow the steps and fill in all your details.</p>
<p> You should then be presented with your unique key which will appear as a series of random numbers and letters like so:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/491_flickr/api-key.png" alt="API key example" width="546" height="222"></div>
<p>You&#8217;ll also see a number called &#8216;Secret;&#8217; ignore that for now. For this exercise  we only need the key; make a note of it as we&#8217;ll need it soon.</p>
<p>If you use the API to build a cool tool or site later on, you might want to submit and feature whatever you build in the Flickr App Garden. You can click on &#8216;Edit app details&#8217; to fill in the info.</p>
<blockquote><p>Pay particular attention to the tips and advice  given in the <a href="http://www.flickr.com/services/api/tos/">API Terms of Use</a> and the <a href="http://www.flickr.com/guidelines.gne">Community Guidelines</a>, if you abuse it, you&#8217;ll lose it.</p>
</blockquote>
<p>
  Now on to the exciting stuff&#8230; </p>
<h3>Step 2 &#8211; Download phpFlickr&nbsp; </h3>
<p>
  <a title="phpFlickr" href="http://phpflickr.com/" id="kguo">phpFlickr</a> is a project by <a href="http://www.dancoulter.com/">Dan Coulter</a>. It is a class written in PHP which acts as a wrapper for Flickr&#8217;s API. The files process the data provided by Flickr and return arrays in PHP, which we use to display our photos</p>
<p>
We need to download the files that we will later include in our webpage, and will do all the complicated work for us. Visit <a title="phpflickr.com" href="http://phpflickr.com/" id="y5sq">phpflickr.com</a> or skip straight to <a title="The download page at Google Code" href="http://code.google.com/p/phpflickr/downloads/list">the download page at Google Code.</a> In this demo, we&#8217;ll be using the zip file:   	phpFlickr-2.3.1 (zip)
</p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/491_flickr/download-link.png" alt="Download link" width="444" height="265" />
</div>
<p>
  Download and unzip it. For this tutorial, we only need the PEAR folder and the phpFlickr.php file. Upload the files to your web directory</p>
<h3>Step 3 &#8211; Basic Setup and Simple Configuration &nbsp; </h3>
<p>
  Now  we have all we need to connect with Flickr and retrieve our photos. We&#8217;ll make two pages: one to show our thumbnails and one to show the photo. All of the code will be available as complete pages at the end of the tutorial. </p>
<p>
  These code examples are all working on the basis that your files are on the root of your server &#8211; or all in the same folder. Before anything else, we need to create a cache folder in order for phpFlickr  to work properly. Create a folder called &#8216;cache&#8217; in your web directory  and give it writable permissions (CHMOD 777). </p>
<p>
  Now we&#8217;ll build a page that displays our thumbnails and has some simple paging. In the example gallery, this is index.php &#8211; and <a title="looks like this" href="http://nettuts-fd.iampaulburgess.co.uk/" id="mhb6">looks like this</a>.</p>
<p>
Before we go any further, we need to set two main variables in the config.php file.</p>
<p>Open config.php. You&#8217;ll see it&#8217;s just asking for two things: your API key and your Flickr username. </p>
<p>First, enter your API key &#8211; the long random set of numbers and letters you were given earlier on by Flickr. Keep your info inside the quote marks. </p>
<pre name="code" class="php">// insert your API key
$key=&quot;ENTER YOUR FLICKR API KEY HERE&quot;;</pre>
<p>Now for your Flickr username; this is  not your Yahoo sign-in username or your Flickr screename &#8211; but the  username you use for Flickr itself. To double check, sign in to Flickr and look at the top of the page where it says &#8216;Signed in as&#8230;&#8217; &#8211; that is your username. So let&#8217;s declare our username as a variable:</p>
<pre name="code" class="php">// enter your Flickr username
$username=&quot;YOUR FLICKR USERNAME HERE&quot;;</pre>
<p>Save the changes to config.php and upload &#8211; you shouldn&#8217;t need that file again. </p>
<h3>Step 4 &#8211; Building the Thumbnails Page</h3>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/491_flickr/finalproject.jpg" alt="Final Project" />
</div>
<p>On to the page itself. Here&#8217;s a breakdown of what we are doing at the top of the page, which cues up everything ready for the action: </p>
<p>
  We are going to include some Previous and Next links with a small  bit of code further down the page. The thumbnails we are going to show  depend on what page we are on, so we run a simple if  statement which will grab our page number. If there&#8217;s a &#8216;fpage&#8217; query in  the url, use that. If not, we are on page one.</p>
<pre name="code" class="php">&lt;?php
  // get page number from the url - if there isn't one - we're on page 1
  $page = isset($_GET['page']) ? $_GET['page'] : 1;
  </pre>
<p>  Next we include the core phpFlickr file that has everything we need in it communicate with Flickr.</p>
<pre name="code" class="php">// inclue the core file
  require_once('phpFlickr.php');
  </pre>
<p>
  Now we fire up a new class from the phpFlickr file using our API key that we got earlier.</p>
<pre name="code" class="php">
// Fire up the main phpFlickr class
$f = new phpFlickr($key);
  </pre>
<p>
phpFlickr uses caching to speed the  process up. There are options of using a database technique but for  this tutorial we will use the simpler cache folder option. We need  a folder called &#8216;cache&#8217; that is writable, meaning that the system has  access to it and can alter its contents. To do this set the folders&#8217;  permissions to 777 via your FTP program. Then we add this line to enable it: </p>
<pre name="code" class="php">$f-&gt;enableCache("fs", "cache");
  </pre>
<p>
  We call the people_findByUsername method which returns an array:</p>
<pre name="code" class="php">$result = $f-&gt;people_findByUsername($username);
  </pre>
<p>
  From that array, we also need your unique user id (your Flickr id that look  like this: 11221312@N00, declared here as $nsid) which we get like so:</p>
<pre name="code" class="php">// grab our unique user id from the $result array
  $nsid = $result["id"];
  </pre>
<p>
Next, we call the people_getPublicPhotos method, which again returns an array that we will call $photos. In  this line, we are also passing through our id which we got in the line  above ($nsid). NULL refers to the &#8216;extras&#8217; option which we&#8217;re not  concerned with right now. We are also stating the number of thumbnails  we want to display (21), and are passing through the page to  start on ($page) which relates back to the $page variable from the top of  the page:</p>
<pre name="code" class="php"> $photos = $f-&gt;people_getPublicPhotos($nsid, NULL, NULL, 21, $page);
  </pre>
<p>
  The last bit we need to set the page up is a little bit of info we need for the paging to work. We  access the $photos array we created above, and pull out the the total  number of pages, plus the total amount of photos in our photostream:</p>
<pre name="code" class="php">$pages = $photos[photos][pages]; // returns total number of pages
  $total = $photos[photos][total]; // returns how many photos there are in total
  ?&gt;
  </pre>
<p>
  Notice we&#8217;re closing the php section off here with the ?&gt; Now we have all we need to get the first 21 thumbnails from our Flickr photostream and display them. We&#8217;ll carry on with the page now, adding some html, using PHP to show the images, and include some simple paging links. So let&#8217;s start by writing some basic html. </p>
<pre name="code" class="php"> &lt;!DOCTYPE html  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&gt;
&lt;title&gt;Nettuts Flickr Gallery Demo&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;

&lt;h1&gt;My photo gallery&lt;/h1&gt;
&lt;div id="thumbs"&gt;
  </pre>
<p>
  Nothing out of the ordinary here; just setting up the html and starting an area for the thumbnails. The next step is to fill our div called &#8216;thumbs&#8217; with our thumbnails like so:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/491_flickr/thumbnails-example.jpg" alt="Thumbnails example" width="601" height="224"></div>
<p>
Note we&#8217;re opening php again with &lt;?php:</p>
<p>
We&#8217;ll  use a foreach loop to run through the $photos array and to get to the  photo element ($photo), which holds the info we need for the thumbnails.<br />
See the comments in the code for an explanation of what&#8217;s going on: </p>
<pre name="code" class="php">
&lt;?php
// loop through each photo
&nbsp;foreach ($photos['photos']['photo'] as $photo) {
&nbsp;&nbsp;
// print out a link to the photo page, attaching the id of the photo
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; echo "&lt;a href=\"photo.php?id=$photo[id]\" title=\"View $photo[title]\"&gt;";
&nbsp;&nbsp;&nbsp;
// This next line uses buildPhotoURL to construct the location of our image, and we want the 'Square' size
// It also gives the image an alt attribute of the photo's title
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; echo "&lt;img src=\"" . $f-&gt;buildPhotoURL($photo, "Square") .  "\" width=\"75\" height=\"75\" alt=\"$photo[title]\" /&gt;";

// close link&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; echo "&lt;/a&gt;";

// end loop
}
?&gt;

&lt;/div&gt;&lt;!-- close thumbs div --&gt;
</pre>
<p>
</strong>We&#8217;re almost done with the main page.  Chances are, you have more than 21 photos in your Photostream; so we&#8217;ll need to add some paging with some Previous and Next links so we can  move to the next 21 thumbnails. The links look like this:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/491_flickr/pagination-example.png" alt="Pagination example" width="252" height="117"></div>
<p>
&nbsp;This  code relies on the line we had at the top calling the $page  variable. When our code calls in the photos from Flickr, it also uses  the $page variable to know where to start &#8211; look back at the line where  we called &#8216;people_getPublicPhotos&#8217; and you&#8217;ll see that we passed in the $page  variable there as well. That value is the backbone of this little paging  arrangement. We&#8217;ll open a paragraph with the id of &#8216;nav&#8217;, open up the PHP tags, and define our &#8216;back&#8217; and &#8216;next&#8217; variables:</p>
<pre name="code" class="php">&lt;p id="nav"&gt;
&lt;?php
// Some simple paging code to add Prev/Next to scroll through the thumbnails
$back = $page - 1;
$next = $page + 1;
</pre>
<p>
Next we handle the actual &#8216;Previous&#8217;  and &#8216;Next&#8217; links by checking that we&#8217;re not on the first or last page,  the close off php and close the &#8216;p&#8217; tag. </p>
<pre name="code" class="php">// if it's not the first page
if($page &gt; 1) {
echo "&lt;a href='?page=$back'&gt;&amp;laquo; &lt;strong&gt;Prev&lt;/strong&gt;&lt;/a&gt;";
}
// if not last page
if($page != $pages) {
echo "&lt;a href='?page=$next'&gt;&lt;strong&gt;Next&lt;/strong&gt; &amp;raquo;&lt;/a&gt;";}
?&gt;
&lt;/p&gt;
</pre>
<p>
Now we refer back to some values we had at the beginning to display a little more about where we are in the gallery:</p>
<pre name="code" class="php">
&lt;?php
// a quick bit of info about where we are in the gallery
echo"&lt;p&gt;Page $page of $pages&lt;/p&gt;";
echo"&lt;p&gt;$total photos in the gallery&lt;/p&gt;";
?&gt;
</pre>
<p>
And to abide by Flickr&#8217;s terms and finish the page off, we&#8217;ll add:</p>
<pre name="code" class="php">
&lt;p&gt;This product uses the Flickr API but is not endorsed or certified by Flickr.&lt;/p&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>
That&#8217;s everything we need to produce a page that displays the latest 21 photos as thumbnails with a simple Prev / Next navigation.  Just like <a href="http://nettuts-fd.iampaulburgess.co.uk" title="the homepage on the demo">the homepage on the demo</a>. Next up: the page that displays our photo. </p>
<h3>Step 5 &#8211; Build a Page to Display Single Photos</h3>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/491_flickr/singlePage.jpg" alt="Single Page" />
</div>
<p>
Now that we have our thumbnails, we need a page to show the full image  when one is clicked on. Here is the code for photo.php, which the  thumbnails link. We start this page similarly to the index page, but instead  of the page number, we want the id of the photo which has been passed  in the url from our thumbnail page:
</p>
<pre name="code" class="php">&lt;?php

// Get id of photo
$id = isset($_GET['id']) ? $_GET['id'] : NULL;

//include the core file
require_once('phpFlickr.php');

// Fire up the main phpFlickr class
$f = new phpFlickr($key);

// cache folder again, permissions set to 777
$f-&gt;enableCache("fs", "cache");
</pre>
<p>
Now we need to gather some info from  Flickr about the photo such as the photo&#8217;s id number, its dimensions,  where it sits in relation to other photos (context) and the url of the  image. </p>
<pre name="code" class="php">// access the getInfo method, passing in the photo's id
$photo = $f-&gt;photos_getInfo("$id", $secret = NULL);

// pass the photo's id to the getSizes method to get the dimensions of our image
$photosize = $f-&gt;photos_getSizes("$id", $secret = NULL);

// we want the dimensions of the medium size which we get from the $photosize array in the previous line
$size = $photosize[3];

// again passing the photo's id through we get the context, which tells us which photos are before and after the current id
$context = $f-&gt;photos_getContext("$id");

//  the buildPhotoURL method does pretty much what you'd expect - build the  photo URL, we pass in $photo and the size we require to return the  image URL e.g.  http://farm4.static.flickr.com/3108/3175330082_0bf4b22e47.jpg
$photoUrl = $f-&gt;buildPhotoURL($photo, "Medium");

// This tells us who the owner of the photo is.
// This is an important part to include as we want our gallery to show  only our photos and not pull in other users' photos - more of an  explanation about this in the notes at the end
$owner = $photo["owner"]["username"];

// We only want the photo if it belongs to us - so if our username  is the same as the owner of the photo... we'll write out the page and  show it
// more info on this at the end of the tutorial
if($username == $owner){
?&gt;
</pre>
<p>
Now we are primed for the rest of the page with the juicy bits. </p>
<pre name="code" class="php">
&lt;!DOCTYPE html  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&gt;
&lt;!-- Let's get in there straight away and get the photo's title --&gt;
&lt;title&gt;
&lt;?php
// We access the $photo array and grab the title of the photo to use as the document title
echo $photo[title]
&nbsp;?&gt;
&lt;/title&gt;
&lt;link href="styles.css" rel="stylesheet" type="text/css"&gt;
&lt;/head&gt;

&lt;body&gt;

&lt;h1&gt;Photo gallery&lt;/h1&gt;

&lt;div id="photo"&gt;
&lt;?php
// The photo's title once again
echo"&lt;h2&gt;$photo[title]&lt;/h2&gt;";

// The photo itself, you'll recognise $photoUrl from above where we  built the photo's url, we are also accessing the $size array that we  prepared earlier to get the width and height
// and the title once again
// We'll also make it link to the version on Flickr for good measure
echo"&lt;a href=\"http://flickr.com/photos/$username/$photo[id]/\" title=\"View $photo[title] on Flickr \"&gt;";
echo"&lt;img src=\"$photoUrl\" width=\"$size[width]\" height=\"$size[height]\" alt=\"$photo[title]\" /&gt;";
echo"&lt;/a&gt;";

// The photo's description
echo"&lt;p&gt;$photo[description]&lt;/p&gt;";
?&gt;
&lt;/div&gt;&lt;!-- end photo --&gt;
</pre>
<p>
Now we have our photo&#8230; and we are almost done. This last bit may look a bit tricky but don&#8217;t be put off by it. It has to do with the photo&#8217;s context, as in, which photo comes next in  the stream and which one was previous to it. Just like you see on  people&#8217;s Flickr galleries. The reason there seems a lot of code is because for this to work best,  we have to check to see if there is a photo before or after the current  photo. If there isn&#8217;t, we don&#8217;t want a link, instead we insert normal  text and a dummy image (noimg.png).
</p>
<pre name="code" class="php">
&lt;div id="context"&gt;
&lt;?php
// if there is a previous photo...
if($context['prevphoto']['id']){echo"&lt;a  href=\"?id=".$context['prevphoto']['id']."\" title=\"Prev:  ".$context['prevphoto']['title']."\"&gt;&lt;img  src=\"".$context['prevphoto']['thumb']."\" width=\"75\" height=\"75\"  /&gt;&lt;/a&gt;";

} else {
// if not - show the blank filler image
echo"&lt;img src=\"noimg.png\" width=\"75\" height=\"75\" alt=\"No photo\" /&gt;";
};

// if there is a next photo...
if($context['nextphoto']['id']){echo "&lt;a  href=\"?id=".$context['nextphoto']['id']."\" title=\"Next:  ".$context['nextphoto']['title']."\"&gt;&lt;img  src=\"".$context['nextphoto']['thumb']."\" width=\"75\" height=\"75\"  /&gt;&lt;/a&gt;";
} else {
// if not - show the blank filler image
echo"&lt;img src=\"noimg.png\" width=\"75\" height=\"75\" alt=\"No photo\" /&gt;";
};

echo"&lt;/div&gt;";

echo"&lt;p&gt;";
// if there is a previous link, write a link - if not, just the text
if($context['prevphoto']['id']){echo"&lt;a  href=\"?id=".$context['prevphoto']['id']."\" title=\"Prev:  ".$context['prevphoto']['title']."\"&gt;&amp;laquo; Prev&lt;/a&gt;";}  else {echo"&amp;laquo; Prev";};
echo" | ";
// if there is a next link, write a link - if not, just the text
if($context['nextphoto']['id']){echo"&lt;a  href=\"?id=".$context['nextphoto']['id']."\" title=\"Next:  ".$context['nextphoto']['title']."\"&gt;Next  &amp;raquo;&lt;/a&gt;";}else {echo"Next &amp;raquo;";};
echo"&lt;/p&gt;";
?&gt;

&lt;/div&gt;&lt;!-- end context --&gt;
</pre>
<p>
And to finish the page off, we&#8217;ll include a link back to the main gallery, a bit of text for Flickr and close off the html.</p>
<pre name="code" class="php">&lt;p&gt;&amp;laquo; &lt;a href="/"&gt;Main gallery&lt;/a&gt;&lt;/p&gt;

&lt;!-- To abide by Flickr's terms - you must include this text --&gt;
&lt;p&gt;This product uses the Flickr API but is not endorsed or certified by Flickr.&lt;/p&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Hold up! One more thing&#8230; we finish the if  statement from just before the html began&#8230; again, see the notes at  the end about why we do this.</p>
<pre name="code" class="php">
&lt;?php
} // end if for owner
?&gt;
</pre>
<p>
And there you have it. A photo gallery for your website, powered by your Flickr account. <a title="Take a look at the demo page" href="http://nettuts-fd.iampaulburgess.co.uk" id="yn2.">Take a look at the demo page</a> to review how it looks with a bit of extra markup and styling added. This  is a very basic implementation of the Flickr API; it just scratches the  surface of what you can do, but it does provides a nice photo gallery  for your site/blog which you can easily update and maintain via Flickr. </p>
<h3>NOTES &amp; EXTRAS</h3>
<ul>
<li>
<p>In this tutorial we are retrieving a user&#8217;s public photos. Within photo.php, we  reference $owner in this tutorial. At this point we are ensuring that  the photo displayed belongs to the owner of the photograph. If we leave  this out, your photo page can pull in any user&#8217;s public photo, and that  is obviously not what we want. This goes back to the advice Flickr provides in <a href="http://www.flickr.com/guidelines.gne">their guidelines</a>.
</p>
<p><em><br />
    You should use the  API to access your own images only or those which you have  permission to use. If you display someone else&#8217;s pictures, you should mention the name of image owner and name of the image. Flickr also say &quot;&#8230;pages on other web sites that display content hosted on flickr.com must  provide a link from each photo or video back to its page on Flickr.&#8221;</em></p>
</li>
<li>
<p>There  are other ways to display your photos using the search method in the  API, but it is a bit more complicated and requires you to provide  authentication &#8211; in other words, use the API to log in and let Flickr  know it really is you &#8211; more info on that can be found <a href="http://phpflickr.com/docs/flickr-authentication/">here.</a>
</p>
</li>
<li> This demo is a very simple example of what you can do with the Flickr  API. You can take it much further and in fact do pretty much everything  Flickr does: get photo sets, show tags and comments, display private  photos, even upload images. Take a look at the API documentation here:  http://www.flickr.com/services/api/ You can cross check the methods  against the phpFlickr.php file.</li>
<li>
    Just  as we called in our photos using $photos =  $f-&gt;people_getPublicPhotos($nsid, NULL, 21, $page); you can do the  same with a set. For example, $photos =  $f-&gt;photosets_getPhotos(&#8221;$set&#8221;, $extras, $privacyfilter, 21, $page);  is a way to get 21 photos per page from a set, where $set = the set id  (something like 72157594488289220), then using foreach  ($photos['photo'] as $photo) {&#8230; to get the images etc.
  </li>
<li>
<p>If  you need to see which part of the array you need, you can use print_r()  to list out the array and see how to find to the value you need.  Surround it with &lt;pre&gt; tags to make the output legible.</p>
</li>
<li>The  file paths in this demo all work on the assumption that everything is  in the same folder (or all on the root) &#8211; feel free to move stuff about  but be sure to change the paths
</li>
<li>Huge thanks to <a href="http://www.dancoulter.com/">Dan Coulter</a> for wrting the excellent <a href="http://phpflickr.com/">phpFlickr</a>. Be sure to take a look around the phpFlickr documentation:  <a href="http://phpflickr.com/docs/">http://phpflickr.com/docs/</a> for more tips and advice on taking things  further
</li>
</ul>
<p><strong>Have fun, and show us what you come up with!</strong></p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for the best web development tutorials on the web.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/php/how-to-create-a-photo-gallery-using-the-flickr-api/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>7AMP &#8211; Creating a Development Environment</title>
		<link>http://net.tutsplus.com/tutorials/php/7amp-creating-a-development-environment/</link>
		<comments>http://net.tutsplus.com/tutorials/php/7amp-creating-a-development-environment/#comments</comments>
		<pubDate>Tue, 10 Nov 2009 16:51:09 +0000</pubDate>
		<dc:creator>Dan Wellman</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[7amp]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=7660</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/489_7amp/7amp.png" alt="Windows 7, Apache, Mysql and PHP" />]]></description>
			<content:encoded><![CDATA[<p>Running a local development web server is one of the best ways of learning AJAX; reading up on it is one thing, but being able to pass the raw data back and forth between a browser and  a server is really the <strong>only</strong> way to truly understand what is happening at a fundamental level. To create the dynamic and interactive apps and sites that we&#8217;ve come to know and love, you <strong>need</strong> a development server.</p>
<p>On Windows systems we really have only a few decent options available; we can use Microsoft&#8217;s Internet Information Services (IIS), which is usually bundled with Ultimate or Business versions of Windows, or we can use Apache, the extremely popular open-source alternative. Remember when Microsoft enjoyed a 90% market share of the browser market? Apache is the MS of the web server world and at some points in its illustrious history has enjoyed almost total domination in its respective field.</p>
<p><span id="more-7660"></span></p>
<p>IIS is generally quite easy to configure as it uses a graphical interface and is fairly intuitive, however IIS is geared towards development with the .net framework; .net is a proprietary language and generally you need something like Visual Studio to succeed in building web applications with it. Visual Studio does not come cheap (although free express versions are available and if you&#8217;re really hardcore you could use notepad to write the code) and many people prefer the open-source alternative PHP.</p>
<p>Similarly, MSSql is a perfectly adequate database solution made by Microsoft, but like its other offerings, is also a proprietary technology. Mysql is free, open-source, and very, very popular. It&#8217;s easy to use, robust and scalable and that&#8217;s why many developers prefer it. To create development environment we really want to spend as little as possible so really our choices here are clear &#8211; Apache as the platform, PHP as the server-side language, and Mysql as the storage technology. But getting all these technologies talking to each other is not quite as straight-forward as running a few installers.</p>
<h2>Getting Started</h2>
<p>First of all, we need to download the installers for Apache and Mysql and the files required to run PHP. The installers can be found at the following locations:</p>
<ul>
<li>http://httpd.apache.org/download.cgi</li>
<li>http://dev.mysql.com/downloads/mysql/5.1.html#downloads</li>
</ul>
<p>On the above pages choose the appropriate MSI packages for your platform (e.g. x64 or x32) and requirements (you may as well choose the full SSL version of Apache). With PHP however, we don&#8217;t want the installer, we want the zip file that contains all of the PHP files as there is more in this package than you get with the standard installer. It can be found at the following URL:</p>
<ul>
<li>http://uk2.php.net/get/php-5.2.11-Win32.zip/from/a/mirror</li>
</ul>
<p>There are two different zip files for Windows on the PHP site, make sure you <strong>do not</strong> get the one with NTS (non thread-safe) in the name as this will not work with Apache (which is thread-safe). Before running the installers or unpacking the zip file we just need to do a couple of minor system tasks; we should stop any instant messenger applications temporarily as they can interfere with the Apache installation, and we should disable Windows User Account Control (UAC) as it interferes with the Mysql configuration utility. To disable UAC visit the User Accounts application in the Control Panel:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp1.png" alt="User Accounts"></div>
<p>In the applet set the slider to the bottom setting:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp2.png" alt="UAC"></div>
<p>Click the OK button and confirm the very last UAC notification you should ever receive (w00t!), then restart your machine as directed.</p>
<h3>Installing Apache</h3>
<p>The first thing we need to install is the Apache web server which serves web pages to browsers following HTTP requests, and forms the foundation of our development environment. Run the installer, click the <strong>next</strong> button to get started and accept the license terms.  Click <strong>next</strong> again and you should then see the following screen:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp3.png" alt="Apache Installer 1"></div>
<p>Complete the dialog as shown above and click <strong>next</strong> again; on the following screen choose the <strong>Typical</strong> option:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp4.png" alt="Apache Installer 2"></div>
<p>We can now just keep clicking <strong>next</strong> until the installation occurs. Once finished you should see the Apache icon in the notification area; it should have a green play symbol to indicate that it is running:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp5.png" alt="Apache Icon"></div>
<p>As a consequence of Apache running successfully, we should be able to open a browser, type <strong>http://localhost</strong> in the address bar and see the following message:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp6.png" alt="It works!"></div>
<h2>Configuring Apache</h2>
<p>The web page we&#8217;re seeing is being served from Apache&#8217;s default content-serving directory which is probably located somewhere like this:</p>
<pre name="code" class="php">C:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs</pre>
<p>That&#8217;s fine, but it will be a bit of a chore having to dig that deep when we want to add or remove files. We can easily configure Apache to server content from a folder that is closer to hand; create a new directory on your <strong>C</strong> drive and call it <strong>apachesite.</strong></p>
<p>In the Start menu group for Apache there is an option to <strong>Edit the Apache httpd.conf Configuration File</strong>, choose this and a text file will be opened. This is Apache&#8217;s main configuration file; unlike IIS, Apache does not have a GUI for configuration, instead we must edit this text file to make changes to the server. Scroll down to the <strong>Main Server Configuratio</strong>n section, which begins on line 144. On line 177 there should be the <strong>DocumentRoot</strong>  directive, which will be pointing at the directory mentioned above. Change this line so that it points to the directory we created on the <strong>C</strong> drive:</p>
<pre name="code" class="php">DocumentRoot "C:/apachesite"</pre>
<p>Just below this directive are several <strong>Directory</strong> directives; you&#8217;ll need to set the second one so that it points to the same path as the <strong>DocumentRoot</strong>:</p>
<pre name="code" class="php">&lt;Directory "C:/apachesite"></pre>
<p>Save the file and restart Apache which you can do by left-clicking the icon in the notification area and choosing <strong>Apache2.2 &#8594; Restart</strong>. To veryify that it works create a new HTML file called <strong>index.html</strong> in the new directory and request <strong>localhost</strong> from the browser again:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp7.png" alt="It still works!"></div>
<h2>Installing PHP</h2>
<p>Next we can install PHP so that Apache can run PHP files when necessary; create another new directory on the <strong>C</strong> drive and call it <strong>php</strong>, then open the PHP zip that we downloaded and drag the entire contents into the <strong>php</strong> folder. That&#8217;s all we need to do as far as &#8216;installation&#8217; is concerned; all we need to do now is configure Apache to use it.</p>
<h2>Configuring Apache to use PHP</h2>
<p>Edit the <strong>httpd.conf</strong> file again; after all of the <strong>AddModule</strong> directives near start of the file add the following new code:</p>
<pre name="code" class="php">####### PHP Config ###########
LoadModule php5_module "C:/php/php5apache2_2.dll"
AddType application/x-httpd-php .php
PHPIniDir "C:/php"
##############################</pre>
<p>Save the file, but don&#8217;t worry about restarting Apache yet as we need to make a couple more changes and restart the computer anyway.</p>
<h2>Configuring PHP</h2>
<p>Like Apache, PHP relies on file-based configuration; in the <strong>C:\php</strong> folder rename the file called <strong>php.ini-recommended</strong> to <strong>php.ini</strong>. Now we need to add a <strong>Class Variable</strong> to Windows so that it knows where the PHP files reside. You&#8217;ll need to go back to the <strong>Control Panel</strong> and open the <strong>System</strong> applet. On the <strong>Advanced</strong> tab, near the bottom of the dialog is a button called <strong>Environment Variables</strong> &#8211; click this button and a new dialog will open:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp8.png" alt="Environment Variables"></div>
<p>The new dialog is divided into 2 sections; in the bottom section select the line that has <strong>Path</strong> as the <strong>Variable</strong> name (you&#8217;ll need to scroll down a bit) and then click the <strong>Edit</strong> button below the second section to open the editor:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp9.png" alt="Edit"></div>
<p>Go to the end of the <strong>Variable value</strong> line and add the following text to the exsting value:</p>
<pre name="code" class="php">;C:\php\;</pre>
<p>This will map to the <strong>php</strong> folder we created on the <strong>C</strong> drive and which we unpacked the PHP files from the zip file into. It is <strong>very</strong> important that you <em>don&#8217;t remove any of the existing text</em> in the <strong>value</strong> (or other programs on your machine, or your entire machine, may stop working) and that you enter the new text exactly as it appears above. Once this is done click <strong>OK</strong> on the three dialog boxes and restart your computer.</p>
<p>Once your computer has restarted, the Apache icon should still have the green play symbol on it and PHP should be configured successfully. To test it create a page in your text editor and add the following code to it:</p>
<pre name="code" class="php">&lt;?php phpinfo() ?></pre>
<p>Save the new file as <strong>phpinfo.php</strong> in the <strong>C:\apachesit</strong>e folder and then request the page by typing the following address in the browser&#8217;s address bar:</p>
<pre name="code" class="php">http://localhost/phpinfo.php</pre>
<p>Your browser should display the PHP information page:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp10.png" alt="PHP Info"></div>
<p>Success! Now we just need to install Mysql and everything is ready.</p>
<h2>Installing Mysql</h2>
<p>Run the Mysql installer that we downloaded and keep clicking <strong>Next</strong> until you get to the configuration wizard:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp11.png" alt="Mysql Installer 1"></div>
<p>Uncheck the <strong>Register</strong> box and then click the <strong>Finish</strong> button.  Click <strong>next</strong> again and then on the following screen choose the default <strong>Detailed Configuration</strong> option:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp12.png" alt="Mysql Installer 2"></div>
<p>On the next screen choose the <strong>Developer Machine</strong> option:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp13.png" alt="Mysql Installer 3"></div>
<p>After clicking <strong>Next</strong> on the above screen choose the default option again on the following screen:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp14.png" alt="Mysql Installer 4"></div>
<p>Go with the defaults that are selected on the next screen too:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp15.png" alt="Mysql Installer 5"></div>
<p>And again, just go with the default option on the next page:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp16.png" alt="Mysql Installer 6"></div>
<p>The next screen has both options checked, just keep them checked and move along:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp17.png" alt="Mysql Installer 7"></div>
<p>Don&#8217;t worry about checking the <strong>Firewall Exception</strong> box, whether this is required will vary depending on your system and firewall so you can do this in a minute manually if need be. Provided you just want the standard Latin character set you can again just choose the default and click <strong>next</strong>:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp18.png" alt="Mysql Installer 8"></div>
<p>On the next screen keep the defaults, but also check the box to add the executions path to the <strong>Windows Path variable</strong> (we did this manually when configuring PHP):</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp19.png" alt="Mysql Installer 9"></div>
<p>Enter a new password for the <strong>Root</strong> account and then click <strong>Next</strong> again:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp20.png" alt="Mysql Installer 9"></div>
<p>On the final screen click the <strong>Execute</strong> button and the configuration changes will be applied:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp21.png" alt="Mysql Installer 10"></div>
<p>Once the wizard has completed you should see confirmation:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp22.png" alt="Mysql Installer 11"></div>
<p>At this point you should restart your computer again. You aren&#8217;t prompted to but Windows is fickle and the installation may not run correctly if you don&#8217;t do it. So ensure you do.</p>
<h2>Testing Mysql</h2>
<p>Ok, so you&#8217;re back after doing the reboot right? Good. Let&#8217;s just check Mysql is running correctly. In the start menu there should be a <strong>Mysql Command Line Client</strong> application, choose this and enter the password you set when running the Mysql configuration wizard. You should see the following screen:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp23.png" alt="Mysql CLI"></div>
<p>Enter the following command at the prompt:</p>
<pre name="code" class="php">show databases;</pre>
<p>The databases in use should be shown; a <strong>test</strong> database is installed by default:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp24.png" alt="Databases"></div>
<p>Type the command</p>
<pre name="code" class="php">use test;</pre>
<p>The <strong>test</strong> database will be selected:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp25.png" alt="Select Database"></div>
<p>Let&#8217;s create a basic table; type the following command:</p>
<pre name="code" class="php">create table users(name varchar(20), age int);</pre>
<p>This will create a new table called <strong>users</strong> and add two columns to it, one to hold name data consisting of up to 20 variable characters (alphanumeric) and the second to hold age data as an integer. Hit enter and you should get the <strong>Query OK</strong> message to confirm the table was created:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp26.png" alt="Create Table"></div>
<p>To populate the table with some dummy data use the following command:</p>
<pre name="code" class="php">insert into users values('Dan', 31);</pre>
<p>You should get the success message again after you hit enter:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp27.png" alt="Populate Table"></div>
<p>As a final test we can check that the data has been inserted into the table corectly using the <strong>select</strong> command:</p>
<pre name="code" class="php">select * from users;</pre>
<p>Which should show the table and the data we inserted:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp28.png" alt="Table"></div>
<h2>Configuring PHP to talk to Mysql</h2>
<p>All we need to do now is configure PHP to talk to Mysql; earlier on we renamed a file to <strong>php.ini</strong> in the <strong>C:\php folder</strong>, open this file now in a text editor. First of all, scroll down to the <strong>Paths and Directories</strong> section and find the <strong>extension_dir</strong> directive on line 536; change it so that it appears as follows:</p>
<pre name="code" class="php">extension_dir = "./ext"</pre>
<p>Then scroll down to the <strong>Dynamic Extensions</strong> section which begins on line 628. In the <strong>Windows extensions</strong> section remove the semi-colon from in front of the following lines:</p>
<ul>
<li>extension=php_mysql.dll</li>
<li>extension=php_mysqli.dll</li>
</ul>
<p>That&#8217;s all we need to do; save the file and once again restart your machine. After restarting you can check for Mysql support in the <strong>phpinfo.php</strong> page again:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp29.png" alt="PHP Mysql success"></div>
<p>This is pretty much a guarantee of success, but really we should create one more PHP file so that we can test that we can read the data from our database; in a text editor create the following file:</p>
<pre name="code" class="php">&lt;?php

  $user = 'root';
  $password = your_password_here;
  $database = 'test';
  $server = 'localhost';

  $connect = mysql_connect($server, $user, $password);
  $select = mysql_select_db($database, $connect);

  $query = mysql_query('select * from users');
  $data = mysql_fetch_assoc($query);

  echo 'Hi ' .$data['name']. ' you are ' .$data['age'];

  mysql_close($connect);

?></pre>
<p>Save this as <strong>phpmysql.php</strong> in the <strong>C:\apachesite</strong> and request it using your browser; you should see the following message:</p>
<div class="tutorial_image"><img style="max-width: 600px;" src="http://nettuts.s3.amazonaws.com/489_7amp/7amp30.png" alt="Complete"></div>
<p>If this doesn&#8217;t work, try putting your firewall into training mode and seeing if you get a notification asking whether to allow the application when you run the page.</p>
<h2>Summary</h2>
<p>We have now truly succeeded and have the perfect development environment for creating dynamic AJAX-powered pages. Sure, there may be various programs that we can run which will do some or all of the configuration for us, but which may or may not work on the latest version of Windows, but where is the fun in that?! Getting Apache, Mysql and PHP configured manually is an achievement and it gives us the opportunity to learn more about the platforms we&#8217;re using when creating modern web applications.</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for the best web development tutorials on the web.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/php/7amp-creating-a-development-environment/feed/</wfw:commentRss>
		<slash:comments>89</slash:comments>
		</item>
		<item>
		<title>Simple Techniques to Lock Down your Website</title>
		<link>http://net.tutsplus.com/tutorials/php/simple-techniques-to-lock-down-your-website/</link>
		<comments>http://net.tutsplus.com/tutorials/php/simple-techniques-to-lock-down-your-website/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 20:45:38 +0000</pubDate>
		<dc:creator>Dustin Blake</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[crypotgraphy]]></category>
		<category><![CDATA[obfuscastion]]></category>
		<category><![CDATA[randomization]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=7035</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/453_php/noisemagnify.jpg" alt="Randomization, Obfuscation, and Cryptography in PHP" width="200" height="200"/>]]></description>
			<content:encoded><![CDATA[<p>One crucial part of PHP development practice is always keeping in mind that security is not something you can simply buy off the shelf at your local convenient store.  Ensuring the security of your web applications is a process, which over time, needs to be constantly evaluated, monitored, and hardened.</p>
<p><span id="more-7035"></span></p>
<div class="tutorial_image">
<a href="http://nettuts.s3.amazonaws.com/453_php/examples.zip"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg"></a>
</div>
<h3>Introduction</h3>
<p>While the use of filters and validating data is one part of the security process, a web developer should be aware that Randomization, Obfuscation, and Cryptography in PHP can make a difference in the security of web applications.  This tutorial will guide you through some simple techniques at creating and using random or unique values within your web applications, taking a look and applying some general obfuscation techniques, and looking deeper into the science of Cryptology and it&#8217;s use within PHP.</p>
<h3>What you Will Learn</h3>
<ul>
<li>How to generate random values with PHP</li>
<li>Generating random Passwords</li>
<li>Salting Passwords and Authenticating The User</li>
<li>Obfuscation in PHP, an Overview</li>
<li>Cryptography in PHP and it&#8217;s Applications</li>
</ul>
<h3>Generating Random Values</h3>
<p>Dictionary.com defines randomization as:</p>
<blockquote><p>&#8220;-verb: to order or select in a random manner, as in a sample or experiment, especially in order to reduce bias and interference caused by irrelevant variables; make random.&#8221;</p>
</blockquote>
<p>Random number generation is determined in a variety of ways, however computational generators fall short of &#8216;true&#8217; randomness as seen in nature or electronic noise(the fuzzy, screeching, black and white channel on TV).  These computed values are regarded as pseudo-random.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/453_php/whitenoise.jpg" border="0" /></div>
<p>PHP provides us with a couple of different ways to create random values. Let&#8217;s look at a few of the more popular functions.</p>
<pre name="code" class="php">
&lt;?php
rand(int $min, int $max);
mt_rand(int $min, int $max);
str_shuffle($str);
uniqid($prefix, more_entropy=);
?>
</pre>
<p>The two functions rand() and mt_rand() are likely the most widely used functions to generate a set of random numbers in PHP.  The function rand(); is an older generator, and is falling out of use due to mt_rand(); which is faster, more reliable, and can handle a higher maximum integer value on some platforms. The function str_shuffle() does exactly what you would expect it to, it shuffles a string passed to it.</p>
<pre name="code" class="php">
&lt;?php
//Examples of mt_rand() usage
print mt_rand();//default

		echo "&lt;br />";

print mt_rand(0, 20);//Outputs a random integer between 0 and 20

		echo "&lt;br />";

//Examples of rand() usage

print rand();//default

		echo "&lt;br />";

print rand(0, 25);//Outputs a random integer between 0 and 25

		echo "&lt;br />";

//Example of str_shuffle usage

$string = 'abcefghijklmnopqrstuvwxyz';

print str_shuffle($string);//shuffles $string
?>
</pre>
<p>The rand() and mt_rand() functions both accept two parameters where $min is the lowest integer to start with, and $max being the largest integer to end with. The function str_shuffle takes one parameter, a string, outputting a shuffled mutation of the string. The str_shuffle function acts the same as if you were shuffling a deck of cards.</p>
<p>While mt_rand(); will spit out a random integer, and str_shuffle will mix a string up, a function widely used to create random unique values is uniqid().  The function uniqid() generates a prefixed unique identifier based on the current time in microseconds(<a href="http://us.php.net/manual/en/function.uniqid.php" title="PHP uniqid manual">via php.net</a>).  Using this function is useful for creating session tokens and even form keys as seen in <a href="http://net.tutsplus.com/tutorials/php/secure-your-forms-with-form-keys/" title="Secure Your Forms with Form Keys">Secure Your Forms with Form Keys</a>.</p>
<pre name="code" class="php">
&lt;?php
//Examples of uniqid() usage

print uniqid();//default

		echo "&lt;br />";

print uniqid("NETTUTS", TRUE);//Adding an additional prefix and setting more_entropy to TRUE
?>
</pre>
<p>The function uniqid() accepts two parameters the first appends a prefix to the results while the second, if set to TRUE, will add additional <a href="http://en.wikipedia.org/wiki/Information_entropy" title="Wikipedia: Entropy">entropy</a> to the end of the returned value.</p>
<h3>Generating Random Passwords</h3>
<p>There are a gazillion examples on the web which generate random passwords, all do a fine job at it.  &#8220;But why,&#8221; you ask &#8220;would I need to generate a random password?&#8221;  Well the answer, quite simply, is so you do not have to rely on the end user to provide themselves with a less than secure password at the get go.  Generating random passwords is very useful in user registrations, or when a user makes a request because they have <a href="http://net.tutsplus.com/tutorials/php/creating-an-advanced-password-recovery-utility/" title="Creating an Advanced Password Recovery Utility">forgotten their password</a>.  Doing this ensures a strong password at the beginning of a users experience at your website, or can cut down lines of code when a user needs to gain access again.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/453_php/shuffle.jpg" border="0" /></div>
<p>Let&#8217;s look at some examples:Example 1</p>
<pre name="code" class="php">
&lt;?php

//A simple function which will output a random password
function randompassword($count){

$pass = str_shuffle('abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890@#%$*');

return substr($pass,3,$count);//returns the password

}
?>
</pre>
<p>This example shuffles a string with str_shuffle and will return a string within a counted range.  So if you wanted to generate an 8 character password then you would pass 8 to the function randompassword, or randompassword(8) from your source code.</p>
<p>Example 2</p>
<pre name="code" class="php">
&lt;?php

//Another example to create a random password
function anorandpass($count) {

	$m_rand = mt_rand(); //generate a random integer

	$u_id = uniqid("MNO!@#$%^&#038;*=+XYZ", TRUE);//create a unique identifier with some extra prefix and extra entropy

	$combine = $m_rand . $u_id;// Combine the variables to form a string

	$new = str_shuffle($combine);//shuffle our string

	return substr($new, 2, $count);//return the password
}

print anorandpass(8);

?>
</pre>
<p>In comparison, example one takes a static string and mixes it up then returns it, example two adds in more dynamic flavor(mmm tasty).  In example two the string being shuffled is no longer static, but changes with each generation.  While the first example is certainly sufficient in most cases to generate a strong password, the second example allows us to ensure the string length and characters will change with use, greatly decreasing the chance of a duplication.</p>
<p>Enforcing the use of strong passwords within a web application will deter users from visiting or signing up for a website.  It is often a trade off between getting the traffic you desire, and ensuring the security of the application.  I suggest allowing your users to create their own passwords at sign-up, or allow them to choose between the two.</p>
<h3>Please Pass the Salt.  Salting Passwords for Increased Security.</h3>
<p>Salting passwords is an effective way to increase the security of your users accounts even if an attacker gains access to your database, if done right.  It can be argued that, with access to the salt, an attacker can still gain your credentials.  While this is true, applying some randomization techniques to the storage of passwords will make that process extremely difficult, especially if the storage of user information and content are divided into separate databases.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/453_php/elements.jpg" border="0" /></div>
<h3>Why and How?</h3>
<p>Again this falls under the &#8220;non-reliance of the end-user to provide themselves simple security&#8221; measure.  Users generally use passwords which are easy to remember, and even use the same passwords across multiple websites(I know, right!?). Easy to remember passwords are generally words found in a dictionary and other kinds of values(ex. 12345, QWERTY).  As developers we often scoff at this practice, but we cannot deny that it&#8217;s just the way things are.</p>
<p>In order for a web application to utilize a salt in a password, the application has to store it somewhere.  It&#8217;s not recommended to use the same salt across an entire database of passwords, but to generate a unique salt per user.  Generating one salt for an entire database actually decreases the security of the web application in a sense that if an attacker manages to crack it the entire scheme is broke, or if lost, renders the database useless. Creating a full fledged member registration system with all the bells and whistles is out of the scope of this tutorial, however we will be creating a simple system to use an example. Let&#8217;s look at generating a salt and applying some randomization techniques:</p>
<h3>1. The Database Connection</h3>
<p>Here is the SQL table that we will be using.</p>
<pre name="code">
CREATE TABLE IF NOT EXISTS `users` (
  `usr_id` int(11) NOT NULL AUTO_INCREMENT,
  `usr_name` varchar(24) NOT NULL,
  `usr_pass` varchar(32) NOT NULL,
  `usr_email` varchar(255) NOT NULL,
  `usr_salt` varchar(255) NOT NULL,
  PRIMARY KEY (`usr_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 ;
</pre>
<pre name="code" class="php">
&lt;?php
/*db_config.php*/

//database configuration
$db_host ="localhost" ; //will likely stay the same
$db_name = "thedbname"; //the name of the database table
$db_usr = "username"; //your database username
$db_pass = "password";//your database password

//Establish a connection with MySQL and select the database to use
mysql_connect($db_host, $db_usr, $db_pass) or die("MySQL Error: " . mysql_error());
mysql_select_db($db_name) or die("MySQL Error: " . mysql_error());
?>
</pre>
<h3>2. The Registration File</h3>
<pre name="code" class="php">
&lt;?php
/*registration.php*/

//require our db_config.php file
require ('db_config.php');

//Check to see if the form has been submitted
if(!empty($_POST['username'])  &#038;&#038; !empty($_POST['email']) &#038;&#038; !empty($_POST['password'])) {

    //Escape our posted inputs
	$username = mysql_real_escape_string($_POST['username']);
	$email = mysql_real_escape_string($_POST['email']);
	$password = mysql_real_escape_string($_POST['password']);

    //generate a strong unique salt
	$salt_gen = uniqid(mt_rand());

    //Combine email, the password and the salt together
	$combine = $email . $password . $salt_gen;

    //md5 hash the combined password * Note: md5 is only used in this scenario as an example
	$newpassword = md5($combine);

    //insert the values into the database
	$registerquery = mysql_query("INSERT INTO users (usr_name, usr_pass, usr_email,  usr_salt) VALUES ('".$username."', '".$newpassword."', '".$email."', '".$salt_gen."')") or die("MySQL Error: ".mysql_error());

    //let the user know of success or failure
	if ($registerquery) {
		echo '&lt;h1>Success&lt;/h1>';
	} else {
		echo '&lt;h1>Failure&lt;/h1>';
	}
}
?>
</pre>
<p>Let&#8217;s go over the PHP code.  To keep things simple we include our database config file.  Next PHP checks to see if the form HTML has been submitted by checking if the $_POST variables are not empty.  If they are not empty then the script proceeds to escape the posted form data from the user, preparing it to be inserted into the database.  We then generate a simple salt using uniqid() and mt_rand() and storing it in the variable $salt_gen.  To salt our password we combine the $password, then the salt. Next step, one way hashing the combined variables with md5.</p>
<p>&#8220;But wait! You also added the users email to the front of the password and salt combo!&#8221; Yup! I did this because, if an attacker gains access to my database in some way, and the salt, the only way the attacker is going to know for sure that the email address is used in the hashing of the password is if they have access to the source code.  How random and unique is an email address?</p>
<p>To top the rest of the PHP code off we insert our variables into the database table within their respective fields, and give the user some feedback on success or failure. Now onto the rest of the registration file, the HTML</p>
<pre name="code" class="html">
&lt;!DOCTYPE html>
&lt;html>

&lt;head>

&lt;/head>

&lt;body>

&lt;form action="" method="post">
	&lt;label for="username">Enter a Username&lt;/label>
    &lt;input type="text" name="username" />&lt;br />

    &lt;label for="email">Enter your Email&lt;/label>
    &lt;input type="text" name="email" />&lt;br />

    &lt;label for="password">Enter a Password&lt;/label>
    &lt;input type="password" name="password" />&lt;br />

    &lt;input type="submit" name="submit" value="Submit" />
&lt;/form>

&lt;/body>

&lt;/html>
</pre>
<p>Here we create a simple HTML form which will collect a username, an email, and a password from a user. Nothing fancy here.</p>
<h3>3. Authenticating the User</h3>
<p>So we now have a simple registration form, which inserts a user into the database along with their salted password.  Let&#8217;s create a login page which will require us to retrieve information from the database and authenticate the user. First the PHP:</p>
<pre name="code" class="php">
&lt;?php
/*login.php*/

//require our db_config.php file
require ('db_config.php');

//Check to see if the form has been submitted
if(!empty($_POST['username'])  &#038;&#038; !empty($_POST['password'])) {

	//Escape our posted inputs
	$username = mysql_real_escape_string($_POST['username']);
	$password = mysql_real_escape_string($_POST['password']);

	//Grab the row associated with the username from the form
	$grab_row = mysql_query("SELECT * FROM users WHERE usr_name = '".$username."'") or die ("MySQL Error: ".mysql_error());

	//If only one row was retrieved
	if (mysql_num_rows($grab_row) == 1) {

		//create an array from the row fields
		$row = mysql_fetch_array($grab_row);

		//store the users salt in a var
		$salt = $row['usr_salt'];

		//store the users email in a var
		$email = $row['usr_email'];

		//recombine the variables email, password, and the salt
		$combine = $email . $password . $salt;

		//re-hash the combined variables Note:md5 is only used in this scenario as an example
		$auth_pass = md5($combine);

		//check the database again for the row associated with the username and the rehashed password
		$checklogin = mysql_query("SELECT * FROM users WHERE usr_name = '".$username."' AND usr_pass = '".$auth_pass."'") or die("MySQL Error: ".mysql_error());

		//if only one row is retrieved output success or failure to the user
		if(mysql_num_rows($checklogin) == 1) {
			echo '&lt;h1>Yippie, we are authenticated!&lt;/h1>';
		} else {
			echo '&lt;h1>Oh no, we are not authenticated!&lt;/h1>';
		}
	} else {
		echo '&lt;h1>Oh no, we are not in the database!&lt;/h1>';
	}
}
?>
</pre>
<p>Basically what we are doing in the login.php file is taking the submitted form variables, grabbing the table row associated with the username and rebuilding the password from the elements in the database it was created with (email, pass, salt) and rehashing them.  We then check the database again for the username AND the rehashed password value to find a match, outputting the user on success or failure. Finally here is the HTML:</p>
<pre name="code" class="HTML">
&lt;!DOCTYPE html>
&lt;html>
&lt;head>

&lt;/head>

&lt;body>
&lt;form action="" method="post">
	&lt;label for="username">Enter your Username&lt;/label>
    &lt;input type="text" name="username" />&lt;br />

    &lt;label for="password">Enter a Password&lt;label>
    &lt;input type="password" name="password" />&lt;br />

    &lt;input type="submit" name="submit" value="Submit" />
&lt;/form>
&lt;/body>
&lt;/html>
</pre>
<h3>Obfuscation in PHP</h3>
<p>A simple yet complex definition of obfuscation is (use the version contained in the source if you wish to run the code):</p>
<pre name="code" class="php">
&lt;?php $a1c0_z2='c'.$a91.'tion&#8201;';$a91="a";$vly_ti="us".'ed';$j1h_32_a='&#8201;to';$z1b_1=$a91."&#8201;";$lz32i_4="&#8220;O"."bfus";$g1k0p='que&#8201;';$lv83="t".'ec'.'hni';$lFa='i'.'s&#8201;';if($z1b_1==$a91."&#8201;")$rx_b_1='a';$glccUv="&#8201complic".$rx_b_1.'te&#8201;';$xl1ttf='code&#8201;';$zljal1="in&#8201;such&#8201;a";if($z1b_1==$a91."&#8201;")$s1b_1='a';$p1x2 ="&#8201;w".$s1b_1."y&#8201;";$il_7x='&#8201;'.$b1zE_.'t&#8201;i'.$l1yes;$b1zE_="i";$l1yes="s";$nltotry_ws='st'.$s1b_1."n";$yl5B_='th&alpha;t&#8201;';$dlno='&#8201;not&#8201;';$m1tomanythings="under";if($s1b_1=='a')$bz_1=$s1b_1;$Ozaq="d".$bz_1."ble&quot;";echo base64_decode("JiM4MjIwO09iZnVzY3Rpb24mIzgyMDE7aXMmIzgyMDE7YSYjODIwMTt0ZWNobmlxdWUmIzgyMDE7dXNlZCYjODIwMTt0byYjODIwMWNvbXBsaWNhdGUmIzgyMDE7Y29kZSYjODIwMTtpbiYjODIwMTtzdWNoJiM4MjAxO2EmIzgyMDE7d2F5JiM4MjAxO3RoJmFscGhhO3QmIzgyMDE7aSYjODIwMTt0JiM4MjAxO2kmIzgyMDE7bm90JiM4MjAxO3VuZGVyc3RhbmRhYmxlJnF1b3Q7");?>
</pre>
<p>As you can see, this code is not meant to be distinguishable. There are no distinct variable names, there are no comments, no spacing, no indentation, no distinct order and it&#8217;s all in one line.  Even though we cannot distinquish the code, our machines still know what it is. It works.  This one line of chaos simply echos &#8220;Obfusction is a technique used to complicate code in such a way that i t i not understandable.&#8221;  Yes, I know about the errors.</p>
<p>Obfuscation has pros and cons.  It&#8217;s purpose is to disuade a person from finding out what code is doing at a glance, or for a period of time. This is a plus toward individuals with little to no knowledge of the programming language.  However, anybody who has a basic understanding of PHP can disseminate the above obfuscated code and figure out what it&#8217;s doing, it might just take a little time.  This is one of the flaws of obfuscation, it is not a form of encryption, it&#8217;s just an attempt to be cryptic.  Obfuscation also normally adds to filesize. A lot of the time, you&#8217;ll encounter obfuscated code in propriatary and malicious software.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/453_php/obfuscation.jpg" border="0" /></div>
<h3>So How Can I Obfuscate My Code?</h3>
<p>This is a common question.  There are primarily two ways to obfuscate your code.  First, you can do it by hand.  Writing obfuscated code takes a long time.  The example used in this article took a while to write because of the same reasons you use obfuscation in the first place (lack of structure, order etc&#8230;), this even resulted in some menial errors which I didn&#8217;t even want to hunt down and fix.  The second way you can obfuscate your code is by buying software that does it for you.  Using a program to obfuscate code is trivial, and of course costs money a lot of the time.  Some software which claims to obfuscate your code, actually encrypts and/or encodes it in such a way it relies on a handshake to function. Often you&#8217;ll find software whose vendor won&#8217;t even guarantee your code will work when it&#8217;s done.  Even in the example, I used a simple Base64 function to encode the construction of the script output.</p>
<h3>Some Obfuscation Tips</h3>
<ul>
<li>Always, always, keep a clean version of the source for yourself.</li>
<li>The more random your technique, the better.</li>
<li>Eliminate all whitespace, where it is not needed.</li>
<li>Character Encode printed/echo&#8217;ed characters and spaces (i.e. quotations, thin spaces, apostropes, hypens)
<li>The more complex the code, the better.</li>
<li>Disregard structure unless it is detrimental to the operation of the code(e.x. variable locations before they&#8217;re called)</li>
<li>Do not use distinguishable variable names, namespaces, or class names.</li>
<li>The less code you reuse, the better</li>
<li>Don&#8217;t believe it&#8217;s foolproof</li>
</ul>
<h3>To Obfuscate or Not to Obfuscate?</h3>
<p>It really depends on your plan. Particularly if your looking to sell your PHP script (or any software) you need to license it.  This is going to be one of the front line defenses to thwart the softwares intended audience from doing whatever they want. A prime example of licensing can be seen in the <a href="http://wiki.envato.com/support/legal-terms/licensing-terms/" title="Envato Marketplaces Licensing Terms" >Envato Marketplace Wiki</a>. However, you may want to obfuscate some, or all of your code for whatever reason. However due to obfuscations negatives, if your really that worried about the security of your source code, it may be worth  looking to encryption instead.</p>
<h3>Cryptography in PHP</h3>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/453_php/quoteimage.jpg" border="0" /></div>
<p>Wikipedia.com defines cryptography as:</p>
<p style="text-align:center; font-style:italic;">&#8220;the practice and study of hiding information.&#8221;</p>
<p>Cryptography is a big deal, wether your aware of it or not.  In almost every web application presently deployed there is some presence of cryptography being utilized (i.e. mail clients and websites). As developers we need to be informed and aware of the practical applications of cryptography within our software.  PHP provides us with some very fundamental and practical functions we can utilize to encrypt data.  In this section, I will be mainly going over one-way hashing algorithms though I will touch lightly on Symmetric-key based encryption. There are plenty more (i.e. Steganography, Asymmetric-Key to name a couple).</p>
<h3>The One Way Hash</h3>
<p>Alot of the time we utilize one-way hashing as a way to securely store passwords and check the data integrity of files.  While we do this, to authenticate members of a web application we hash the users entered password, and match it against the users stored hash.  The same technique applies to checking the integrity of files.</p>
<p style="font-weight:bold;">SHA-1, 2, and 3</p>
<p>The SHA family of hash algorithms are currently the most popular, significantly SHA-1.  Even though the SHA-1 algorithm may have a weakness, it is still in wide use.</p>
<pre name="code" class="php">
&lt;?php

///One way hashing with SHA-1

$string = "Netuts is Awesome";

$hash = sha1($string);
//or
$hash2 = hash('sha1', $string);

echo $hash."&lt;br />";
echo $hash2."&lt;br />&lt;br />";

//Will output: 42d2f15c3f92d28d7d58776e5d81b800f662cc6c
?>
</pre>
<p>In PHP, SHA-2 is called upon in a different respect, and requires PHP 5 greater than or equal to 5.1.2.  SHA-2 is superior to SHA-1 and can be called with different bit sizes.</p>
<pre name="code" class="php">
&lt;?php
$string_sha256 = "Nettuts is Awesome";
$string_sha384 = "Nettuts is Awesome";
$string_sha512 = "Nettuts is Awesome";

$hash_sha256 = hash('sha256', $string_sha256);
$hash_sha384 = hash('sha384', $string_sha384);
$hash_sha512 = hash('sha512', $string_sha512);

echo $hash_sha256."&lt;br />";
echo $hash_sha384."&lt;br />";
echo $hash_sha512."&lt;br />";

/* Outputs repspectively:
sha256 : 09074adc0d70e15b88494643e29c2836e1ab94a21989691dec594cb0bd742ebc
sha384 : 8535470750df54a78701d4bfe0451f9799057a5bc101944a32480d2436e8b95440bce3bcab3f9ce107b0b92d9595ae32
sha512 : c2e6dce873a71800b862791e56b480b976bb26cd3136c02da510c3905caa49b7b9e9260549976e1e741cc93e4569a611f2030d3b7104c6c6c2ff9e6c9bf0946a
*/

?>
</pre>
<p>The hash function is called by hash(algorithm, string); In the newest PHP versions the hash() function can be used to call any one-way hash algorithm PHP supports (i.e. md5, sha-1, haval, ghost). If you want to see a list of all the registered hashing algorithms you can use:</p>
<pre name="code" class="php">
&lt;?php
//As of PHP5 >= 5.1.2
print_r(hash_algos());
?>
</pre>
<p>SHA-3 is still being developed and considered for standardization.  A <a href="http://www.csrc.nist.gov/groups/ST/hash/index.html" title="NIST">competition</a> to find a good candidate to act as the new secure hash algorithm was launched by the National Institute of Standards and Technology and entries for the competition were deadlined for October 31, 2008.  A rather popular entry named Skein,  has an available PHP module you can download (though you have to compile it yourself).  Skein is developed by some big names found within the security industry such as Bruce Schneier, Niels Ferguson, and Stefan Lucks to name a few.  The official Skein website can be found <a href="http://www.skein-hash.info" title="Skein Official Site">here</a>.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/453_php/encrypt.jpg" border="0" /></div>
<h3>Key-based Encryption</h3>
<p>Symmetric-Key encryption methods is where the security of the encryption primarily resides within a key, which is shared between two points, where the data is encrypted and where the data is decrypted.  A very good example of how this can work was provided by Christian Beikov&#8217;s &#8220;<a href="http://net.tutsplus.com/tutorials/php/creating-a-crypter-class/" title="Creating a Crypter Class with PHP at Nettuts">Creating a Crypter Class with PHP</a>&#8221; tutorial.</p>
<h3>HMAC</h3>
<p>Essentially HMAC is like a mix between one-way hashing and key based encryption.  HMAC security relies on the key size used, and strength of the hash function it is calculated with.  You can somewhat compare this method to salting passwords.</p>
<pre name="code" class="php">
&lt;?php
$string_hmac = "Nettuts is Awesome";

//hash_hmac(algorithm, string to hash, key)
$hmac = hash_hmac('sha1', $string_hmac, 'secret');

echo $hmac."&lt;br />";
?>
</pre>
<h3>Wrapping it All Up</h3>
<p>Well what a journey!  Randomizing values, generating random passwords, salting, storing and authenticating users, obfuscation, crypto&#8230;seems like alot to take in.  But worth it!  It&#8217;s important to know what kind of security your going to implement into your web applications, and how your going to protect it.  Even more, it&#8217;s important to keep a clever attitude towards these implementations and not think that security is only implemented by a few methods, but by a combination of them, with a dash of creativity.</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/php/simple-techniques-to-lock-down-your-website/feed/</wfw:commentRss>
		<slash:comments>64</slash:comments>
		</item>
		<item>
		<title>Creating a Crypter Class with PHP</title>
		<link>http://net.tutsplus.com/tutorials/php/creating-a-crypter-class/</link>
		<comments>http://net.tutsplus.com/tutorials/php/creating-a-crypter-class/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 20:13:49 +0000</pubDate>
		<dc:creator>Christian Beikov</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[crypt]]></category>
		<category><![CDATA[crypter]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=6941</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/448_crypter/200x00.jpg" alt="Creating a Crypter Class" />]]></description>
			<content:encoded><![CDATA[<p>In this article I will explain how to create a PHP Class that will encrypt and decrypt any data with a given password. It is object programmed and uses existing PHP algorithms.
</p>
<p><span id="more-6941"></span></p>
<div class="tutorial_image">
<a href="http://nettuts.s3.amazonaws.com/448_crypter/Creating_a_Crypter_Class_Source_Files.zip"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg"></a>
</div>
<p>
	Think about what we might need a class like this for?<br />
	We want to encrypt important data with a password for security reasons. We also want, as already mentioned, to be able to<br />
	decrypt that data when necessary. Why should you use symmetric algorithms?<br />
	It&#8217;s easy; when you&#8217;re offering a password sent via email or something like that,<br />
	you need the password to be sent in plaintext. The hash algorithms are not reversible.<br />
	Once you have hashed a string you can&#8217;t decipher the original text from the hash. </p>
<p>
	Maybe you have already heard of MD5? It&#8217;s not really the best option anymore because it tends to be unsafe.<br />
	There are databases around the web &#8211; that I don&#8217;t want to mention -<br />
	that can be used to retrieve the plaintext from a hash simply by typing in the hash into a search box.<br />
	So you should use something like SHA which was developed by the NSA (National Security Agency). SHA is the abbreviation for Secure Hash Algorithm and is one of the most secure hash algorithms.<br />
	There are some others as well, such as WHIRLPOOL, PANAMA and RIPEMD, but SHA is currently the secure standard for hashes and is used in numerous applications.
</p>
<h3>Step 1 &#8211; Preparation</h3>
<p>
	I think it is important to create an interface. This is because we can always use the<br />
	methods which are defined in the interface without thinking, when instancing an<br />
	object of a class, which implements that interface. </p>
<p>
	When a class implements an interface it has to implement the methods given in that interface,<br />
	otherwise there will be an error! So here is an example: </p>
<pre class="php" name="code">
		interface ICrypter{
			public function Encrypt($data);
			public function Decrypt($data);
		}

		class Crypter implements ICrypter{
			public function Encrypt($data){ ... }
			public function Decrypt($data){ ... }
		}
	</pre>
<p>
	As you can see, the interface instructs the classes which implement ICrypter to have<br />
	the public function Encrypt with one parameter $data. The public function Decrypt<br />
	also has the parameter $data. You can try it out; if the class lacks one of the given<br />
	methods in the interface, you get a fatal error. Here&#8217;s an example:</p>
<h3>Decrypt</h3>
<blockquote>
<p>
	Fatal error: Class Crypter contains 1 abstract method and must therefore be declared<br />
	abstract or implement the remaining methods (ICrypter::Decrypt) in C:\www\Nettuts\Crypter\crypter.php on line 32. </p>
</blockquote>
<p>	Nice error right? So you can be sure that the classes really have the methods!
</p>
</blockquote>
<div class="tutorial_image">
	<img border="0" src="http://farm4.static.flickr.com/3317/3619465338_e0b46b5d23_o.jpg"/>
</div>
<h3>Step 2 &#8211; Password for Encryption and Decryption</h3>
<p>
	As I said before, we want to be able to use a specific password for encryption<br />
	and decryption. This password has to be accessible for the encrypt- and<br />
	decrypt-function so we will define an instance variable, called key, which is<br />
	passed to the constructor. The definition of $Key is only needed in the Crypter Class: </p>
<pre class="php" name="code">
		private $Key;
	</pre>
<p>
	However, the definition of the constructor has to be in the interface. Therefore, it is<br />
	also needed in the class, because we have to implement everything we have defined<br />
	in the interface. The interface will contain: </p>
<pre class="php" name="code">
		public function __construct($Key);
	</pre>
<p>	and the class: </p>
<pre class="php" name="code">
		public function __construct($Key){ ... }
	</pre>
<p>Now that we know we get a key, we can use it to encrypt and decrypt!
</p>
<div class="tutorial_image">
	<img border="0" src="http://farm4.static.flickr.com/3595/3619465342_5474e711d2_o.jpg"/>
</div>
<h3>Step 3 &#8211; Constructor</h3>
<p>
	In the constructor we have to set the key and choose an algorithm.<br />
	We will use the Blowfish algorithm for this example and use it as a standard value.<br />
	I will explain a bit more about the symmetric algorithms later in the text, but for<br />
	simplicity we will use Blowfish. You can change this later if you want to.<br />
	So we need another instance variable called Algo: </p>
<pre class="php" name="code">
		private $Algo;
	</pre>
<p>	and the constructor&#8230; </p>
<pre class="php" name="code">
		public function __construct($Key, $Algo = MCRYPT_BLOWFISH){
			$this-&gt;Key = substr($Key, 0, mcrypt_get_key_size($Algo, MCRYPT_MODE_ECB));
			$this-&gt;Algo = $Algo;
		}
	</pre>
<p>
	The length of the key depends on the algorithm and the encryption mode. In this<br />
	example we will use the ECB mode. You can make this variable like we have already done with the algorithm.<br />
	We use the substring of the given key with the maximum allowed length.<br />
	You can get this length with the mcrypt_get_key_size function which requires the algorithm and the encryption mode as parameters. </p>
<p>
	Now we give our instance variable Key the correct key for the algorithm<br />
	and assign our instance variable Algo. </p>
<p>
	So now we have the constructor. As I said previously, you can change the standard value<br />
	of Algo to any other algorithm that is supported by MCrypt. </p>
<p>
	List of supported algorithms from php.net: </p>
<ul>
<li>MCRYPT_3DES</li>
<li>MCRYPT_ARCFOUR_IV (libmcrypt &gt; 2.4.x only)</li>
<li>MCRYPT_ARCFOUR (libmcrypt &gt; 2.4.x only)</li>
<li>MCRYPT_BLOWFISH</li>
<li>MCRYPT_CAST_128</li>
<li>MCRYPT_CAST_256</li>
<li>MCRYPT_CRYPT</li>
<li>MCRYPT_DES</li>
<li>MCRYPT_DES_COMPAT (libmcrypt 2.2.x only)</li>
<li>MCRYPT_ENIGMA (libmcrypt &gt; 2.4.x only, alias for MCRYPT_CRYPT)</li>
<li>MCRYPT_GOST</li>
<li>MCRYPT_IDEA (non-free)</li>
<li>MCRYPT_LOKI97 (libmcrypt &gt; 2.4.x only)</li>
<li>MCRYPT_MARS (libmcrypt &gt; 2.4.x only, non-free)</li>
<li>MCRYPT_PANAMA (libmcrypt &gt; 2.4.x only)</li>
<li>MCRYPT_RIJNDAEL_128 (libmcrypt &gt; 2.4.x only)</li>
<li>MCRYPT_RIJNDAEL_192 (libmcrypt &gt; 2.4.x only)</li>
<li>MCRYPT_RIJNDAEL_256 (libmcrypt &gt; 2.4.x only)</li>
<li>MCRYPT_RC2</li>
<li>MCRYPT_RC4 (libmcrypt 2.2.x only)</li>
<li>MCRYPT_RC6 (libmcrypt &gt; 2.4.x only)</li>
<li>MCRYPT_RC6_128 (libmcrypt 2.2.x only)</li>
<li>MCRYPT_RC6_192 (libmcrypt 2.2.x only)</li>
<li>MCRYPT_RC6_256 (libmcrypt 2.2.x only)</li>
<li>MCRYPT_SAFER64</li>
<li>MCRYPT_SAFER128</li>
<li>MCRYPT_SAFERPLUS (libmcrypt &gt; 2.4.x only)</li>
<li>MCRYPT_SERPENT(libmcrypt &gt; 2.4.x only)</li>
<li>MCRYPT_SERPENT_128 (libmcrypt 2.2.x only)</li>
<li>MCRYPT_SERPENT_192 (libmcrypt 2.2.x only)</li>
<li>MCRYPT_SERPENT_256 (libmcrypt 2.2.x only)</li>
<li>MCRYPT_SKIPJACK (libmcrypt &gt; 2.4.x only)</li>
<li>MCRYPT_TEAN (libmcrypt 2.2.x only)</li>
<li>MCRYPT_THREEWAY</li>
<li>MCRYPT_TRIPLEDES (libmcrypt &gt; 2.4.x only)</li>
<li>MCRYPT_TWOFISH (for older mcrypt 2.x versions, or mcrypt &gt; 2.4.x )</li>
<li>MCRYPT_TWOFISH128 (TWOFISHxxx are available in newer 2.x versions, but not in the 2.4.x versions)</li>
<li>MCRYPT_TWOFISH192</li>
<li>MCRYPT_TWOFISH256</li>
<li>MCRYPT_WAKE (libmcrypt &gt; 2.4.x only)</li>
<li>MCRYPT_XTEA (libmcrypt &gt; 2.4.x only)</li>
</ul>
<p>
  	So which one should we use when we want to use the Crypter Class in our products?<br />
  	At the moment AES is the standard of the symmetric algorithms. It is used in many<br />
  	applications, but where is AES? AES was originally published as Rijndael which is listed.<br />
  	It is a really fast, but secure, algorithm and is even fast with 256-Bit key size.<br />
  	My advice is to use MCRYPT_RIJNDAEL_256 for your applications. Just as an example,<br />
  	AES is used in WPA2 which is a security standard for WLAN.
</p>
<div class="tutorial_image">
	<img border="0" src="http://farm4.static.flickr.com/3655/3619465344_c358737684_o.jpg" />
</div>
<h3>Step 4 &#8211; Now to the Encryption</h3>
<p>
	First thing to check: is there any data to encrypt? If not, you can go ahead and break the<br />
	encryption. If you want to use any other encryption modes then you have to add the<br />
	following code. </p>
<pre class="php" name="code">
		$iv_size = mcrypt_get_iv_size($this-&gt;Algo, MCRYPT_MODE_ECB);
		$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
	</pre>
<p>
	This $iv is used for example in CBC, CFB, OFB and in some algorithms in STREAM<br />
	encryption mode. If the parameter is not passed in these modes, the $iv will be<br />
	set to &#39;\0&#39;. The next step is to encrypt the data with the simple function<br />
	mcrypt_encrypt. Here we need our algorithm, the key, the data and<br />
	an encryption mode. The $iv is optional. </p>
<pre class="php" name="code">
		$crypt = mcrypt_encrypt($this-&gt;Algo, $this-&gt;Key, $data, MCRYPT_MODE_ECB, $iv);
	</pre>
<p>
	Finally encode the encrypted data<br />
	with base64_encode and trim it before you return it. </p>
<pre class="php" name="code">
		return trim(base64_encode($crypt));
	</pre>
<p>
	We have to base64 encode the encrypted data to get URL-Safe data.<br />
	This is needed because, if you want to use the encrypted data, for example in a URL,<br />
	you will have problems with &#8216;&#038;&#8217; as it is a reserved character specified in the RFC.<br />
	So you need something like alphanumeric characters &#8211; in other words, character that are safe.<br />
	The base64 encode supplies these safe characters, which is why we&#8217;re using it.<br />
	We do not know what will be done with the data after encryption. </p>
</p>
<div class="tutorial_image">
	<img border="0" src="http://farm3.static.flickr.com/2470/3619465346_cdf1928555_o.jpg"/>
</div>
<h3>Step 5 &#8211; Decryption is Reversed Encryption</h3>
<p>
	Again we ask the same first question. Is there data? If there is, you have to base64_decode<br />
	the data as we have previously encoded it with base64_encode.  </p>
<pre class="php" name="code">
	$crypt = base64_decode($data);
	</pre>
<p>
	Then the optional part with $iv. </p>
<pre class="php" name="code">
			$iv_size = mcrypt_get_iv_size($this-&gt;Algo, MCRYPT_MODE_ECB);
			$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
	</pre>
<p>
	Decryption with the simple function mcrypt_decrypt. Here we need &#8211; nearly &#8211; the same parameters. The difference is that the decrypt-function needs to access the crypted data rather than the original data.<br />
	So here again we use, the algorithm, the key, the crypted data, the encryption mode, and the optional iv. </p>
<pre class="php" name="code">
		$decrypt = mcrypt_decrypt($this-&gt;Algo, $this-&gt;Key, $crypt, MCRYPT_MODE_ECB, $iv);
	</pre>
<p>	Finally return the trimmed and decrypted data. </p>
<pre class="php" name="code">
		return trim($decrypt);
	</pre>
</p>
<div class="tutorial_image">
	<img border="0" src="http://farm4.static.flickr.com/3339/3619465348_25e097ecf2_o.jpg"/>
</div>
<h3>Examples</h3>
<p>Define a global Crypter. In this example we will use RIJNDAEL_256 (AES)<br />
   with the password &#8220;Any password&#8221;. After instancing you call your functions<br />
   or methods to test it. Here we call the function foo and the method foo1. </p>
<pre class="php" name="code">
		$crypter = new Crypter("Any password", MCRYPT_RIJNDAEL_256);

		foo();

		$foo = new Foo();
		$foo->foo1();
	</pre>
<p>
	You can get your crypter from the Superglobal variable called $GLOBALS.<br />
	This is an associative array, so you can call all your global variables<br />
	by the name you defined them with. You can retrieve the $crypter which is defined<br />
    outside	of the foo or foo1 block with $GLOBALS["crypter"]&#8230; </p>
<pre class="php" name="code">
		function foo(){
			...
			$encrypted = $GLOBALS["crypter"]->Encrypt($data);
			$decrypted = $GLOBALS["crypter"]->Decrypt($encrypted);
			...
		}

		class Foo{
			public function foo1(){
				...
				$encrypted = $GLOBALS["crypter"]->Encrypt($data);
				$decrypted = $GLOBALS["crypter"]->Decrypt($encrypted);
				...
			}
		}
	</pre>
<h3>Conclusion</h3>
<p>
	Now you have a complete Crypter class and you can crypt and decrypt as many times as you wish! Download the <a href="http://nettuts.s3.amazonaws.com/448_crypter/Creating_a_Crypter_Class_Source_Files.zip">complete source code</a> with a nice example if you do not want to type it in yourself.<br />
	I hope that you have enjoyed this article.</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/php/creating-a-crypter-class/feed/</wfw:commentRss>
		<slash:comments>51</slash:comments>
		</item>
		<item>
		<title>How to Code a Signup Form with Email Confirmation</title>
		<link>http://net.tutsplus.com/tutorials/php/create-a-signup-form-with-email-confirmation/</link>
		<comments>http://net.tutsplus.com/tutorials/php/create-a-signup-form-with-email-confirmation/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 13:42:19 +0000</pubDate>
		<dc:creator>Matt Vickers</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[email confirmation]]></category>
		<category><![CDATA[email signup]]></category>
		<category><![CDATA[signup]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=6860</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/444_signup/images/preview.jpg" alt="preview" width="200" height="200"/>]]></description>
			<content:encoded><![CDATA[<p>In this tutorial, we are going to be creating a user signup form that adds a user to a database, and then sends out a confirmation email that the user must click on before their account will be activated.</p>
<p><span id="more-6860"></span></p>
<div class="tutorial_image">
<a href="http://nettuts.s3.amazonaws.com/444_signup/source.zip"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg"></a>
</div>
<h3>Tutorial Details</h3>
<ul>
<li>PHP Server and MySQL Database required </li>
<li>Difficulty: Beginner/Intermediate</li>
<li>Estimated Completion Time: ~45 Minutes</li>
</ul>
<p><!-- 600 --></p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/444_signup/images/template.jpg" alt="preview" width="600" height="500"/>
</div>
<h3>Step 1: The Template</h3>
<p>I&#8217;ve included the basic site layout so we aren&#8217;t wasting time creating the form and making the site looks pretty. We are going to get right into coding which is what you came here for.</p>
<p>Open up the Site Template folder and copy it to either your localhost or web server.</p>
<p>Open up index.php and take a quick look. You&#8217;ll see a simple form with 3 inputs. These are the fields we are going to capture. We want the username, their password as well as their email. You can choose to capture other elements when users are signing up, but these are the 3 barebones elements we need.</p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/444_signup/images/mysql.jpg" alt="preview" width="600" height="95"/>
</div>
<h3>Step 2: Setting up the MySQL Database</h3>
<p>Open up PHPMyAdmin or whatever program you use to manage your MySQL database and create a new database. You can name this whatever you like. Now we want to create the rows that are going to hold our user information and confirmation information. For this we create two tables. Users and Confirm.</p>
<pre name="code" class="sql">
CREATE TABLE `users` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(50) NOT NULL default '',
  `password` varchar(128) NOT NULL default '',
  `email` varchar(250) NOT NULL default '',
  `active` binary(1) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
</pre>
<p>Our first table has 5 rows. The first is the ID that is given to the user when they signup. This is set to auto increment so that each user is given a unique ID. Next is the username, password and ID. The last row lets us set the users active state. When we first create the user row, the active state will default to 0. This means that the users account is currently inactive. Once the user confirms their account we will set this to 1. This will state that the account is active.</p>
<pre name="code" class="sql">
CREATE TABLE `confirm` (
  `id` int(11) NOT NULL auto_increment,
  `userid` varchar(128) NOT NULL default '',
  `key` varchar(128) NOT NULL default '',
  `email` varchar(250) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
</pre>
<p>Our second table is the confirm table. This holds the user&#8217;s ID and email as well as a randomly generated key that we will use to confirm the users account.</p>
<h3>Step 3: Connecting to the MySQL Database</h3>
<p>Open up inc/php/config.php. </p>
<p>First we need to make the connect to the database.</p>
<pre name="code" class="php">
mysql_connect('localhost', 'username', 'password') or die("I couldn't connect to your database, please make sure your info is correct!");
</pre>
<p>Depending on your setup, we are going to need to change a few variables. So go ahead and fill in everything.</p>
<p>Next we need to tell MySQL which database we want to use.</p>
<pre name="code" class="php">
mysql_select_db('your_database_name') or die("I couldn't find the database table make sure it's spelt right!");
</pre>
<p>Once everything has been edited to fit your database go ahead and point to the index.php file on your server.</p>
<p>If you don&#8217;t see any errors at the top, we are all connected.</p>
<h3>Step 4: Submitting the Form</h3>
<p>Ok, now that we are all connected to the database, we need to capture the form data so we can get the user signed up.</p>
<p>I&#8217;m going to give you the piece of code and then explain what&#8217;s going on. After that we are going to make changes and add functionality.</p>
<p>Here is the base; place this right after the first includes at the top of index.php</p>
<pre name="code" class="php">
//check if the form has been submitted
if(isset($_POST['signup'])){

}
</pre>
<p>This if statement is checking to see if the form has been submitted. </p>
<p>Without this, our script would run every time the page is refreshed and we don&#8217;t want that.</p>
<p>Note: Depending on your application or just general style of coding this code may be placed in a separate file that is accessed when the form is submitted. I&#8217;ve placed the code all in one file to keep things simple and easy to follow along.</p>
<h3>Step 5: Cleaning up and Checking the Variables</h3>
<p>We want to make sure that the user has submitted actual content instead of just a blank form, so we are going to perform some quick checks.</p>
<p>The first part is to place the $_POST variables into simpler variables and clean them for the database. Place this inside our if statement.</p>
<pre name="code" class="php">
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
</pre>
<p>mysql_real_escapse_string() makes sure that the user isn&#8217;t trying to use apostrophes to access our database with MySQL injection. Whenever you want to put information into a database the the user has inputed, please run it through mysql_real_escape_string(). For more information on MySQL injection you can <a href="http://en.wikipedia.org/wiki/SQL_injection" target="_blank">read this article on Wikipedia</a></p>
<p>So, we&#8217;ve cleaned up our variables, now let&#8217;s check to see if the user forgot any fields.</p>
<pre name="code" class="php">
if(empty($username)){ //put code in me please }
if(empty($password)){ //put code in me please }
if(empty($email)){ //put code in me please }
</pre>
<p>Now we have three if statements that are checking if each field is empty. If the field is empty we are going to assign some variables.</p>
<p>To make things clean we are going to create an array that will hold the status of the signup process as well as any text we need to show the user.</p>
<p>Right above that piece of code, let&#8217;s create an array and a few variables.</p>
<pre name="code" class="php">
$action = array();
$action['result'] = null;

$text = array();
</pre>
<p>First we are creating a blank array called action and then setting an array value of result. Result is going to hold a value of either success or error. Next we create another blank array called text. This is going to hold any text we want to show the user during the signup.</p>
<p>Right now, our if statements that are checking our variables aren&#8217;t executing any code, so let&#8217;s go ahead and put some code inside the first if statement.</p>
<p>Put this code inside the username if statement.</p>
<pre name="code" class="php">
$action['result'] = 'error';
array_push($text,'You forgot your username');
</pre>
<p>Let&#8217;s say the user submits the form without a username. Our statement is going to run the code above. First it&#8217;s going to set the result field of our action array to error. </p>
<p>Then we are going to use array_push() to put some text into our text array. We are going to be using this same piece of code for the final two &#8220;if&#8221; statements so copy and paste that code into the last two if statements. You&#8217;ll probably want to change the text to match the current if statement.</p>
<p>Note: We are using array_push() in case we have multiple errors in the form submission. If all if statements are executed, the text array will looks like:</p>
<pre name="code" class="php">
Array(
	[0] => 'You forgot your username',
	[1] => 'You forgot your password',
	[2] => 'You forgot your email'
)
</pre>
<p>We now need to check if we have any errors so we can continue on with the signup process.</p>
<h3>Step 6: No Errors, Let&#8217;s Signup the User</h3>
<p>We are going to check to see if our action array result value is set to error.</p>
<pre name="code" class="php">
if($action['result'] != 'error'){
	//no errors, continue signup
       $password = md5($password);
}

$action['text'] = $text;
</pre>
<p>We are also running our password through the <a href="http://ca2.php.net/md5" target="_blank">md5()</a> function. This takes the password and returns a 32 character string that looks something like this: a3470ce826283eca7ce3360d0f26b230. It&#8217;s good practice to run the password through some sort of hashing function before putting it into the database. This prevents people from viewing the users passwords if your database is hacked.</p>
<p>A quick check of our action result value and we can continue on with the signup. If our result is error we will skip over all this code and output the errors to our user so they can make the necessary changes.</p>
<p>The last piece of this code we are putting the values of your text array into our action array.</p>
<h3>Step 7: Adding the User to the Database</h3>
<p>Place this code inside our last if statement.</p>
<pre name="code" class="php">
...
If Statement checking for errors
...

//add to the database
$add = mysql_query("INSERT INTO `users` VALUES(NULL,'$username','$password','$email',0)");

if($add){

	//the user was added to the database	

}else{

	$action['result'] = 'error';
	array_push($text,'User could not be added to the database. Reason: ' . mysql_error());
	=
}
</pre>
<p>We use mysql_query() and INSERT to insert the users information into the database. Next, we create another if statement checking to see if the user was added to the database. We do this by checking if the $add variable is true or false.</p>
<p>If the user is added we can continue on with the signup; if not we are going to assign some familiar variables and stop the signup.</p>
<p>When working with MySQL queries, we use the mysql_error() function if their are errors because it helps with debugging what is wrong with your queries. It will output text errors when something is wrong. This is good!</p>
<h3>Step 8: Confirmation is Needed</h3>
<p>The user has submitted the form, everything checks out and they&#8217;re now living in the database. We want the user to be able to use their account, so let&#8217;s setup the confirmation.</p>
<pre name="code" class="php">
...
if added check
...

//get the new user id
$userid = mysql_insert_id();

//create a random key
$key = $username . $email . date('mY');
$key = md5($key);

//add confirm row
$confirm = mysql_query("INSERT INTO `confirm` VALUES(NULL,'$userid','$key','$email')");	

if($confirm){

	//let's send the email

}else{

	$action['result'] = 'error';
	array_push($text,'Confirm row was not added to the database. Reason: ' . mysql_error());

}
</pre>
<p>To make things easy, let&#8217;s assign the new user id to a variable so we can use it later. We do this by using mysql_insert_id(). This will set $userid to whatever the new user&#8217;s ID is.</p>
<p>Next we create the random key for that specific user. We create a variable named key and fill it with a value of the username, email and date. The string will look like mattmatt@email.com012009. After that we use the md5() function to convert it to a random string that is unique to that user.</p>
<p>Using mysql_query() and INSERT again, we put the new user ID, the key and the users email into the database.</p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/444_signup/images/email_template.jpg" alt="preview" width="600" height="200"/>
</div>
<h3>Step 9: Setting up the Email Templates</h3>
<p>We are going to take a break from the PHP coding and create two new files. For the sake of being quick and easy we are actually going to use two templates that I&#8217;ve included with this tutorial.</p>
<p>The two files we&#8217;re going to be looking at are signup_template.html and signup_template.txt. </p>
<p>Swift lets us assign an HTML as well as a TXT version of the email incase the users email client doesn&#8217;t support HTML emails.</p>
<p>Open up signup_template.html</p>
<p>Note: You can read up on HTML in emails over at <a href="http://carsonified.com/blog/design/html-emails-taming-the-beast/" target="_blank">carsonified</a></p>
<p>We aren&#8217;t going to be editing this file, i&#8217;m just going to explain whats going on and then you can play around with it once the tutorial is complete.</p>
<p>The most important part of this file is the tags that look like {USERNAME} and confirm.php?email={EMAIL}&#038;key={KEY}.</p>
<p>We are going to write a function that uses this template and replaces those tags with the variables from our form.</p>
<h3>Step 10: The Template Function</h3>
<p>Open up inc/php/functions.php and place this code inside.</p>
<pre name="code" class="php">
function format_email($info, $format){

	//set the root
	$root = $_SERVER['DOCUMENT_ROOT'].'/dev/tutorials/email_signup';

	//grab the template content
	$template = file_get_contents($root.'/signup_template.'.$format);

	//replace all the tags
	$template = ereg_replace('{USERNAME}', $info['username'], $template);
	$template = ereg_replace('{EMAIL}', $info['email'], $template);
	$template = ereg_replace('{KEY}', $info['key'], $template);
	$template = ereg_replace('{SITEPATH}','http://site-path.com', $template);

	//return the html of the template
	return $template;

}
</pre>
<p>format_email() is taking two variables which will be used in index.php. The first is our form information array and the second is format. We have a format variable so we can re-use this array for both the HTML and TXT versions of the template.</p>
<p>First we set the root. This points to the folder that the templates are hosted.</p>
<p>Next we open up the contents of our template and assign it to a variable.</p>
<p>Now we are going to use ereg_replace() to replace our {USERNAME} tags in our template with the content from our form. It&#8217;s basically just a super simple template system.</p>
<p>Lastly we return the template variable which holds all the html.</p>
<p>Explanation: In a nutshell, format_email() opens up our template files, takes the HTML and assigns it to our variable. This is just a cleaner way then assigning all the HTML in the function itself.</p>
<h3>Step 11: Sending the Email</h3>
<p>We are going to write another function to deal with Swift and sending the emails.</p>
<pre name="code" class="php">
function send_email($info){

	//format each email
	$body = format_email($info,'html');
	$body_plain_txt = format_email($info,'txt');

	//setup the mailer
	$transport = Swift_MailTransport::newInstance();
	$mailer = Swift_Mailer::newInstance($transport);
	$message = Swift_Message::newInstance();
	$message ->setSubject('Welcome to Site Name');
	$message ->setFrom(array('noreply@sitename.com' => 'Site Name'));
	$message ->setTo(array($info['email'] => $info['username']));

	$message ->setBody($body_plain_txt);
	$message ->addPart($body, 'text/html');

	$result = $mailer->send($message);

	return $result;

}
</pre>
<p>Just like format_email(), send_email() takes our info array as a variable.</p>
<p>The first part of the function we assign two variables, $body and $body_plain_text. We are using format_email() to assign the HTML values of our template to each variable.</p>
<p>Now comes the good part. We have setup the swift instance using Swift_MailTransport:newInstance() and then setup the mailer using Swift_Mailer::newInstance($transport);</p>
<p>We create a new instance of the Swift message with Swift_Message::newInstance() and start to assign some variables to this instance.</p>
<p>We set the subject, from email and to email address and then use setBody() to assign out text version of the email to the mailer instance. To add the HTML version we use addPart().</p>
<p>The send() function takes care of the sending of the email and then we return the result.</p>
<p>Alright, we have our email create and send functions written, let&#8217;s go back to index.php and start to wrap up the main signup.</p>
<h3>Step 12: Did we Send? Shall we Confirm?</h3>
<p>Our last bit should&#8217;ve been the if statement checking if the confirm row was created.</p>
<p>Let&#8217;s send the email and check if everything went though alright.</p>
<pre name="code" class="php">
...
if confirm
...

//include the swift class
include_once 'inc/php/swift/swift_required.php';

//put info into an array to send to the function
$info = array(
	'username' => $username,
	'email' => $email,
	'key' => $key
);

//send the email
if(send_email($info)){

	//email sent
	$action['result'] = 'success';
	array_push($text,'Thanks for signing up. Please check your email for confirmation!');

}else{

	$action['result'] = 'error';
	array_push($text,'Could not send confirm email');

}
</pre>
<p>Without the Swift class we can&#8217;t send out any emails, so in our first line, we are including the swift class.</p>
<p>We need to send our information to both of our new functions, so we create a new array and assign our variables to it.</p>
<p>I know i know, more if statements, but we need to check for errors to make it easier for the users. You always have to assume that users will make every possible mistake imaginable.</p>
<p>We wrap our send_email() function in another if statement as well as passing the $info array.</p>
<p>If the email is sent we assign a value of success and thank the user for signing up. If there are errors we use the familiar variables.</p>
<p>So now, we are almost done with the signup, just one last function needs to be created.</p>
<p>Even though we are assigning all these error/success variables and text we haven&#8217;t displayed this information to the user.</p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/444_signup/images/errors.jpg" alt="preview" width="600" height="526"/>
</div>
<p>Move back to functions.php and paste this code.</p>
<pre name="code" class="php">
//cleanup the errors
function show_errors($action){

	$error = false;

	if(!empty($action['result'])){

		$error = "
<ul class=\"alert $action[result]\">"."\n";

		if(is_array($action['text'])){

			//loop out each error
			foreach($action['text'] as $text){

				$error .= "
<li>

$text
</li>

"."\n";

			}	

		}else{

			//single error
			$error .= "
<li>

$action[text]
</li>

";

		}

		$error .= "</ul>

"."\n";

	}

	return $error;

}
</pre>
<p>This may seem confusing but it&#8217;s really just making our success/errors looks nice.</p>
<p>First it checks to see if the array is empty so we aren&#8217;t executing the code when it isn&#8217;t needed.</p>
<p>Next it creates a ul tag and applies the result as a class. This will either be success or error and is aesthetic only.</p>
<p>We then check to see if the text variable is an array or simply a string. If it&#8217;s a string, we wrap it in an li. If it&#8217;s an array we loop through each array item and wrap it in an li.</p>
<p>Lastly, we close the ul and return the entire string.</p>
<p>If we move back to index.php and place this code right after include Ôheader.php&#8217; we can wrap up this section.</p>
<pre name="code" class="php">
...
header include
...

<?= show_errors($action); ?>
</pre>
<p>A quick little explanation. We are taking all the values of our action array and passing it to the show_errors() function. If there is any content it returns a nice unordered list.</p>
<h3>Step 13: Confirming the User</h3>
<p>We should have a good grip on how the script is functioning; so for this next script I&#8217;m going to give you the entire chunk of code and then go through it with you.</p>
<p>Open up confirm.php and paste this in-between the header include and your show_errors() function.</p>
<pre name="code" class="php">
//setup some variables
$action = array();
$action['result'] = null;

//quick/simple validation
if(empty($_GET['email']) || empty($_GET['key'])){
	$action['result'] = 'error';
	$action['text'] = 'We are missing variables. Please double check your email.';
}

if($action['result'] != 'error'){

	//cleanup the variables
	$email = mysql_real_escape_string($_GET['email']);
	$key = mysql_real_escape_string($_GET['key']);

	//check if the key is in the database
	$check_key = mysql_query("SELECT * FROM `confirm` WHERE `email` = '$email' AND `key` = '$key' LIMIT 1") or die(mysql_error());

	if(mysql_num_rows($check_key) != 0){

		//get the confirm info
		$confirm_info = mysql_fetch_assoc($check_key);

		//confirm the email and update the users database
		$update_users = mysql_query("UPDATE `users` SET `active` = 1 WHERE `id` = '$confirm_info[userid]' LIMIT 1") or die(mysql_error());
		//delete the confirm row
		$delete = mysql_query("DELETE FROM `confirm` WHERE `id` = '$confirm_info[id]' LIMIT 1") or die(mysql_error());

		if($update_users){

			$action['result'] = 'success';
			$action['text'] = 'User has been confirmed. Thank-You!';

		}else{

			$action['result'] = 'error';
			$action['text'] = 'The user could not be updated Reason: '.mysql_error();;

		}

	}else{

		$action['result'] = 'error';
		$action['text'] = 'The key and email is not in our database.';

	}

}
</pre>
<p>Most of this should look very familiar; so I&#8217;m going to skip ahead to the Ò//check if the key is in the databaseÓ section.</p>
<p>Again, we use mysql_query() to get any rows in the database where the email and key are equal to the keys provided by the users email.</p>
<p>We use mysql_num_rows() to check if the number of rows returned is greater than 0.</p>
<p>If the email and key are in the database we grab all the information from the database using mysql_fetch_assoc().</p>
<p>Now that the user has confirmed his account, we need to update the database and set the active row to 1.</p>
<p>We use mysql_query() again, but instead of INSERT we use UPDATE to update the active row to 1 where the user ID is the same as our current users ID.</p>
<p>To clean everything up we use mysql_query() and DELETE to remove the confirmation row from the database. This makes sure that the user can&#8217;t come back to this page and reconfirm. It also keeps the database nice and clean.</p>
<h3>Conclusion</h3>
<p>We&#8217;ve covered many different areas in this tutorial. We downloaded and included a 3rd party script to deal with sending the emails, implemented simple form validation as well as created a super simple template system to style our emails. If you&#8217;re new to MySQL we&#8217;ve touched on the three most common functions in MySQL so you should have no problem completing some more advanced tutorials.</p>
<h3>Final Notes</h3>
<ul>
<li>I&#8217;ve used Swift Mailer as our email deployment script which can be downloaded here: http://swiftmailer.org/</li>
<li>I&#8217;ve also used button styles provided by Zurb. Be sure to check them out and give them some love. http://www.zurb.com/blog_uploads/0000/0485/buttons-02.html</li>
</ul>
<p>Thanks for reading and be sure to visit me on <a href="http://www.twitter.com/envex">Twitter</a> if you have any questions!</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/php/create-a-signup-form-with-email-confirmation/feed/</wfw:commentRss>
		<slash:comments>86</slash:comments>
		</item>
		<item>
		<title>How to Update your Twitter Status with CodeIgniter</title>
		<link>http://net.tutsplus.com/tutorials/php/how-to-update-your-twitter-status-with-codeigniter/</link>
		<comments>http://net.tutsplus.com/tutorials/php/how-to-update-your-twitter-status-with-codeigniter/#comments</comments>
		<pubDate>Mon, 21 Sep 2009 19:48:52 +0000</pubDate>
		<dc:creator>Drazen Mokic</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=6829</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/442_twitterCI/preview.jpg" alt="How to Update your Twitter with CodeIgniter" width="200" height="200"/>]]></description>
			<content:encoded><![CDATA[<p>Hi, in this tutorial we will update our twitter status via the &#8216;Twitter API&#8217; using <a href="http://www.codeigniter.com">CodeIgniter</a>. I recommend following step by step, rather than glossing over the tutorial. Let&#8217;s dig in!
</p>
<p><span id="more-6829"></span></p>
<h3>Tutorial Details</h3>
<ul>
<li><b>Program</b>: CodeIgniter PHP Framework</li>
<li><b>Version</b>: 1.7.1</li>
<li><b>Difficulty: Advanced</b> </li>
<li><b>Estimated Completion Time: 30 minutes</b> </li>
</ul>
<p><!--Configuration--></p>
<h3>1. Configuring CodeIgniter</h3>
<p>At first we need to edit some default settings within the CI config section.</p>
<p>Open the <b>system/application/config/autoload.php</b> and edit the following from:</p>
<pre name="code" class="php">
$autoload['libraries'] = array('');
</pre>
<p>to:</p>
<pre name="code" class="php">
$autoload['libraries'] = array('database');
</pre>
<p>
	This will autoload the database. Next, open <b>database.php</b> and edit the database connection setting &#8211; the name of<br />
	your database, user and password. As name we will be using <b>ci_twitter_api</b>.
</p>
<p>
	Now open <b>config.php</b> and change the <b>base_url</b> to your CI folder. My folder is called <i>twitter_api</i>.<br />
    In that folder is my <i>system</i> folder. So my base_url will be:
</p>
<pre name="code" class="php">
$config['base_url']	= "http://localhost/ci/twitter_api";
</pre>
<p><!--Step 1--></p>
<h3>2. Filling the Database</h3>
<p>
	Because we are going to work with a database, we will need some data to play with. Open <i>phpmyadmin</i> or your<br />
    favorite database management tool and create a new database called <b>ci_twitter_api</b>. Now we will set up a<br />
    new table using the following SQL query, but <b>attention</b>, use YOUR twitter username and password credentials.
</p>
<pre name="code" class="sql">
CREATE TABLE IF NOT EXISTS `accounts` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `username` varchar(120) NOT NULL,
     `password` varchar(32) NOT NULL,
     `active` int(11) NOT NULL,
     `last_message` varchar(140) NOT NULL,
     PRIMARY KEY (`id`)
   ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

   INSERT INTO `accounts` (`id`, `username`, `password`, `active`, `last_message`) VALUES
   (1, '<b>YOUR USERNAME</b>', '<b>YOUR PASSWORD</b>', 1, 'No message sent.');
</pre>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/442_twitterCI/img1.jpg" border="0" /></div>
<p>
	Click the <i>OK</i> button on the right side and the query should be processed. Now your structure for the table<br />
    <i>accounts</i> should look similar to the image below.
</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/442_twitterCI/img2.jpg" border="0" /></div>
<p><!--Step 2--></p>
<h3>3. Building the Model</h3>
<p> Go to <b>system/application/models</b> and create a new file called <b>twitter_model.php</b>.</p>
<p>
	First, we&#8217;ll declare two global variables at the top.
</p>
<pre name="code" class="php">
var $accounts_table = 'accounts';
var $update_url = 'http://twitter.com/statuses/update.xml';
</pre>
<p>
	So <b>$accounts_table</b> refers to the table we created just before, and <b>$update_url</b> is the url we will be using<br />
    to update our status. If Twitter changes their update URL, you only need to edit it one time here instead of every time its used in the code.
</p>
<p>
	Now we will create our first method which will simply return the active user account stored in the database,<br />
    based on the row <i>active</i> and value <i>1</i>. I have added this because some people have two or more Twitter<br />
    accounts.
</p>
<pre name="code" class="php">
 class Twitter_model extends Model {

    // get the active twitter account from the database, by row active = 1
    function getActiveAccount()
    {
        return $this->db->get_where($this->accounts_table, array('active' => '1'))->row();
    }
</pre>
<p>
	We are simply using <a href="http://codeigniter.com/user_guide/database/active_record.html">active records</a><br />
    to retrieve the active account and return the affected row.
</p>
<p>
	Next step, we are going to build the main method, the <i>update</i> method. This will use our<br />
    username, password and of course the message we want to send and update our status on Twitter. Apart from that,<br />
    it will interpret the <i>HTTP_CODE</i> which is returned by Twitter for telling us if the status was updated<br />
    successfully or not.
</p>
<pre name="code" class="php">
// update twitter status and last message on success
function update_status($username, $password, $message)
{
	$ch = curl_init($this->update_url);

	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, 'status='.urlencode($message));
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);

	curl_exec($ch);

	$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

	// if we were successfull we need to update our last_message
	if ($httpcode == '200')
	{
		$this->db->where('active', '1');
		$this->db->update($this->accounts_table, array('last_message' => $message));

		return TRUE;
	}

	else
	{
		return FALSE;
	}
}
</pre>
<p>
	At first view the code above may look a bit complicated but it&#8217;s not that hard to understand. The most important part is<br />
    that we use <a href="http://www.php.net/manual/en/intro.curl.php">cURL</a> to communicate with Twitter. It&#8217;s a really great<br />
    library which allows us to send and receive<i>HTTP POST</i> data from Twitter.
</p>
<p>
	Now then <b>curl_init</b> initializes a cURL session and takes the URL as a parameter &#8211; in our case the status update<br />
    URL from the <i>Twitter API</i>.
</p>
<p>
	With <b>curl_setopt</b> we set some necessary options for the cURL transfer.
</p>
<ul>
<li><b>CURLOPT_POST</b>: We set this to &#8216;1&#8242; to use HTTP POST, which is the same as used in HTML forms. </li>
<li>
    	<b>CURLOPT_POSTFIELDS</b>: This options aceepts the <i>POST Data</i> that we want to send. In our case<br />
        &#8217;status=&#8217; and our <i>message</i>. We need to <b>urlencode</b> the message to be able to use special<br />
        characters like <i>&#8216;%&#038;/&#8221; </i>.
    </li>
<li>
    	<b>CURLOPT_RETURNTRANSFER</b>: Its important for us to set this to &#8216;1&#8242; because it will return the transfer<br />
        as a string. That string will later tell us if the status was updated successfully or not.
    </li>
<li>
    	<b>CURLOPT_USERPWD</b>: This option is for authentication. It simply takes our twitter username and password<br />
        in the format <b>username:password</b>.
   </li>
</ul>
<pre name="code" class="php">
curl_exec($ch);

$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// if we were successfull we need to update our last_message
if ($httpcode == '200')
{
	$this->db->where('active', '1');
	$this->db->update($this->accounts_table, array('last_message' => $message));

	return TRUE;
}

else
{
	return FALSE;
}
</pre>
<p>
	In this part we are executing the transfer with <b>curl_exec()</b> and retrieving the returned <i>HTTP_CODE</i><br />
    using <b>curl_getinfo(CURLINFO_HTTP_CODE)</b>. This <i>HTTP_CODE</i> tells us if the status update was completed or not.<br />
    Code &#8216;200&#8242; means it worked and the update was done. You can view a complete list of HTTP status codes<br />
    <a href="http://apiwiki.twitter.com/HTTP-Response-Codes-and-Errors">here</a>.
</p>
<p>
	If we get &#8216;200&#8242; returned by Twitter, we send a query to our database which updates our last_message row, and finally<br />
    we return <i>TRUE</i>. If 200 is not returned, we simply return <i>FALSE</i>.
</p>
<p>
	To finish our <b>twitter_model</b> we will create one last method which will get the <i>last message</i> we sent. We need<br />
    this method because we will display our most recent message in a view.
</p>
<pre name="code" class="php">
// get the last_message, by row active = 1
function getLastMessage()
{
	$this->db->select('last_message');
	$last_message =  $this->db->get_where($this->accounts_table, array('active' => '1'))->row()->last_message;

	return htmlspecialchars($last_message);
}
</pre>
<p>
	This method is pretty simple. It selects the <i>last_message</i> row from our active account and returns it<br />
    converted with <a href="http://us3.php.net/manual/en/function.htmlspecialchars.php">htmlspecialchars</a> to HTML entities.<br />
    Our <b>twitter_model.php</b> now looks like this:
</p>
<pre name="code" class="php">
	class Twitter_model extends Model {

	var $accounts_table = 'accounts';
	var $update_url = 'http://twitter.com/statuses/update.xml';

	// get the active twitter account from the database, by row active = 1
	function getActiveAccount()
	{
		return $this->db->get_where($this->accounts_table, array('active' => '1'))->row();
	}

	// update twitter status and last message on success
	function update_status($username, $password, $message)
	{
		$ch = curl_init($this->update_url);

		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, 'status='.urlencode($message));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);

		curl_exec($ch);

		$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

		// if we were successfull we need to update our last_message
		if ($httpcode == '200')
		{
			$this->db->where('active', '1');
			$this->db->update($this->accounts_table, array('last_message' => $message));

			return TRUE;
		}

		else
		{
			return FALSE;
		}
	}

	// get the last_message, by row active = 1
	function getLastMessage()
	{
		$this->db->select('last_message');
		$last_message =  $this->db->get_where($this->accounts_table, array('active' => '1'))->row()->last_message;

		return htmlspecialchars($last_message);
	}
}
</pre>
<p><!--Step 3--></p>
<h3>4. Building the Controller</h3>
<p>
	Now go to <b>system/application/controllers</b> and create a new file called <b>twitter.php</b>.<br />
    Let&#8217;s add some lines:
</p>
<pre name="code" class="php">
class Twitter extends Controller {

function Twitter()
{
	parent::Controller();

	$this->load->model('twitter_model');
}
</pre>
<p>
	This is a simple CI constructor which loads our <i>twitter_model</i>. So it will be available to us within the whole controller.<br />
    Now comes the <b>index()</b> method.
</p>
<pre name="code" class="php">
function index()
{
	$data['heading'] = 'Hi, send a tweet!';
	$data['last_message'] = $this->twitter_model->getLastMessage();
	$data['active_user'] = $this->twitter_model->getActiveAccount()->username;

	$this->load->view('header', $data);
	$this->load->view('index');
	$this->load->view('footer');
}
</pre>
<p>
	We are passing information like some text, our last message and the username of the active user to the <i>$data</i> array.<br />
    Thanks to our <i>twitter_model</i> it&#8217;s a cinch to grab the last message and the active username. At least we are loading some<br />
    <i>views</i> which we will create after we finish our controller. Let&#8217;s build the <b>update</b> method.
</p>
<pre name="code" class="php">
// updating our status on twitter ( new message )
function update()
{
	if ($this->input->post('submit'))
	{
		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('&lt;div class="error">', '&lt;/div>');
		$this->form_validation->set_rules('message', 'Message', 'trim|required|min_length[5]|max_length[140]');

		if ($this->form_validation->run() == FALSE)
		{
			$this->index();
		}

		else
		{
			$message = $this->input->post('message');

			// get useraccount data
			$account = $this->twitter_model->getActiveAccount();
			$username = $account->username;
			$password = $account->password;

			// send a tweet
			if ($this->twitter_model->update_status($username, $password, $message))
			{
				redirect('twitter');
			}

			else
			{
				$data['error'] = 'There was an error while updating your status';

				$this->load->view('header', $data);
				$this->load->view('error');
				$this->load->view('footer');
			}
		}
	}
</pre>
<p>
	This may be confusing again but we will go through it part by part.
</p>
<pre name="code" class="php">
if ($this->input->post('submit'))
	{
		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('
<div class="error">', '</div>

');
		$this->form_validation->set_rules('message', 'Message', 'trim|required|min_length[5]|max_length[140]');

		if ($this->form_validation->run() == FALSE)
		{
			$this->index();
		}
</pre>
<p>
	With <b>$this->input->post(&#8217;submit&#8217;)</b> we check if the form was submitted &#8211; which we will create later in our main view<br />
    file. After that, we load the <b>form_validation</b> library because we want to ensure that certain inputs require some rules,<br />
    like a minimum and maximum length of 5 and 140 characters. Additionally we are trimming off the whitespace with <i>trim</i> and<br />
    setting the field as <i>required</i> because we don&#8217;t need an empty message. The function <b>set_rules</b> takes, as the first parameter,<br />
    the name of the from field, our case <i>message</i> (which will be created soon in the view) and as second parameter a human<br />
    the name for this field, which will be inserted into the error message ( will be done in the view file ).
</p>
<p>
	We call <b>$this->form_validation->run()</b>, which can return <i>TRUE</i> or <i>FALSE</i>. If a rule we set was broken it<br />
    will return <i>FALSE</i> and we simply call our <i>index()</i> method. In the view files called by the index() method the<br />
    error messages will be displayed after we have created our views.
</p>
<pre name="code" class="php">
else
   {
       $message = $this->input->post('message');

       // get useraccount data
       $account = $this->twitter_model->getActiveAccount();
       $username = $account->username;
       $password = $account->password;

       // send a tweet
       if ($this->twitter_model->update_status($username, $password, $message))
       {
           redirect('twitter');
       }

       else
       {
           $data['error'] = 'There was an error while updating your status';

           $this->load->view('header', $data);
           $this->load->view('error');
           $this->load->view('footer');
       }
   }
</pre>
<p>
	Thanks to our <i>twitter_model</i>, again it&#8217;s so easy to retrieve the <i>username</i> and the <i>password</i> of the current active user.<br />
    We could also do <i>$username = $this->twitter_model->getActiveAccount()->username</i> but I think for this tutorial this is<br />
    a little bit easier to understand.
</p>
<p>
	Using <b>$this->twitter_model->update_status()</b> we call the method that will &#8220;talk&#8221; to Twitter. It tells Twitter our<br />
    <i>username</i>, <i>password</i> and our message. If the status was updated successfully, we redirect, using <b>redirect()</b> from the <i>url helper</i>.
</p>
<p>
	If something was wrong, we set an error message and load some view files, which will be created in the next step <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .<br />
    The Controller looks now like this:
</p>
<pre name="code" class="php">
	class Twitter extends Controller {

	function Twitter()
	{
		parent::Controller();

		$this->load->model('twitter_model');
	}

	function index()
	{
		$data['heading'] = 'Hi, send a tweet!';
		$data['last_message'] = $this->twitter_model->getLastMessage();
		$data['active_user'] = $this->twitter_model->getActiveAccount()->username;

		$this->load->view('header', $data);
		$this->load->view('index');
		$this->load->view('footer');
	}

	// updating our status on twitter ( new message )
	function update()
	{
		if ($this->input->post('submit'))
		{
			$this->load->library('form_validation');
			$this->form_validation->set_error_delimiters('
<div class="error">', '</div>

');
			$this->form_validation->set_rules('message', 'Message', 'trim|required|min_length[5]|max_length[140]');

			if ($this->form_validation->run() == FALSE)
			{
				$this->index();
			}

			else
			{
				$message = $this->input->post('message');

				// get useraccount data
				$account = $this->twitter_model->getActiveAccount();
				$username = $account->username;
				$password = $account->password;

				// send a tweet
				if ($this->twitter_model->update_status($username, $password, $message))
				{
					redirect('twitter');
				}

				else
				{
					$data['error'] = 'There was an error while updating your status';

					$this->load->view('header', $data);
					$this->load->view('error');
					$this->load->view('footer');
				}
			}
		}

		else
		{
			redirect('twitter');
		}
	}
}
</pre>
<p><!--Step 4--></p>
<h3>5. Creating the Views</h3>
<p>
	Now we will create our view files. Go to <b>system/application/views</b> and create the following files:
</p>
<ul>
<li>header.php</li>
<li>footer.php</li>
<li>index.php</li>
<li>error.php</li>
</ul>
<p>
	The <b>header.php</b> will contain the basic html meta information, our CSS link, and the opening tags of our main divs,<br />
    <i>#wrapper</i> and <i>#main</i>.
</p>
<pre name="code" class="php">
    &lt;!DOCTYPE html>
    &lt;html>
    &lt;head>
    &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    &lt;link media="screen" rel="Stylesheet" type="text/css" href="&lt;?php echo base_url(); ?>css/style.css" />
    &lt;title>Using the Twitter API with CodeIgniter&lt;/title>
    &lt;/head>

    &lt;body>

    &lt;div id="wrapper">

    &lt;div id="main">
</pre>
<p>
	We are using <b>base_url()</b> which we configured to reference our CSS file, which will be created in the next step.
</p>
<p>
	The <b>footer.php</b> simply contains our closing tags.
</p>
<pre name="code" class="html">
	&lt;/div>&lt;!--end main-->

    &lt;/div>&lt;!--end wrapper-->

    &lt;/body>
    &lt;/html>
</pre>
<p>
	The <b>index.php</b> is where the party goes.
</p>
<pre name="code" class="php">
	&lt;h3>
	&lt;?php echo $heading; ?>
    &lt;span>
    	( account: &lt;?php echo anchor('http://twitter.com/' . $active_user, $active_user); ?> )
    &lt;/span>
    &lt;/h3>

    &lt;?php echo form_error('message'); ?>

    &lt;?php echo form_open('twitter/update', array('id' => 'update_form')); ?>
    &lt;?php echo form_input(array('name' => 'message', 'maxlength' => '140')); ?>
    &lt;?php echo form_submit('submit', 'update'); ?>
    &lt;?php echo form_close(); ?>

    &lt;div id="last_message">
        &lt;fieldset>
            &lt;legend>Last &lt;span>sent by &lt;b>&lt;?php echo $active_user ?>&lt;/b>&lt;/span>&lt;/legend>
            &lt;p>&lt;?php echo $last_message; ?>&lt;/p>
        &lt;/fieldset>
    &lt;/div><!--end last_message-->
</pre>
<p>
	All variables used here are passed through the <b>index()</b> method from our controller. In addition to that,<br />
    we are using the <i>form helper</i> to create a simple html form. Remember, I told you the error handling for the<br />
    message field will be done here; <b>form_error(&#8217;message&#8217;)</b> is doing that magic.
</p>
<p>
	Below the form we are displaying the last message sent by the active user&#8217;s account.
</p>
<p>Finally the <b>error.php</b> will be used for a custom error file in case the status update was unsuccessful.</p>
<pre name="code" class="php">
	&lt;h3>&lt;?php echo $error; ?>&lt;/h3>

     &lt;?php echo anchor('twitter', 'Go back and try again'); ?>
</pre>
<p><!--Step 5--></p>
<h3>6. Adding some CSS</h3>
<p>
	To make it a bit prettier, we will add some CSS. Go to <b>system/</b><br />
    and create the folder <b>css</b>. Inside of that folder create a file called <b>style.css</b> and insert<br />
    the following code.
</p>
<pre name="code" class="css">
    /* Reset CSS */

    html, body, div, span, object, h1, h2, h3, h4, h5, h6, p, blockquote, pre,
    a, address, code, img,
    small, strong, dl, dt, dd, ol, ul, li,
    fieldset, form, label {
        margin: 0;
        padding: 0;
        border: 0;
        outline: 0;
        font-size: 100%;
        vertical-align: baseline;
        background: transparent;
    }

    body {
    	line-height: 1.5;
        font-family:Arial, sans-serif;
        margin:0;
    }
    ol, ul, li {
        list-style: none;
        list-style-type:none;
    }

    .clear { clear:both; }

    /* DEFAULTS */

    h3 {
        color:#35CCFF;
        font-size:20px;
    }

    /* CUSTOM */

    #wrapper {
        width:900px;
        margin:0 auto;
    }

    /* main */

    #main {
        margin-top:50px;
    }

    #main h3 span {
        font-size:14px;
        color:#cccccc;
    }

    #main h3 a {
        color:#cccccc;
    }

    /* form */

    #update_form input {
        width:888px;
        padding:5px;
        border:1px solid #d3d3d3;
        display:block;
    }

    #update_form input[type="submit"] {
        width:auto;
        margin-top:10px;
        background-color:#000000;;
        border:none;
        color:white;
        font-size:12px;
        font-weight:bold;
        cursor:pointer;
        padding:3px;
    }

    div.error {
        display:block;
        background-color:#FB8A8A;
        border:1px solid #FF3B3B;
        padding:5px;
        color:#ffffff;
        width:50%;
        margin-bottom:30px;
        font-weight:bold;
        margin:0 auto 10px auto;
        text-align:center;
    }

    /* last message */

    #last_message fieldset {
        border:1px dashed #d3d3d3;
        padding:5px;
        margin-top:30px;
    }

    #last_message fieldset p {
        padding:5px;
        font-size:18px;
        font-weight:normal;
    }

    #last_message legend span {
        font-size:12px;
    }
</pre>
<p>
	I am using <a href="http://meyerweb.com/">Eric Meyers</a> CSS reset to neutralize the view on all browsers. Your application should now likebthe image below.
</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/442_twitterCI/img3.jpg" border="0" /></div>
<p><!--Step 6--></p>
<h3>The Big Finale</h3>
<p>Let&#8217;s test our fresh application. We&#8217;ll drop a message and press the <i>update</i> button!</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/442_twitterCI/img4.jpg" border="0" /></div>
<p>After the update was made:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/442_twitterCI/img5.jpg" border="0" /></div>
<p>Lets take a look at Twitter <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/442_twitterCI/img6.jpg" border="0" /></div>
<p>if we are violating a form validation rule by trying to send an empty message:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/442_twitterCI/img7.jpg" border="0" /></div>
<p><!--Conclusion--></p>
<h3>Conclusion</h3>
<p>
	I really hope that I helped you a little bit with learning CodeIgniter and how to use the great Twitter API! Would you have done anything differently? If so, let us know!
</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/php/how-to-update-your-twitter-status-with-codeigniter/feed/</wfw:commentRss>
		<slash:comments>42</slash:comments>
		</item>
		<item>
		<title>Getting Clean With PHP</title>
		<link>http://net.tutsplus.com/tutorials/php/getting-clean-with-php/</link>
		<comments>http://net.tutsplus.com/tutorials/php/getting-clean-with-php/#comments</comments>
		<pubDate>Tue, 15 Sep 2009 07:57:01 +0000</pubDate>
		<dc:creator>Michael Owens</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[clean php]]></category>
		<category><![CDATA[sanitizing]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=6732</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/437_gettingClean/images/preview.jpg" alt="Getting Clean With PHP" width="200" height="200"/>]]></description>
			<content:encoded><![CDATA[<p>Data security is important and often undervalued by designers, developers, and clients alike. Since PHP 5.2.0, data sanitization and validation has been made significantly easier with the introduction of data filtering. Today, we&#8217;re going to take a closer look at these filters, how to use them, and build a few custom functions.</p>
<p><span id="more-6732"></span></p>
<h3>Tutorial Details</h3>
<ul>
<li><b>Program</b>: PHP </li>
<li><b>Version</b>: 5.2.0+</li>
<li><b>Difficulty:</b> Beginner</li>
<li><b>Estimated Completion Time:</b> 20 minutes</li>
</ul>
<div class="tutorial_image">
<a href="http://nettuts.s3.amazonaws.com/437_gettingClean/demo.zip"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg"></a>
</div>
<h3>Introduction</h3>
<p>I have always felt that it&#8217;s easy to write code in PHP, and even easier to write bad code in PHP. The proliferation of PHP on the web has really been helped out by its use in popular open-source software packages like WordPress, Drupal, and Magento as well as major web applications like Facebook; with PHP being used in so many varied instances (dynamic websites, in-depth web applications, blogging platforms, content management systems, and e-commerce being only a subset of the many applications of PHP) the opportunities for <em>dirty</em> data and insecure systems are numerous. This tutorial will explain some methods of <strong>Getting Clean With PHP: Data Sanitization and Validation</strong> by focusing on several different forms of data inputs and how to use PHP filters and custom functions.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/437_gettingClean/images/forms_to_clean.png" border="0" alt="Sanitization and Validation of Forms" /></div>
<h3>Why Sanitize and Validate?</h3>
<p>In this tutorial, we are really focused on data inputs that users or external sources may provide. This means that we do not control the data we are receiving. All we can do is control what is done with it after we receive it. There are all sorts of threats related to data security from user-inputs and third-party data.</p>
<p>Some <em>un-</em>popular data security threats:</p>
<ul>
<li><strong>Cross-Site Scripting (XSS)</strong>: A form of code injection where a script is injected onto a website from a completely different website. This is by far the most common security vulnerability online. Two recent, very prominent examples of this technique are the <a href="http://bit.ly/TwitterXSS">Stalk Daily and Mikeyy Twitter Worms</a> from earlier this year that used poorly sanitized inputs to launch Javascript via an &#8220;infected&#8221; Twitter web interface.</li>
<li><strong>SQL Injection</strong>: The second most common security vulnerability online, this is another form of code injection in which a script is used to participate in one of numerous exploitative behaviors including (but not limited to) exposing and/or gaining unauthorized access to data, altering data inside of a database, or simply injecting code to be rendered or executed within a website thereby breaking or altering the website.</li>
<li><strong>Cross-Site Request Forgery (CSRF/XSRF)</strong>: A less common exploit that relies more on data sources like browser and session cookies than poorly sanitized and validated data inputs, CSRF (pronounced &#8220;sea-surf&#8221;) can be used to execute commands on a website without the user&#8217;s permission. One popular CSRF method is using an improperly formed image data URI or src value to execute a script instead of displaying an image.</li>
<li><strong>Improper Data</strong>: Not really a &#8220;security vulnerability&#8221; <em>per se</em>, improper data can cause hosts of problems for a website owner or database administrator. Often, improper data can break poorly coded websites or cause automated systems to crash. An example of this was the ability to alter entire MySpace profile pages by posting using all sorts of HTML/CSS hackery (Note: this may still work; I&#8217;ve not used MySpace in a long time).</li>
</ul>
<div class="tutorial_image">
	<img src="http://nettuts.s3.amazonaws.com/437_gettingClean/images/exploits_of_a_mom.png" border="0" alt="Exploits of a Mom" title="Her daughter is named Help I'm trapped in a driver's license factory." /></p>
<div><em>Image Source: <a href="http://xkcd.com/327/">XKCD</a></em></div>
</div>
<p>For our purposes, we are going to only focus on server-side methods of improving data security with PHP, so let&#8217;s see how the terms &#8220;sanitization&#8221; and &#8220;validation&#8221; are defined with relation to PHP. According to the <a href="http://www.php.net/manual/en/intro.filter.php">PHP manual</a>:</p>
<blockquote><p>Validation is used to validate or check if the data meets certain qualifications. For example, passing in FILTER_VALIDATE_EMAIL will determine if the data is a valid email address, but will not change the data itself.</p>
<p>Sanitization will sanitize the data, so it may alter it by removing undesired characters. For example, passing in FILTER_SANITIZE_EMAIL will remove characters that are inappropriate for an email address to contain. That said, it does not validate the data.</p></blockquote>
<p>Essentially, if your website is the nightclub that everybody wants to get into, validation checks the guest list and IDs at the door while sanitization acts as the bouncer that throws out any undesirables that happen to squeak past. With this in mind, let&#8217;s take a look at PHP Filters Extension.</p>
<h3>What Filters Do I Have?</h3>
<p>All PHP installations are not created equal. While PHP 5.2.0 was the introduction of filters, not all installations have the same set of filters in their Filters Extension. Most installations will have all of the filters we&#8217;re going to go over, but to teach you a bit about the Filters Extension, we&#8217;re going to find out just what you have on your server. In the source download, I have included a file called <em>getfilters.php</em> that, once installed and run on your server, will display all of your filters (both data filters available through the <strong>filter_var</strong> function and stream filters available through <strong>stream_filter_append</strong>).</p>
<pre name="code" class="php">
 echo "&lt;h1&gt;Data Filters&lt;/h1&gt;\n&lt;table&gt;\n&lt;tr&gt;\n";
 echo "&lt;td&gt;&lt;strong&gt;Filter ID&lt;/strong&gt;&lt;/td&gt;\n";
 echo "&lt;td&gt;&lt;strong&gt;Filter Name&lt;/strong&gt;&lt;/td&gt;\n&lt;/tr&gt;";
 foreach(filter_list() as $id =&gt;$filter) {
	 echo "&lt;tr&gt;&lt;td&gt;$filter&lt;/td&gt;&lt;td&gt;".filter_id($filter)."&lt;/td&gt;&lt;/tr&gt;\n";
 }
 echo "&lt;/table&gt;\n";
</pre>
<p>First, we get the array containing the list of all available filters with <strong>filter_list</strong>, then we loop through the array and echo out the filter name, find out the filter&#8217;s assigned ID, and echo this ID as well.</p>
<h3>How Do I Use A Filter?</h3>
<p>PHP Filters for validation and sanitization are activated by passing at least two values to the PHP Filters Extension function <em>filter_var</em>. As an example, let&#8217;s use the Sanitize Filter for an Integer number like so:</p>
<pre name="code" class="php">
$value = '123abc456def';
echo filter_var($value, FILTER_SANITIZE_NUMBER_INT);
</pre>
<p>In the example, we have a variable <em>$value</em> that is passed through the Filters Extension function <em>filter_var</em> using the <em>FILTER_SANITIZE_NUMBER_INT</em> filter. This results in the following output:</p>
<pre name="code" class="html">
123456
</pre>
<p>The Sanitize Filter for an Integer number removes all non-integer characters from the output and produces a clean integer. Within the <a href="http://nettuts.s3.amazonaws.com/437_gettingClean/demo.zip">download source code</a>, you can try out various inputs and it will apply a number of common filters to your input value. I have included a number of different example strings that you can test out as well.</p>
<h3>What Do The Different Filters Do?</h3>
<p>The list below is not complete, but it does contain the majority of the filters that come standard with 5.2.0+ installations. Custom filters and those added from custom extensions are not included here.</p>
<p><strong>FILTER_VALIDATE_BOOLEAN:</strong> Checks whether or not the data passed to the filter is a boolean value of <em>TRUE</em> or <em>FALSE</em>. If the value is a non-boolean value, it will return <em>FALSE</em>. The script below would echo &#8220;TRUE&#8221; for the example data <em>$value01</em> but would echo &#8220;FALSE&#8221; for the example data <em>$value02</em>:</p>
<pre name="code" class="php">
$value01 = TRUE;
if(filter_var($value01,FILTER_VALIDATE_BOOLEAN)) {
 echo 'TRUE';
} else {
 echo 'FALSE';
}
echo '&lt;br /&gt;&lt;br /&gt;'
$value02 = TRUE;
if(filter_var($value02,FILTER_VALIDATE_BOOLEAN)) {
 echo 'TRUE';
} else {
 echo 'FALSE';
}
</pre>
<p><strong>FILTER_VALIDATE_EMAIL:</strong> Checks whether or not the data passed to the filter is a potentially valid e-mail address. It does not check whether the e-mail address actually exists, just that the format of the e-mail address is valid. The Script below would echo &#8220;TRUE&#8221; for the example data <em>$value01</em> but would echo &#8220;FALSE&#8221; for the example data <em>$value02</em> (because the second lacks the required @domain.tld portion of the e-mail address):</p>
<pre name="code" class="php">
$value01 = 'test@example.com';
if(filter_var($value01,FILTER_VALIDATE_EMAIL)) {
 echo 'TRUE';
} else {
 echo 'FALSE';
}
echo '&lt;br /&gt;&lt;br /&gt;'
$value02 = 'nettuts';
if(filter_var($value02,FILTER_VALIDATE_EMAIL)) {
 echo 'TRUE';
} else {
 echo 'FALSE';
}
</pre>
<p><strong>FILTER_VALIDATE_FLOAT:</strong> Checks whether or not the data passed to the filter is a valid float value. The Script below would echo &#8220;TRUE&#8221; for the example data <em>$value01</em> but would echo &#8220;FALSE&#8221; for the example data <em>$value02</em> (because comma separators are not allowed in float values):</p>
<pre name="code" class="php">
$value01 = '1.234';
if(filter_var($value01,FILTER_VALIDATE_FLOAT)) {
 echo 'TRUE';
} else {
 echo 'FALSE';
}
echo '&lt;br /&gt;&lt;br /&gt;'
$value02 = '1,234';
if(filter_var($value02,FILTER_VALIDATE_FLOAT)) {
 echo 'TRUE';
} else {
 echo 'FALSE';
}
</pre>
<p><strong>FILTER_VALIDATE_INT:</strong> Checks whether or not the data passed to the filter is a valid integer value. The Script below would echo &#8220;TRUE&#8221; for the example data <em>$value01</em> but would echo &#8220;FALSE&#8221; for the example data <em>$value02</em> (because fractions / decimal numbers are not integers):</p>
<pre name="code" class="php">
$value01 = '123456';
if(filter_var($value01,FILTER_VALIDATE_INT)) {
 echo 'TRUE';
} else {
 echo 'FALSE';
}
echo '&lt;br /&gt;&lt;br /&gt;'
$value02 = '123.456';
if(filter_var($value02,FILTER_VALIDATE_INT)) {
 echo 'TRUE';
} else {
 echo 'FALSE';
}
</pre>
<p><strong>FILTER_VALIDATE_IP:</strong> Checks whether or not the data passed to the filter is a potentially valid IP address. It does not check if the IP address would resolve, just that it fits the required data structure for IP addresses. The Script below would echo &#8220;TRUE&#8221; for the example data <em>$value01</em> but would echo &#8220;FALSE&#8221; for the example data <em>$value02</em>:</p>
<pre name="code" class="php">
$value01 = '192.168.0.1';
if(filter_var($value01,FILTER_VALIDATE_IP)) {
 echo 'TRUE';
} else {
 echo 'FALSE';
}
echo '&lt;br /&gt;&lt;br /&gt;'
$value02 = '1.2.3.4.5.6.7.8.9';
if(filter_var($value02,FILTER_VALIDATE_IP)) {
 echo 'TRUE';
} else {
 echo 'FALSE';
}
</pre>
<p><strong>FILTER_VALIDATE_URL:</strong> Checks whether or not the data passed to the filter is a potentially valid URL. It does not check if the URL would resolve, just that it fits the required data structure for URLs. The Script below would echo &#8220;TRUE&#8221; for the example data <em>$value01</em> but would echo &#8220;FALSE&#8221; for the example data <em>$value02</em>:</p>
<pre name="code" class="php">
$value01 = 'http://net.tutsplus.com';
if(filter_var($value01,FILTER_VALIDATE_URL)) {
 echo 'TRUE';
} else {
 echo 'FALSE';
}
echo '&lt;br /&gt;&lt;br /&gt;'
$value02 = 'nettuts';
if(filter_var($value02,FILTER_VALIDATE_URL)) {
 echo 'TRUE';
} else {
 echo 'FALSE';
}
</pre>
<p><strong>FILTER_SANITIZE_STRING:</strong> By default, this filter removes any data from a string that is invalid or not allowed in that string. For example, this will remove any HTML tags, like <em>&lt;script&gt;</em> or <em>&lt;strong&gt;</em> from an input string:</p>
<pre name="code" class="php">
$value = '&lt;script&gt;alert('TROUBLE HERE');&lt;/script&gt;';
echo filter_var($value, FILTER_SANITIZE_STRING);
</pre>
<p>This script would remove the tags and return the following:</p>
<pre name="code" class="html">
alert('TROUBLE HERE');
</pre>
<p><strong>FILTER_SANITIZE_ENCODED:</strong> Many programmers use PHP&#8217;s <em>urlencode()</em> function to handle their URL Encoding. This filter essentially does the same thing. For example, this will encode any spaces and/or special characters from an input string:</p>
<pre name="code" class="php">
$value = '&lt;script&gt;alert('TROUBLE HERE');&lt;/script&gt;';
echo filter_var($value, FILTER_SANITIZE_ENCODED);
</pre>
<p>This script would encode the punctuation, spaces, and brackets, then return the following:</p>
<pre class="html" name="code">
%3Cscript%3Ealert%28%27TROUBLE%20HERE%27%29%3B%3C%2Fscript%3E
</pre>
<p><strong>FILTER_SANITIZE_SPECIAL_CHARS:</strong> This filter will, by default, HTML-encode special characters like quotes, ampersands, and brackets (in addition to characters with ASCII value less than 32). While the demo page does not make it abundantly clear without viewing the source (because the HTML-encoded special characters will be interpreted and rendered out), if you take a look at the source code you&#8217;ll see the encoding at work:</p>
<pre name="code" class="php">
$value = '&lt;script&gt;alert('TROUBLE HERE');&lt;/script&gt;';
echo filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS);
</pre>
<p>It converts the special characters into their HTML-encoded selves:</p>
<pre class="html" name="code">
&amp;#60;script&amp;#62;alert(&amp;#39;TROUBLE HERE&amp;#39;);&amp;#60;/script&amp;#62;
</pre>
<p><strong>FILTER_SANITIZE_EMAIL:</strong> This filter does exactly what one would think it does. It removes any characters that are invalid in e-mail addresses (like parentheses, brackets, colons, etc). For example, let&#8217;s say you accidentally added parentheses around a letter of your e-mail address (don&#8217;t ask how, use your imagination):</p>
<pre name="code" class="php">
$value = 't(e)st@example.com';
echo filter_var($value, FILTER_SANITIZE_EMAIL);
</pre>
<p>It removes those parentheses and you get your beautiful e-mail address back:</p>
<pre class="html" name="code">
test@example.com
</pre>
<p>This is a great filter to use on e-mail forms in concert with FILTER_VALIDATE_EMAIL to reduce user error or prevent XSS-related attacks (as some past XSS attacks involved the returning of the original data provided in a non-sanitized e-mail field directly to the browser).</p>
<p><strong>FILTER_SANITIZE_URL:</strong> Similar to the e-mail address sanitize filter, this filter does exactly what one would think, as well. It removes any characters that are invalid in a URL (like certain UTF-8 characters, etc). For example, let&#8217;s say you accidentally added a &#8220;®&#8221; into your website&#8217;s URL (again, don&#8217;t ask how, pretend a velociraptor did it):</p>
<pre name="code" class="php">
$value = 'http://net.tuts®plus.com';
echo filter_var($value, FILTER_SANITIZE_URL);
</pre>
<p>It removes the unwanted &#8220;®&#8221; and you get your handsome URL back:</p>
<pre class="html" name="code">
http://net.tutsplus.com
</pre>
<p><strong>FILTER_SANITIZE_NUMBER_INT:</strong> This filter is similar to the FILTER_VALIDATE_INT but instead of simply checking if it is an Integer or not, it actually removes everything non-integer from the value! Handy, indeed, for pesky spambots and tricksters in some input forms:</p>
<pre name="code" class="php">
$value01 = '123abc456def';
echo filter_var($value01, FILTER_SANITIZE_NUMBER_INT);
echo '&lt;br /&gt;';
$value02 = '1.2.3.4.5.6.7.8.9';
echo filter_var($value02, FILTER_SANITIZE_NUMBER_INT);
</pre>
<p>Those silly letters and decimals get thrown right out:</p>
<pre class="html" name="code">
123456
123456789
</pre>
<p><strong>FILTER_SANITIZE_NUMBER_FLOAT:</strong> This filter is similar to the FILTER_VALIDATE_INT but instead of simply checking if it is an Integer or not, it actually removes everything non-integer from the value! Handy, indeed, for pesky spambots and tricksters in some input forms:</p>
<pre name="code" class="php">
$value01 = '123abc456def';
echo filter_var($value01, FILTER_SANITIZE_NUMBER_FLOAT);
echo '&lt;br /&gt;';
$value02 = '1.2.3.4.5.6.7.8.9';
echo filter_var($value02, FILTER_SANITIZE_NUMBER_FLOAT);
</pre>
<p>Again, all those silly letters and decimals get thrown right out:</p>
<pre name="code" class="html">
123456
123456789
</pre>
<p>But what if you wanted to keep a decimal like in the next example:</p>
<pre name="code" class="php">
$value = '1.23';
echo filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT);
</pre>
<p>It would still remove it and return:</p>
<pre name="code" class="html">
123
</pre>
<p>One of the main reasons why FILTER_SANITIZE_NUMBER_FLOAT and FILTER_SANITIZE_INT are separate filters is to allow for this via a special Flag &#8220;FILTER_FLAG_ALLOW_FRACTION&#8221; that is added as a third value passed to <em>filter_var</em>:</p>
<pre name="code" class="php">
$value = '1.23';
echo filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
</pre>
<p>It would keep the decimal and return:</p>
<pre name="code" class="html">
1.23
</pre>
<h3>Options, Flags, and Array Controls, OH MY!</h3>
<p>The flag in this last example is just one of many more options, flags, and array controls that allow you to have more granular control over what types of data gets sanitized, definitions of delimiters, how arrays are processed by the filters, and more. You can find more about these flags and other filter-related functions in the PHP manual&#8217;s <a href="http://www.php.net/manual/en/book.filter.php">Filters Extension section</a>.</p>
<h3>Other Methods of Santizing Data with PHP</h3>
<p>Now, we&#8217;ll go over a few key supplemental methods of sanitizing data with PHP to prevent &#8220;dirty data&#8221; from wreaking havoc on your systems. These are especially useful for applications still running PHP 4, as they were all available when it was released.</p>
<p><strong>htmlspecialchars</strong>: This PHP function converts 5 special characters into their corresponding HTML entities:</p>
<ul>
<li>&#8216;&amp;&#8217; (ampersand) becomes &#8216;&amp;amp;&#8217;</li>
<li>&#8216;&#8221;&#8216; (double quote) becomes &#8216;&amp;quot;&#8217; when ENT_NOQUOTES is not set.</li>
<li>&#8221;&#8217; (single quote) becomes &#8216;&amp;#039;&#8217; only when ENT_QUOTES is set.</li>
<li>&#8216;&lt;&#8217; (less than) becomes &#8216;&amp;lt;&#8217;</li>
<li>&#8216;&gt;&#8217; (greater than) becomes &#8216;&amp;gt;&#8217;</li>
</ul>
<p>It is used like any other PHP string function:</p>
<pre name="code" class="php">
echo htmlspecialchars('$string');
</pre>
<p><strong>htmlentities</strong>: Like htmlspecialchars, this PHP function converts characters into their corresponding HTML entities. The big difference is that <strong>ALL</strong> characters that can be converted will be converted. This is a useful method of obfuscating e-mail addresses from some bots that collect e-mail addresses, as not of them are programmed to read htmlentities.</p>
<p>It is used like any other PHP string function:</p>
<pre name="code" class="php">
echo htmlentities('$string');
</pre>
<p><strong>mysql_real_escape_string</strong>: This MySQL function helps protect against SQL injection attacks. It is considered a best practice (or even a mandatory practice) to pass all data that is being sent to a MySQL query through this function. It escapes any special characters that could be problematic and would cause little Bobby Tables to destory yet another school students database.</p>
<pre name="code" class="php">
$query = 'SELECT * FROM table WHERE value='.mysql_real_escape_string('$string').' LIMIT 1,1';
$runQuery = mysql_query($query);
</pre>
<h3>Custom Functions</h3>
<p>For many people, these built-in filters and functions are just not good enough. Data validation of some data like phone numbers, zip codes, or even e-mails often requires more strict validation and masking. To do this, many people create custom functions to validate and their data is real. An example of this may be as simple as using a MySQL query to look up the data in a database of known values like so:</p>
<pre name="code" class="php">
function checkZipCode($value) {
	$zipcheck = 'SELECT COUNT(*) FROM `database`.`zipcodes` WHERE value="'.filter_var(mysql_real_escape_string($value),FILTER_SANITIZE_NUMBER_INT).'"';
	$count = mysql_query($zipcheck);
	if($count==1) {
		return TRUE;
	} else {
		return FALSE;
	}
}
</pre>
<p>Other custom functions can be made that do not rely on databases of known values, and can be created by checking magic-quotes, stripping slashes, and escaping for insert into a database:</p>
<pre name="code" class="php">
function cleanString($string) {
	$detagged = strip_tags($string);
	if(get_magic_quotes_gpc()) {
		$stripped = stripslashes($detagged);
		$escaped = mysql_real_escape_string($stripped);
	} else {
		$escaped = mysql_real_escape_string($detagged);
	}
	return $escaped;
}
</pre>
<p>The possibilities are endless, especially if you integrate regular expressions, but for most occasions, the PHP Filters Extension should do the trick.</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/php/getting-clean-with-php/feed/</wfw:commentRss>
		<slash:comments>73</slash:comments>
		</item>
		<item>
		<title>Supercharge Your CSS with PHP Under the Hood</title>
		<link>http://net.tutsplus.com/tutorials/php/supercharge-your-css-with-php-under-the-hood/</link>
		<comments>http://net.tutsplus.com/tutorials/php/supercharge-your-css-with-php-under-the-hood/#comments</comments>
		<pubDate>Mon, 24 Aug 2009 15:16:19 +0000</pubDate>
		<dc:creator>Michael Owens</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[css variable]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=6409</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/416_superCharge/images/preview.jpg" alt="Supercharge Your CSS With PHP Under The Hood" width="200" height="200"/>]]></description>
			<content:encoded><![CDATA[<p>Cascading Style Sheets is a presentational style sheet language. In that sense, it does not have a lot of the functionality that many developers want to satisfy their programmer instincts. Today, we&#8217;re going to go over how to supercharge your CSS by putting some PHP under the hood.</p>
<p><span id="more-6409"></span></p>
<h3>Tutorial Details</h3>
<ul>
<li><b>Program</b>: Apache, PHP</li>
<li><b>Version</b>: n/a</li>
<li><b>Difficulty:</b> Intermediate</li>
<li><b>Estimated Completion Time:</b> 20 minutes</li>
</ul>
<h3>Introduction</h3>
<p>Using CSS to power up a website is a requisite in the contemporary web for non-Flash websites &#8211; and for good reason. CSS is powerful. It can make or break a website (although usually IE6 is doing the breaking). Even with its usefulness, designers and developers alike have have wished for more out of the language since its inception over twelve years ago with the CSS Level 1 Recommendation. Today, we&#8217;re going to review some ways to <strong>Supercharge Your CSS With PHP Under The Hood</strong>.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/416_superCharge/images/supercharge.png" border="0" alt="Supercharging XHTML/CSS" /></div>
<p><em>Note: I am not going to be arguing for or against the concept of CSS Variable and/or CSS Constants. This article is written with the assumption that you will <a href="#cssvariablecontroversy">make an informed decision</a> regarding these once presented with what it can do. This article teaches how to set them up and use them, but does not address the controversy in full.</em></p>
<h3>Setting Things Up</h3>
<p>Before the supercharging begins, we have to ensure that you have the proper requirements for doing so. We are going to go over two methods of making your CSS work with PHP, one that is short and sweet, and one that is a bit more elegant and less noticeable to the user. Both of these have the same basic requirement of a server running PHP. The more elegant version requires a bit more:</p>
<ol>
<li>Apache (running PHP, obviously)</li>
<li>An editable .htaccess file</li>
</ol>
<h4>Setting Up the Simple Method</h4>
<p>Web browsers are not that picky about file extensions when dealing with the HTML link tag. What they are picky about is the header data that it receives for that file. What that means is that you can link a *.php file with the proper header data in the place of a *.css file, and the browser will interpret the result just like standard CSS. To do so, add the PHP header that tells Apache to output the file as CSS:</p>
<pre name="code" class="php">
&lt;?php header("Content-type: text/css; charset: UTF-8"); ?&gt;
</pre>
<p>Then, just link to the PHP file like you normally would:</p>
<pre name="code" class="html">
&lt;link rel="stylesheet" href="css/supercharged.php" media="screen"&gt;
</pre>
<p>Now that you have done this, you can&#8211;in theory&#8211;skip to the next section of the tutorial dealing with CSS variables and constants, if you would like; however, anyone who views your source is going to see that you have a PHP file where a CSS file should be. Additionally, just because the browser will interpret the result properly does not mean that it will necessarily do other things like caching the file in the browser. To fix this, we move on to the slightly more elegant version.</p>
<h4>Setting Up the Elegant Method</h4>
<p>Apache comes with a large number of .htaccess tricks. This is one of them. We are going to tell Apache to interpret all CSS files in a certain folder as PHP files, and the web browser (and your users) will, generally speaking, not know that you are doing so. First thing to do is to put the header data in your CSS file, just like the Simple Method:</p>
<pre name="code" class="php">
&lt;?php header("Content-type: text/css; charset: UTF-8"); ?&gt;
</pre>
<p>Then, instead of saving the CSS file as a *.php file, you save it as a *.css file, and you place it in a folder for CSS (in our example, ~/css/). Once you have done this, create a *.htaccess file in that folder and add the following:</p>
<pre name="code" class="htaccess">
AddHandler application/x-httpd-php .css
</pre>
<p>This snippet tells Apache to interpret all CSS files in the folder with the *.htaccess file with the PHP script handler. If you do not have the ability to add this to a single folder or if you need this to be serverwide, you can also add this to the <em>httpd.conf</em> server configuration file for Apache. To do so, you would want to add the previous snippet right below the group of <strong>AddType</strong> and <strong>AddHandler</strong> declarations (like these from one of my servers):</p>
<pre name="code" class="html">
AddType application/x-httpd-php .php .php3 .php4 .php5
AddType application/x-httpd-php-source .phps
AddHandler cgi-script .cgi .pl
</pre>
<p>Just remember that if you do add this to your <em>httpd.conf</em> server configuration file that <strong>EVERY</strong> *.css file on the server now must have the PHP header for text/css prepended to it. This is why my recommendation is to add it via .htaccess</p>
<h3>Start the Engine with CSS Variables</h3>
<p>From the <a href="http://www.websiteoptimization.com/speed/tweak/average-top-100-weblog/">Average Top 100 Weblog Performance Survey</a>:</p>
<blockquote><p>We ran a test on the top 100 blogs for external CSS files and total size. The average top 100 blog uses 4 external CSS files (@imports included) with an average total file size of 43.1K (uncompressed). The number of external CSS files ranged from 1 to 18. The total size of CSS ranged from to 0.2K to a whopping 307K. Note that this analysis does not include internal CSS within (X)HTML files. It does include nested CSS files called with @import directives.</p></blockquote>
<p>That is a lot of CSS. Why is this? A lot of times it is because the CSS is being delivered uncompressed and not optimized. The more likely suspect is CSS bloat and poorly maintained code. One popular option to improving code maintainability is to implement CSS Variables through PHP.</p>
<p>What this means is that instead of having CSS like this (yes, this would produce an aberration of design, but it&#8217;s good at illustrating the point):</p>
<pre name="code" class="css">
body {
 color: #000;
 background: #fff;
 font-size: 10px;
}
div#content {
 background: #ccc;
 font-size: 1.1em;
}
div#sidebar {
 color: #fff;
 background: #000;
 font-size: 1.0em;
}
div#footer {
 color: #555;
 background: #ccc;
}
</pre>
<p>You could have CSS like this:</p>
<pre name="code" class="php">
&lt;?php
$primaryTextColor = '#000';
$secondaryTextColor = '#fff';
$tertiaryTextColor = '#555';
$primaryBGColor = '#fff';
$secondaryBGColor = '#ccc';
$tertiaryBGColor = '#000';
$primaryTextSize = '10'; //pixels
?&gt;
body {
 color: &lt;?=$primaryTextColor?&gt;;
 background: &lt;?=$primaryBGColor?&gt;;
 font-size: &lt;?=$primaryTextSize?&gt;px;
}
div#content {
 background: &lt;?=$secondaryBGColor?&gt;;
 font-size: &lt;? echo 1.1*$primaryTextSize ?&gt;px;
}
div#sidebar {
 color:  &lt;?=$secondaryTextColor?&gt;;
 background: &lt;?=$tertiaryBGColor?&gt;;
 font-size: &lt;?=$primaryTextSize;?&gt;px;
}
div#footer {
 color: &lt;?=$tertiaryTextColor?&gt;;
 background: &lt;?=$secondaryBGColor?&gt;;
}
</pre>
<blockquote><p>Note that the long variable names is for illustration purposes only. Obviously, these variables can be as long as or as short as you like, and shorter variables make for smaller file sizes.</p>
</blockquote>
<p>In the example above, we have used basic variables to set up a monochrome color scheme that could then be used throughout the website in other styles. These variables could easily have been interchanged with $color01, $color02, $color03, etc to produce similar effects. Often, designers and front-end web developers get asked by clients &#8220;Hey, can you make all of the text a little darker?&#8221; or &#8220;Can you make all of the text just a little bigger?&#8221; While using variables like this will not always be the best solution, it often would reduce the maintenance time when using many templating systems and blogging platforms (WordPress, Moveable Type, Expression Engine, etc) or corporate CMSes (Drupal, Joomla, Bitrix, etc).</p>
<p>An alternative method of storing the variables is to store the data in associate arrays (which is my preferred method), which produces code more like the following:</p>
<pre name="code" class="php">
&lt;?php
$defaultCSS = array(
 'color01' => '#000',
 'color02' => '#fff',
 'color03' => '#ccc',
 'color04' => '#555',
 'baseTextSize' => '10'
);
?&gt;
body {
 color: &lt;?=$defaultCSS['color01']?&gt;;
 background: &lt;?=$defaultCSS['color02']?&gt;;
 font-size: &lt;?=$defaultCSS['baseTextSize']?&gt;px;
}
div#content {
 background: &lt;?=$defaultCSS['color03']?&gt;;
 font-size: &lt;? echo 1.1*$defaultCSS['baseTextSize']; ?&gt;px;
}
div#sidebar {
 color:  &lt;?=$defaultCSS['color02']?&gt;;
 background: &lt;?=$defaultCSS['color01']?&gt;;
 font-size: &lt;?=$defaultCSS['baseTextSize'];?&gt;px;
}
div#footer {
 color: &lt;?=$defaultCSS['color04']?&gt;;
 background: &lt;?=$defaultCSS['color03']?&gt;;
}
</pre>
<h3>Calculations in CSS</h3>
<p>Once you have set things up for using PHP with your CSS, you can then do some neat things like calculations. Let&#8217;s assume that you want to set up a system in you provide a bunch of DIVs on screen, each with a different type of element inside. Each element type (i.e. img, p, blockquote, etc) has a unique height and width controlled via CSS, and you want the amount of margin to be based off these values like so:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/416_superCharge/images/imgmeasures.png" border="0" alt="Diagram of Padding / Element Measurements" /></div>
<p>In this scenario, you want to set up a standardized grid that contains three different types of elements (img, p, and blockquote) encapsulated in two different containers (div and li). Every DIV has to be 550px wide and 250px tall, every LI has to be 600px wide and 300px tall, and each of the element types has a different height and width. The positioning of the elements on the inside must be dead center. Over time, the heights and widths of the different DIVs/LIs and elements will likely need to be changed. You could manual enter the amount of margin for each of the different elements and/or use extra class information on the container DIVs to add the appropriate amount of padding, but this is not that useful for quick changes, like those wanted by someone who is prototyping in the browser or who has 200 of these different elements for which they would have to modify data.</p>
<h4>Step 1 &#8211; The Structure</h4>
<p>First, we set up the XHTML content that we are going to style like so:</p>
<pre name="code" class="html">
&lt;div&gt;&lt;p&gt;Lorem ipsum dolor sit amet tellus.&lt;/p&gt;&lt;/div&gt;
&lt;div&gt;&lt;blockquote&gt;Etiam quis nulla pretium et.&lt;/blockquote&gt;&lt;/div&gt;
&lt;div&gt;&lt;img src="images/inset.png" alt="Inset Image" /&gt;&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Lorem ipsum dolor sit amet tellus.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;blockquote&gt;Etiam quis nulla pretium et.&lt;/blockquote&gt;&lt;/li&gt;
&lt;li&gt;&lt;img src="images/inset.png" alt="Inset Image" /&gt;&lt;/li&gt;
&lt;/ul&gt;
</pre>
<h4>Step 2 &#8211; The PHP Header and Variable Declarations</h4>
<p>Next, we set up the PHP/CSS file that we are going to use to style the XHTML. This is where we declare the standard sizes of the different elements for use throughout the page.</p>
<pre name="code" class="php">
&lt;?php
header("Content-type: text/css; charset: UTF-8");

$divData = array(
 'width' => '550',
 'height' => '250',
);
$liData = array(
 'width' => '600',
 'height' => '300',
);
$blockquoteData = array(
 'width' => '440',
 'height' => '100'
);
$imgData = array(
 'width' => '450',
 'height' => '150'
);
$pData = array(
 'width' => '480',
 'height' => '130'
);
?&gt;
</pre>
<h4>Step 3 &#8211; The CSS with Variables and PHP Calculations</h4>
<p>Next, we continue the PHP file from Step 2 and utilize the variables that we set in calculations. Additionally, we set the calculated MarginX and MarginY values of the different elements to reduce the number of calculations necessary.</p>
<pre name="code" class="php">
div {
 width: &lt;?=$divData['width']?&gt;px;
 height: &lt;?=$divData['height']?&gt;px;
}
li {
 width: &lt;?=$liData['width']?&gt;px;
 height: &lt;?=$liData['height']?&gt;px;
}
div blockquote {
 width: &lt;?=$blockquoteData['width']?&gt;px;
 height: &lt;?=$blockquoteData['height']?&gt;px;
 &lt;?
  $blockquoteData['divMarginX'] = $divData['width']-$blockquoteData['width'];
  $blockquoteData['divMarginY'] = $divData['height']-$blockquoteData['height'];
 ?&gt;
 margin: &lt;? echo blockquoteData['divMarginY']/2; ?&gt;px &lt;? echo blockquoteData['divMarginX']/2; ?&gt;px;
}
div img {
 width: &lt;?=$imgData['width']?&gt;px;
 height: &lt;?=$imgData['height']?&gt;px;
 &lt;?
  $imgData['divMarginX'] = $divData['width']-$imgData['width'];
  $imgData['divMarginY'] = $divData['height']-$imgData['height'];
 ?&gt;
 margin: &lt;? echo imgData['divMarginY']/2; ?&gt;px &lt;? echo imgData['divMarginX']/2; ?&gt;px;
}
div p {
 width: &lt;?=$pData['width']?&gt;px;
 height: &lt;?=$pData['height']?&gt;px;
 &lt;?
  $pData['divMarginX'] = $divData['width']-$pData['width'];
  $pData['divMarginY'] = $divData['height']-$pData['height'];
 ?&gt;
 margin: &lt;? echo pData['divMarginY']/2; ?&gt;px &lt;? echo pData['divMarginX']/2; ?&gt;px;
}
li blockquote {
 width: &lt;?=$blockquoteData['width']?&gt;px;
 height: &lt;?=$blockquoteData['height']?&gt;px;
 &lt;?
  $blockquoteData['liMarginX'] = $liData['width']-$blockquoteData['width'];
  $blockquoteData['liMarginY'] = $liData['height']-$blockquoteData['height'];
 ?&gt;
 margin: &lt;? echo blockquoteData['liMarginY']/2; ?&gt;px &lt;? echo blockquoteData['liMarginX']/2; ?&gt;px;
}
li img {
 width: &lt;?=$imgData['width']?&gt;px;
 height: &lt;?=$imgData['height']?&gt;px;
 &lt;?
  $imgData['liMarginX'] = $liData['width']-$imgData['width'];
  $imgData['liMarginY'] = $liData['height']-$imgData['height'];
 ?&gt;
 margin: &lt;? echo imgData['liMarginY']/2; ?&gt;px &lt;? echo imgData['liMarginX']/2; ?&gt;px;
}
li p {
 width: &lt;?=$pData['width']?&gt;px;
 height: &lt;?=$pData['height']?&gt;px;
 &lt;?
  $pData['liMarginX'] = $liData['width']-$pData['width'];
  $pData['liMarginY'] = $liData['height']-$pData['height'];
 ?&gt;
 margin: &lt;? echo pData['liMarginY']/2; ?&gt;px &lt;? echo pData['liMarginX']/2; ?&gt;px;
}
</pre>
<p>What this allows us to do now is to change the size of elements once at the top of the file and not recalculate 12 margin values (24 if the margin values were asymmetric). Understand that I am not suggesting this will be used in every one of your projects going forward, but this kind of technique has definite advantages over the standard &#8220;static&#8221; CSS method.</p>
<h3>Shrink that CSS</h3>
<p>As mentioned earlier, CSS can get pretty big. One thing that you can do to reduce CSS size is to automatically gzipping your CSS files. To do this, you have two options on how to do so: straight from Apache using <a href="http://httpd.apache.org/docs/2.0/mod/mod_deflate.html">mod_gzip / mod_deflate</a> or use PHP&#8217;s built-in compression methods, which we&#8217;ll do here.</p>
<h4>Step One &#8211; Set Up The Gzipping Snippet</h4>
<p>Inside of our CSS file, we already have a snippet of PHP that sets up the header:</p>
<pre name="code" class="php">
&lt;?php header("Content-type: text/css; charset: UTF-8"); ?&gt;
</pre>
<p>All we have to do now, is add a single line of code setting an output buffer to use <a href="http://es.php.net/ob_gzhandler">ob_gzhandler</a> before the header declaration like so:</p>
<pre name="code" class="php">
&lt;?php
ob_start("ob_gzhandler");
header("Content-type: text/css; charset: UTF-8");
?&gt;
</pre>
<p>It should be noted that there are other ways of doing gzip compression and they all have their benefits and shortcomings. My preferred method is using mod_deflate as mentioned earlier, but not all designers and developers have that option.</p>
<h3>If($usingPHP==TRUE) { return &#8216;Happiness&#8217;; }</h3>
<p>Adding programming logic to a style sheet language is nothing new. Many websites determine what stylesheets they use based on URL, login status, or even the date. Here&#8217;s a simple example that can be applied easily to blogs and e-commerce sites (amongst others). Let&#8217;s assume that you have a h1 tag that is replaced using the Phark image replacement method described by the following CSS:</p>
<pre name="code" class="css">
h1 {
 width: 300px;
 height: 80px;
 text-indent: -9999px;
 background: url(images/logo.png) no-repeat;
}
</pre>
<p>By adding a little PHP in the mix to determine the date when the CSS is loaded, you can then specify a different image for a holiday like Google often does with its Google Doodles (although they use a different technology solution to do so):</p>
<pre name="code" class="php">
&lt;?php
 $month = date('m');
 $day = date('d');
 if($month=='12' &#038;&#038; $day=='25') {
 	$logoSrc = 'images/holidayLogo.png';
 } else {
 	$logoSrc = 'images/logo.png';
 }
?&gt;
h1 {
 width: 300px;
 height: 80px;
 text-indent: -9999px;
 background: url(&lt;?=$logoSrc?&gt;) no-repeat;
}
</pre>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/416_superCharge/images/holidaylogo.png" border="0" alt="Normal Logo becomes Holiday Logo" /></div>
<p>This is just a super simple example. Your CSS is just waiting to be amped up by PHP. What you do with it can vary from person to person. One of my personal uses is to use it as a way of obscuring and embedding @font-face files using data URI strings and checking the referer requesting the file similar to parts of the technology that <a href="http://typekit.com">Typekit</a> uses:</p>
<pre name="code" class="php">
&lt;?php
// This function grabs the file and converts it to a URI string
function data_url($file, $mime) {
 $contents = file_get_contents($file);
 $base64 = base64_encode($contents);
 return ('data:' . $mime . ';base64,' . $base64);
}

$checkReferer = $_SERVER['HTTP_REFERER'];
$checkMatch = preg_match('/yourdomain\.com/',$checkReferer);
if($checkMatch) {
?&gt;
 @font-face {
   font-family: FontName;
   src: local("FontName"), url(&lt;?php echo data_url('FontFileName.otf','font/otf'); ?&gt;) format("opentype");
 }
&lt;?php
} else {
 /* This @font-face asset is unavailable */
}
?&gt;
</pre>
<h3 id="cssvariablecontroversy">CSS Variable Controversy</h3>
<p>Using variables in CSS, no matter the pros and cons has been a controversial issue for years. Like I said at the beginning of this article, I am not going to argue for or against the concept of CSS Variables or CSS Constants. Some very respected designer and developers have <a href="http://meiert.com/en/blog/20090401/why-css-needs-no-variables/">argued</a> <a href="http://www.w3.org/People/Bos/CSS-variables">against</a> <a href="http://maymay.net/blog/2008/12/14/why-css-needs-delegation-capabilities-and-not-variables/">it</a>, while others have <a href="http://alex.dojotoolkit.org/2008/08/css-variables-are-the-future/">argued</a> <a href="http://www.broken-links.com/2008/04/01/future-css-variables-and-calculations/">for</a> <a href="http://disruptive-innovations.com/zoo/cssvariables/">it</a>. I hope, for the sake of a better web, that an effective CSS-only solution happens sooner than later. In the meantime, those of us who support CSS variables and constants can rely on our server-side languages while those who do not support them will simply continue on as normal.</p>
<h3>What Ideas Can You Come up With?</h3>
<p>I&#8217;m always on the lookout for new and innovative ways to supercharge my CSS with PHP. What are some of your favorite use-case scenarios for mixing CSS with PHP?</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/php/supercharge-your-css-with-php-under-the-hood/feed/</wfw:commentRss>
		<slash:comments>64</slash:comments>
		</item>
		<item>
		<title>30+ PHP Best Practices for Beginners &#8211; Basix</title>
		<link>http://net.tutsplus.com/tutorials/php/30-php-best-practices-for-beginners/</link>
		<comments>http://net.tutsplus.com/tutorials/php/30-php-best-practices-for-beginners/#comments</comments>
		<pubDate>Thu, 13 Aug 2009 15:28:09 +0000</pubDate>
		<dc:creator>Glen Stansberry</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[basix]]></category>
		<category><![CDATA[best practices]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=6194</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/407_php/200x200.png" alt="30 PHP Best Practices for Beginners" />]]></description>
			<content:encoded><![CDATA[<p>PHP is <em>the</em> most widely-used language for programming on the web. Here are thirty best practices for beginners wanting to gain a firmer grasp of the fundamentals.
</p>
<p><strong>Editor&#8217;s Note:</strong> The &#8220;Best Practices&#8221; <a href="http://net.tutsplus.com/tutorials/javascript-ajax/24-javascript-best-practices-for-beginners/">series</a> has been my <a href="http://net.tutsplus.com/tutorials/html-css-techniques/30-html-best-practices-for-beginners/">baby</a> for three <a href="http://net.tutsplus.com/articles/general/15-tips-to-speed-up-your-website-and-optimize-your-code/">articles</a> now. However, due to my focus on the <a href="http://net.tutsplus.com/videos/screencasts/codeigniter-from-scratch-day-4-newsletter-signup/">CI video series</a>, I&#8217;ve decided to hand off this next entry to Glen. Having said that, I&#8217;m not very good at keeping my mouth shut! I thought it might be fun to sporadically add a few rebuttals to his tips. I hope he doesn&#8217;t mind!<br />
<span id="more-6194"></span></p>
<h3>1. Befriend the PHP Manual</h3>
<p>If you&#8217;re new to PHP, then it&#8217;s time to get acquainted with the awesomeness that is the <a href="http://www.php.net/manual/en/index.php">PHP manual</a>. The PHP manual is incredibly thorough and has truly helpful comments following each article. Before asking questions or trying to figure out an issue on your own, save some time and just head straight to the manual. Odds are the answer to your question is already nestled in a helpful article at the PHP.net site.</p>
<h3>2. Turn on Error Reporting</h3>
<p><a href="http://www.php.net/manual/en/function.error-reporting.php">Error reporting in PHP</a> is very helpful. You&#8217;ll find bugs in your code that you might not have spotted earlier, as not all bugs keep the application from working. There are different levels of strictness in the reporting that you can use, but E_ALL will show you the most errors, critical and warnings alike.</p>
<p>Once you&#8217;ve gotten your application ready for production, you&#8217;ll want to turn off error reporting, or your visitors will see strange errors that they don&#8217;t understand.</p>
<h3>3. Try an IDE</h3>
<p>IDE&#8217;s (Integrated Development Environments) are helpful tools for any developer. While they&#8217;re not for everyone, an IDE definitely has its place. IDE&#8217;s provide tools like </p>
<ul>
<li>syntax highlighting</li>
<li>code completion</li>
<li>error warnings</li>
<li>refactoring (reworking)</li>
</ul>
<p>
And many other features. There are <a href="http://www.smashingmagazine.com/2009/02/11/the-big-php-ides-test-why-use-oneand-which-to-choose/">plenty of great IDEs</a> out there that support PHP.</p>
<div class="tutorial_image">
	<img src="http://nettuts.s3.amazonaws.com/407_php/3-IDE.png" alt="Try an IDE">
</div>
<h3>4. Try a PHP Framework</h3>
<p>You can learn a lot about PHP just by experimenting with PHP frameworks. Frameworks like <a href="http://cakephp.org">CakePHP</a> or <a href="http://codeigniter.com">CodeIgniter</a> allow you to quickly create PHP applications, without having to be an expert with PHP. In a sense, they&#8217;re almost like PHP training wheels that show you what a PHP application should look like, and show you valuable programming concepts (like separating the logic from the design, etc.).</p>
<blockquote><p><em>Rebuttal: I personally wouldn&#8217;t recommend that beginners use a framework. Learn the fundamentals first. <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </em></p>
</blockquote>
<h3>5. Learn the DRY Approach</h3>
<p>DRY stands for <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">Don&#8217;t Repeat Yourself</a>, and it&#8217;s a valuable programming concept, no matter what the language. DRY programming, as the name implies, is ensuring that you don&#8217;t write redundant code. Here&#8217;s an example from <a href="http://reinholdweber.com/php/php-programmers-evolution-scribble/">Reinhold Weber</a>:</p>
<div class="tutorial_image">
	<img src="http://nettuts.s3.amazonaws.com/407_php/DRY.png" alt="Learn the DRY approach" />
</div>
<p>This code&#8230;</p>
<pre name="code" class="php">$mysql = mysql_connect('localhost', 'reinhold', 'secret_hash');
mysql_select_db('wordpress') or die("cannot select DB");</pre>
<p>now with the DRY approach:</p>
<pre name="code" class="php">$db_host = 'localhost';
$db_user = 'reinhold';
$db_password = 'secret_hash';
$db_database = 'wordpress';

$mysql = mysql_connect($db_host, $db_user, $db_password);
mysql_select_db($db_database);</pre>
<p>You can read more about the DRY programming principle <a href="http://www.artima.com/intv/dry.html">here</a> and <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">here</a>.</p>
<h3>6. Indent Code and Use White Space for Readability</h3>
<p>If you don&#8217;t use indentations and white space in your code, the result looks like a Jackson Pollack painting. Ensure that your code is readable and easy to search because you&#8217;ll most definitely be making changes in the future. IDEs and advanced text editors can add indentation automatically.</p>
<h3>7. &#8220;Tier&#8221; your Code</h3>
<p>Tiering your applications is nothing more than separating the different components of the code into different parts. This allows you to easily change your code in the future. NETTUTS writer Jason Lengstorf has written an excellent article on <a href="http://net.tutsplus.com/tutorials/php/add-power-to-your-php-with-multi-tiered-applications/">how to tier your PHP applications</a> for easier maintenance.</p>
<h3>8. Always Use &lt;?php ?&gt;</h3>
<p>Often times programmers try to take shortcuts when declaring PHP. Here are a few common ones:</p>
<pre name="code" class="php">
&lt;?
    echo "Hello world";
?>

&lt;?="Hello world"; ?>

&lt;% echo "Hello world"; %>
</pre>
<p>
While these do save a few characters, all of these methods are depreciated and unofficial. Stick with the standard &lt;?php ?> as it will be guaranteed to be supported in all future versions.
</p>
<h3>9. Use Meaningful, Consistent Naming Conventions</h3>
<p>Naming this isn&#8217;t just for your own good. There&#8217;s nothing worse than trying to find your way through some other programmer&#8217;s nonsensical naming conventions. Help yourself <em>and</em> others by using names that make sense for your classes and functions.</p>
<h3>10. Comment, Comment, Comment</h3>
<p>Aside from using white space and indentations to separate the code, you&#8217;ll also want to use inline comments to annotate your code. You&#8217;ll thank yourself later when you&#8217;re needing to go back and find something in the code, or if you just can&#8217;t remember what a certain function did. It&#8217;s also useful for anyone else who needs to look over your code.</p>
<h3>11. Install MAMP/WAMP</h3>
<p>MySQL is the most popular type of database to use with PHP (though it&#8217;s not the only one). If you&#8217;re wanting to set up a local environment to develop and test your PHP applications on your computer, look into installing <a href="http://www.mamp.info/en/index.html">MAMP</a> (Mac) or <a href="http://www.wampserver.com/en/">WAMP</a> (Windows). Installing MySQL on your own computer can be a tedious process, and both of these software packages are drop-in installs of MySQL. Clean and simple.</p>
<div class="tutorial_image">
	<img src="http://nettuts.s3.amazonaws.com/407_php/mamp.png" alt="Install MAMP/WAMP" />
</div>
<h3>12. Give your Scripts Limits</h3>
<p>Putting a time limit on your PHP scripts is a very critical thing. There are times when your scripts will fail, and when they do, you&#8217;ll want to use the <a href="http://php.net/manual/en/function.set-time-limit.php">set_time_limit</a> function to avoid infinite loops and database connection timeouts. The set_time_limit puts a time limit on the maximum number of seconds a script will run (the default is 30). After that time period, a fatal error is thrown.</p>
<h3>13. Use Objects (or OOP)</h3>
<p>Object-oriented programming (OOP) uses objects to represent parts of the application. Not only is OOP a way to break your code into separate, logical sections, it also reduces code repetition and makes it much easier to modify in the future. If you&#8217;re wanting to learn more, DevArticles has a great write-up on <a href="http://www.devarticles.com/c/a/PHP/Object-Oriented-Programming-in-PHP/">object-oriented programming with PHP</a>.</p>
<h3>14. Know the Difference Between Single and Double Quotes</h3>
<p>It is more efficient to use <em>single</em> quotes in strings as the parser doesn&#8217;t have to sift through the code to look for escaped characters and other things that double quotes allow. Always try to use single quotes whenever possible.</p>
<blockquote>
<p><em>Rebuttal: Actually, that&#8217;s not necessarily true. Benchmark tests show that, when testing strings without variables, there are definite performance benefits to using <strong>double quotes</strong>. </em></p>
</blockquote>
<h3>15. Don&#8217;t Put phpinfo() in your Webroot</h3>
<p><a href="http://us2.php.net/phpinfo">Phpinfo</a> is a beautiful thing. By simply creating a PHP file that has</p>
<pre name="code" class="php">
	&lt;?php phpinfo(); ?>
</pre>
<p>and dropping it onto the sever somewhere, you can instantly learn everything about your server environment. However, a lot of beginners will place a file containing phpinfo() in the webroot of the server. This is a really insecure practice, and if prying eyes gain access, it could potentially spell doom for your server. Make sure phpinfo() is in a secure spot, and as an extra measure, delete it once you&#8217;re done.</p>
<div class="tutorial_image">
	<img src="http://nettuts.s3.amazonaws.com/407_php/phpinfo.png" alt="don't put phpinfo() in your web root" />
</div>
<h3>16. Never, Ever Trust Your Users</h3>
<p>If your application has places for user input, you should always assume that they&#8217;re going to try to input naughty code. (We&#8217;re not implying that your users are bad people. It&#8217;s just a good mindset.) A great way to keep your site hacker-free is to always initialize your variables to safeguard your site from <a href="http://ha.ckers.org/xss.html">XSS attacks</a>. PHP.net has an example of a <a href="http://talks.php.net/show/php-best-practices/19">properly secured form</a> with initialized variables:</p>
<pre name="code" class="php">
	&lt;?php
	if (correct_user($_POST['user'], $_POST['password']) {
	    $login = true;
	}

	if ($login) {
	    forward_to_secure_environment();
	}
	?>
</pre>
<h3>17. Store Passwords with Encryption</h3>
<p>Many PHP beginners often plunk sensitive data like passwords into the database without applying any encryption. Consider using <a href="http://us3.php.net/md5">MD5</a> to encrypt passwords before you put them into the database.</p>
<pre name="code" class="php">
echo md5('myPassword'); // renders - deb1536f480475f7d593219aa1afd74c
</pre>
<blockquote>
<p><em>Rebuttal: </em> Keep in mind, however, that MD5 hashes have long since been compromised. They&#8217;re absolutely more secure than not, but, with the use of an enormous &#8220;rainbow table,&#8221; hackers can cross reference your hash. To add even more security, consider adding a salt as well. A salt is basically an additional set of characters that you append to the user&#8217;s string.
</p></blockquote>
<h3>18. Use Database Visualization Design Tools</h3>
<p>If you&#8217;re finding it difficult to plan and modify databases for your PHP applications, you might look into using a database visualization tool. MySQL users can work with <a href="http://fabforce.net/dbdesigner4/">DBDesigner</a> and <a href="http://dev.mysql.com/workbench/">MySQL Workbench</a> to visually design your databases.</p>
<div class="tutorial_image">
	<img src="http://nettuts.s3.amazonaws.com/407_php/workbench.png" alt="use database visualization design tools" />
</div>
<h3>19. Use Output Buffering</h3>
<p>Output buffering is a simple way to greatly improve the performance and speed of your PHP script. Without output buffering, your script will show the HTML on the page as it&#8217;s processed &#8211; in pieces. Adding output buffering allows the PHP to store the HTML as a variable and send it to the browser in one chunk.</p>
<p>To enable output buffering, simply add ob_start() like so at the top of the file.</p>
<blockquote>
<p>
</em><br />
Rebuttal: Though not required, it&#8217;s generally considered to be a good practice to go ahead and append the &#8220;ob_end_flush();&#8221; function as well to the bottom of the document. P.S. Want to compress the HTML as well? Simply replace &#8220;ob_start();&#8221; with &#8220;ob_start(&#8217;ob_gzhandler&#8217;)&#8221;;
<p>Refer to this <a href="http://dev-tips.com/featured/output-buffering-for-web-developers-a-beginners-guide">Dev-tips article</a> for more information. </p>
<p></em>
</p>
</blockquote>
<pre name="code" class="php">
&lt;!DOCTYPE html>
&lt;?php ob_start('ob_gzhandler'); ?>
&lt;html lang="en">
&lt;head>
	&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	&lt;title>untitled&lt;/title>
&lt;/head>
&lt;body>

&lt;/body>
&lt;/html>
&lt;?php ob_end_flush(); ?>
</pre>
<h3>20. Protect your Script From SQL Injection</h3>
<p>If you don&#8217;t escape your characters used in SQL strings, your code is vulnerable to SQL injections. You can avoid this by either using the <a href="http://us3.php.net/mysql_real_escape_string">mysql_real_escape_string</a>, or by using prepared statements.</p>
<p>Here&#8217;s an example of mysql_real_escape_string in action:</p>
<pre name="code" class="php">$username = mysql_real_escape_string( $GET['username'] );</pre>
<p>and a prepared statement:</p>
<pre name="code" class="php">
	$id = $_GET['id'];
	$statement = $connection->prepare( "SELECT * FROM tbl_members WHERE id = ?" );
	$statement->bind_param( "i", $id );
	$statement->execute();
</pre>
<blockquote>
<p><em>By using prepared statements, we never embed the user&#8217;s inputted data directly into our query. Instead, we use the &#8220;bind_param&#8221; method to bind the values (and escaping) to the query. Much safer, and, notably, faster when executing multiple CRUD statements at once.</em></p>
</blockquote>
<p>Read more on <a href="http://net.tutsplus.com/tutorials/php/5-helpful-tips-for-creating-secure-php-applications/">creating secure PHP applications</a> at Nettuts.</p>
<h3>21. Try ORM</h3>
<p>If you&#8217;re writing object-oriented PHP, then you can use the nifty object relational mapping (ORM). ORM allows you to convert data between relational databases and object-oriented programming languages. In short: ORM allows you to work with databases the same way that you work with classes and objects in PHP.</p>
<p>There are plenty of ORM libraries for PHP like <a href="http://propel.phpdb.org/trac/">Propel</a>, and ORM is built into PHP frameworks like <a href="http://cakephp.org">CakePHP</a>. </p>
<h3>22. Cache Database-Driven Pages</h3>
<p>Caching database-driven PHP pages is an excellent idea to improve the load and performance of your script. It&#8217;s really not all that difficult to create and retrieve static files of content with the help of our good friend ob_start(). Here&#8217;s an example taken <a href="http://www.snipe.net/2009/03/quick-and-dirty-php-caching/">from Snipe.net</a>:</p>
<pre name="code" class="php">
	// TOP of your script
	$cachefile = 'cache/'.basename($_SERVER['SCRIPT_URI']);
	$cachetime = 120 * 60; // 2 hours
	// Serve from the cache if it is younger than $cachetime
	if (file_exists($cachefile) &#038;&#038; (time() - $cachetime &lt; filemtime($cachefile))) {
	include($cachefile);
	echo "&lt;!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." -->";
	exit;
	}
	ob_start(); // start the output buffer
	// Your normal PHP script and HTML content here
	// BOTTOM of your script
	$fp = fopen($cachefile, 'w'); // open the cache file for writing
	fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file
	fclose($fp); // close the file
	ob_end_flush(); // Send the output to the browser
</pre>
<p>This bit of code will use a cached version of a page that is less than 2 hours old.</p>
<h3>23. Use a Caching System</h3>
<p>If you&#8217;re wanting a more robust caching system, there are a few caching scripts for PHP that might be more complete than the above example.</p>
<ul>
<li><a href="http://www.danga.com/memcached/">Memcached</a></li>
<li><a href="http://us.php.net/manual/en/intro.apc.php">APC</a></li>
<li><a href="http://xcache.lighttpd.net/">XCache</a></li>
<li><a href="http://files.zend.com/help/Zend-Platform/zend_cache_api.htm">Zend Cache</a></li>
<li><a href="http://www.eaccelerator.net/">eAccelerator</a></li>
</ul>
<div class="tutorial_image">
	<img src="http://nettuts.s3.amazonaws.com/407_php/memcached.png" alt="use a caching system" />
</div>
<h3>24. Validate Cookie Data</h3>
<p>Cookie data, like any data passed on the Web, can be harmful. You can validate cookie data with either the <a href="http://us3.php.net/manual/en/function.htmlspecialchars.php">htmlspecialchars()</a> or <a href="http://us3.php.net/mysql_real_escape_string">mysql_real_escape_string()</a>.</p>
<h3>25. Use Static File Caching Systems</h3>
<p>Aside from using database caching systems like Memcached, you might also want to try a templating system to increase performance in your PHP applications. <a href="http://www.smarty.net/">Smarty</a> is a robust templating system has caching built into it.</p>
<h3>26. Profile your Code</h3>
<p>Profiling your code with a tool like <a href="http://xdebug.org/">xdebug</a> can help you to quickly spot bottlenecks and other potential problems in your PHP code. Some IDEs like <a href="http://netbeans.org">Netbeans</a> have PHP profiling capabilities as well.</p>
<h3>27. Code to a Standard</h3>
<p>Once you&#8217;ve gotten the ropes of PHP down, you can start learning about coding to a standard. There are differences between standards out there (say <a href="http://framework.zend.com/manual/en/coding-standard.html">Zend</a> and <a href="http://pear.php.net/manual/en/standards.php">Pear</a>), and finding one and sticking with it will help with the consistency of your coding in the long run.</p>
<h3>28. Keep Functions Outside of Loops</h3>
<p>You take a hit of performance when you include functions inside of loops. The larger the loop that you have, the longer the execution time will take. Take the extra time and line of code and place the function outside of the loop.</p>
<blockquote>
<p><em><br />
Editor&#8217;s Note: Think of it this way. Try to remove as many operations from the loop as possible. Do you really need to create that variable for every iteration of the loop? Do you really need to create the function each time? Of course not. <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
</em></p>
</blockquote>
<h3>29. Don&#8217;t Copy Extra Variables</h3>
<p>Some people like to try and make their code more appealing by copying predefined variables to smaller-named variables. This is redundant and could potentially double the memory of your script. Google Code has bad and good examples of variable usage:</p>
<p>Bad</p>
<pre name="code" class="php">
	$description = strip_tags($_POST['description']);
	echo $description;
</pre>
<p>Good</p>
<pre name="code" class="php">
	echo strip_tags($_POST['description']);
</pre>
<blockquote>
<p>
<em><br />
Rebuttal: In reference to the comment about &#8220;doubling the memory,&#8221; this actually is a common misconception. PHP implements &#8220;copy-on-write&#8221; memory management. This basically means that you can assign a value to as many variables as you like without having to worry about the data actually <em>being</em> copied. While it&#8217;s arguable that the &#8220;Good&#8221; example exemplified above might make for cleaner code, I highly doubt that it&#8217;s any quicker.<br />
</em>
</p>
</blockquote>
<h3>30. Upgrade to the Latest Version of PHP</h3>
<p>While it seems like a common sense thing, many people don&#8217;t upgrade PHP as often as they should. There are lots of performance increases between PHP 4 and PHP 5. Check your server to make sure you&#8217;re up to date.</p>
<h3>31. Reduce the Number of Database Queries</h3>
<p>Any way that you can cut back on the number of database queries, the better your PHP script will perform. There are tools like <a href="http://en.wikipedia.org/wiki/Strace">Stace</a> (Unix) and <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx">Process Explorer</a> (Windows) that allow you to find redundant processes and how you might combine them.</p>
<div class="tutorial_image">
	<img src="http://nettuts.s3.amazonaws.com/407_php/strace.png" alt="Reduce the number of database queries">
</div>
<h3>32. Don&#8217;t be Afraid to Ask for Help</h3>
<p>It&#8217;s only human nature to want to hide the fact that we don&#8217;t know much about a certain topic. Nobody likes being a n00b! But how are we going to learn without asking? Feel free to use forums, IRC, <a href="http://www.stackoverflow.com">StackOverflow</a> to ask more seasoned PHP developers questions. The PHP website has a page on <a href="http://www.php.net/support.php">getting PHP help</a>.</p>
<p>
Have any rebuttals of your own? I&#8217;m sure you do! Let&#8217;s start the debate.
</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="NETTUTS RSS Feed">NETTUTS RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/php/30-php-best-practices-for-beginners/feed/</wfw:commentRss>
		<slash:comments>111</slash:comments>
		</item>
	</channel>
</rss>
<!--
This site's performance optimized by W3 Total Cache:

W3 Total Cache improves the user experience of your blog by caching
frequent operations, reducing the weight of various files and providing
transparent content delivery network integration.

Learn more about our WordPress Plugins: http://www.w3-edge.com/wordpress-plugins/

Page Caching using memcached
Database Caching 10/25 queries in 0.011 seconds using memcached
Content Delivery Network via 

Served from: psdtutsplus.com @ 2009-11-21 11:24:46 -->