<?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>Yavor Atanasov</title>
	<atom:link href="http://yavkata.co.uk/weblog/feed/" rel="self" type="application/rss+xml" />
	<link>http://yavkata.co.uk/weblog</link>
	<description>Bits and pieces from the Web</description>
	<lastBuildDate>Sat, 30 Mar 2013 00:22:41 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.1</generator>
		<item>
		<title>Code snippet: JavaScript &#8211; defining a local undefined</title>
		<link>http://yavkata.co.uk/weblog/javascript/code-snippet-javascript-defining-a-local-undefined/</link>
		<comments>http://yavkata.co.uk/weblog/javascript/code-snippet-javascript-defining-a-local-undefined/#comments</comments>
		<pubDate>Thu, 05 Apr 2012 14:13:53 +0000</pubDate>
		<dc:creator>Yavor Atanasov</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[snipetts]]></category>
		<category><![CDATA[code snippet]]></category>
		<category><![CDATA[undefined]]></category>

		<guid isPermaLink="false">http://yavkata.co.uk/weblog/?p=633</guid>
		<description><![CDATA[Although already introduced features of ECMAScript5 fix this, the global property undefined in older versions of JavaScript is writable just like any other property. This means someone can override it which can cause trouble in a shared environment where everyone assumes its value. undefined = "not undefined anymore"; (function(arg1, arg2, undefined){ // undefined is undefined [...]]]></description>
			<content:encoded><![CDATA[<p>Although <a href="https://developer.mozilla.org/en/JavaScript/New_in_JavaScript/1.8.5">already introduced features of ECMAScript5</a> fix this, the global property <span class="code">undefined</span> in older versions of JavaScript is <strong>writable</strong> just like any other property. This means someone can override it which can cause trouble in a shared environment where everyone assumes its value.</p>
<pre class="prettyprint">
<code class="prettyprint">undefined = "not undefined anymore";
(function(arg1, arg2, undefined){

    // undefined is undefined in here

})(value1, value2);
</code>
</pre>
<p>This creates a locally scoped variable <span class="code">undefined</span> that has the value of <span class="code">undefined</span> (more on the type, value and variable <span class="code">undefined</span> <a href="http://javascriptweblog.wordpress.com/2010/08/16/understanding-undefined-and-preventing-referenceerrors/" title="Understanding JavaScript’s undefined">here</a>). This way your code does not rely on the &#8220;fragile&#8221; global <span class="code">undefined</span> and is more robust.<br />
More info:</p>
<ul>
<li><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined" title="Undefined - Mozilla Developer Network">Undefined &#8211; Mozilla Developer Network</a></li>
<li><a href="https://developer.mozilla.org/en/JavaScript/New_in_JavaScript/1.8.5" title="New in JavaScript 1.8.5">New in JavaScript 1.8.5</a></li>
<li><a href="http://javascriptweblog.wordpress.com/2010/08/16/understanding-undefined-and-preventing-referenceerrors/" title="Understanding JavaScript’s ‘undefined’">Understanding JavaScript&#8217;s &#8216;undefined&#8217;</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://yavkata.co.uk/weblog/javascript/code-snippet-javascript-defining-a-local-undefined/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code snippet: Python &#8211; Get value from a dictionary without handling exceptions</title>
		<link>http://yavkata.co.uk/weblog/snipetts/code-snippet-python-get-value-from-a-dictionary-without-handling-exceptions/</link>
		<comments>http://yavkata.co.uk/weblog/snipetts/code-snippet-python-get-value-from-a-dictionary-without-handling-exceptions/#comments</comments>
		<pubDate>Wed, 04 Apr 2012 15:33:59 +0000</pubDate>
		<dc:creator>Yavor Atanasov</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[snipetts]]></category>
		<category><![CDATA[code snippet]]></category>
		<category><![CDATA[dictionary]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://yavkata.co.uk/weblog/?p=612</guid>
		<description><![CDATA[The more verbose way of getting the value from a key in a dictionary in Python involves checking if the key exists first and then reading the value. Otherwise an exception would be raised. Like so: dict = {'key':'value'} if dict.has_key('key'): print dict['key'] else: print 'no such key' The .get() method will do all that [...]]]></description>
			<content:encoded><![CDATA[<p>The more verbose way of getting the value from a key in a dictionary in Python involves checking if the key exists first and then reading the value. Otherwise an exception would be raised.<br />
Like so:</p>
<pre class="prettyprint"><code class="prettyprint">dict = {'key':'value'}
if dict.has_key('key'):
    print dict['key']
else:
    print 'no such key'
</code></pre>
<p>The <span class="code">.get()</span> method will do all that for you:</p>
<pre class="prettyprint"><code class="prettyprint">print dict.get('key', 'no such key') </code></pre>
<p>This is far more compact and expressive. Ref: <a title="Python Mapping Types - dict" href="http://docs.python.org/release/2.5.2/lib/typesmapping.html">Python Mapping Types &#8211; dictionary</a></p>
]]></content:encoded>
			<wfw:commentRss>http://yavkata.co.uk/weblog/snipetts/code-snippet-python-get-value-from-a-dictionary-without-handling-exceptions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Some New Ubuntu 10.10 Wallpapers</title>
		<link>http://yavkata.co.uk/weblog/graphics-and-wallpapers/some-new-ubuntu-10-10-wallpapers/</link>
		<comments>http://yavkata.co.uk/weblog/graphics-and-wallpapers/some-new-ubuntu-10-10-wallpapers/#comments</comments>
		<pubDate>Mon, 25 Oct 2010 01:07:42 +0000</pubDate>
		<dc:creator>Yavor Atanasov</dc:creator>
				<category><![CDATA[Graphics and wallpapers]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Ubuntu]]></category>
		<category><![CDATA[wallpapers]]></category>

		<guid isPermaLink="false">http://yavkata.co.uk/weblog/?p=545</guid>
		<description><![CDATA[Earlier this month (on 10/10/10 in fact) Canonical added a brand new member to the mighty Ubuntu family &#8211; 10.10 Maverick Meerkat. If you still have not switched to it, I strongly encourage you to do it There are some great improvements and added features. And in case you have already switched, and you are [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-552" title="ubuntu_10.10_wallpapers" src="http://yavkata.co.uk/weblog/wp-content/uploads/ubuntu_10.10_wallpapers.jpg" alt="ubuntu_10.10_wallpapers" width="200" height="113" /></p>
<p>Earlier this month (on 10/10/10 in fact) Canonical added a brand new member to the mighty Ubuntu family &#8211; <a href="http://www.ubuntu.com/" title="Ubuntu official website">10.10 Maverick Meerkat</a>. If you still have not switched to it, I strongly encourage you to do it There are some great improvements and added features. And in case you have already switched, and you are just looking for some new wallpapers to bring some Ubuntu harmony to your desktop, well, you&#8217;ve stumbled upon the right URI! Here is a small, but very clean and beautiful collection of fresh desktop eye candy. The first 5 are kindly created by <a title="jbaer's deviantART page" href="http://jbaer.deviantart.com/">jbaer</a>.<span id="more-545"></span></p>
<h2>Maverick Beginning</h2>
<p><a title="Get Maverick Beginning wallpaper" href="http://jbaer.deviantart.com/art/Maverick-Beginning-178202652"><img class="alignnone size-medium wp-image-548" src="http://yavkata.co.uk/weblog/wp-content/uploads/ubuntu_thumbs/maverick_beginning_by_jbaer-615.jpg" alt="maverick_beginning_by_jbaer" width="615" height="384" /></a></p>
<h2>Maverick Blush</h2>
<p><a title="Get Maverick Blush wallpaper" href="http://jbaer.deviantart.com/gallery/#/d2xk6gh"><img class="alignnone size-medium wp-image-548" src="http://yavkata.co.uk/weblog/wp-content/uploads/ubuntu_thumbs/maverick_blush_by_jbaer-615.jpg" alt="maverick_blush_by_jbaer" width="615" height="384" /></a></p>
<h2>Maverick Dunes</h2>
<p><a title="Get Maverick Dunes wallpaper" href="http://jbaer.deviantart.com/gallery/#/d2wkgg1"><img class="alignnone size-medium wp-image-548" src="http://yavkata.co.uk/weblog/wp-content/uploads/ubuntu_thumbs/Maverick_Dunes_by_jbaer-615.jpg" alt="maverick_beginning_by_jbaer" width="615" height="384" /></a></p>
<h2>Maverick Metro</h2>
<p><a title="Get Maverick Metro wallpaper" href="http://jbaer.deviantart.com/gallery/#/d2yjdbv"><img class="alignnone size-medium wp-image-548" src="http://yavkata.co.uk/weblog/wp-content/uploads/ubuntu_thumbs/maverick_metro_by_jbaer-615.jpg" alt="maverick_beginning_by_jbaer" width="615" height="384" /></a></p>
<h2>Maverick 10.10</h2>
<p><a title="Get Maverick 10.10 wallpaper" href="http://jbaer.deviantart.com/gallery/#/d2yd0r9"><img class="alignnone size-medium wp-image-548" src="http://yavkata.co.uk/weblog/wp-content/uploads/ubuntu_thumbs/maverick_10_10_by_jbaer-615.jpg" alt="maverick_beginning_by_jbaer" width="615" height="384" /></a></p>
<h2>Ubuntu 3D name</h2>
<p><a title="Get Ubuntu 3D Name wallpaper" href="http://img513.imageshack.us/img513/3020/ubname4x3.png"><img class="alignnone size-medium wp-image-548" src="http://yavkata.co.uk/weblog/wp-content/uploads/ubuntu_thumbs/ubname4x3-615.jpg" alt="maverick_beginning_by_jbaer" width="615" height="384" /></a></p>
<h2>Ubuntu 3D Logo</h2>
<p><a title="Get Ubuntu 3D Logo wallpaper" href="http://img193.imageshack.us/img193/601/ub4x3.png"><img class="alignnone size-medium wp-image-548" src="http://yavkata.co.uk/weblog/wp-content/uploads/ubuntu_thumbs/ub4x3-615.jpg" alt="maverick_beginning_by_jbaer" width="615" height="384" /></a></p>
<h2>Ubuntu Dual-monitor default wallpaper</h2>
<p><a title="Get the dual-monitor default wallpaper" href="http://yavkata.co.uk/weblog/wp-content/uploads/ubuntu-10-10-maverick-meerkat-2560x1024.jpg"><img class="alignnone size-medium wp-image-548" src="http://yavkata.co.uk/weblog/wp-content/uploads/ubuntu_thumbs/ubuntu-10-10-maverick-meerkat-615.jpg" alt="maverick_beginning_by_jbaer" width="615" height="246" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://yavkata.co.uk/weblog/graphics-and-wallpapers/some-new-ubuntu-10-10-wallpapers/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The Pitfalls of CSS3</title>
		<link>http://yavkata.co.uk/weblog/xhtml_css/the-pitfalls-of-css3/</link>
		<comments>http://yavkata.co.uk/weblog/xhtml_css/the-pitfalls-of-css3/#comments</comments>
		<pubDate>Sat, 17 Jul 2010 22:19:25 +0000</pubDate>
		<dc:creator>Yavor Atanasov</dc:creator>
				<category><![CDATA[XHTML and CSS]]></category>
		<category><![CDATA[CSS3]]></category>
		<category><![CDATA[HTML5]]></category>

		<guid isPermaLink="false">http://yavkata.co.uk/weblog/?p=493</guid>
		<description><![CDATA[Everyone in the vast community of &#8220;web people&#8221; these days seems to be extremely excited about CSS3. Along with &#8220;HTML5&#8243;, &#8220;CSS3&#8243; has become one of the big buzz words on the web. Browser leaders like Firefox, Chrome, Safari and Opera started adoption of CSS3 before the final specification has been released. This has made it [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://yavkata.co.uk/weblog/wp-content/uploads/css3.jpg" alt="Pitfalls of CSS3" title="css3" width="200" height="113" class="alignleft size-full wp-image-530" /></p>
<p>Everyone in the vast community of &#8220;web people&#8221; these days seems to be extremely excited about <a href="http://www.css3.info/" title="CSS3 Info Website">CSS3</a>. Along with &#8220;HTML5&#8243;, &#8220;CSS3&#8243; has become one of the big buzz words on the web. Browser leaders like <a href="http://www.mozilla-europe.org/en/firefox/" title="Firefox Official Website">Firefox</a>, <a href="http://www.google.com/chrome" title="Chrome Official Website">Chrome</a>, <a href="http://www.apple.com/safari/" title="Safari Official Website">Safari</a> and <a href="http://www.opera.com/" title="Opera Official Website">Opera</a> started adoption of CSS3 before the final specification has been released. This has made it possible for developers to tap into new style properties, selectors and even transformations. CSS3 is like the new playground that all children have been waiting for and now everyone wants to play. Everyone is excited, <strong>but is it for the right reasons</strong>?<span id="more-493"></span></p>
<h2>The CSS3 &#8220;Image-less&#8221; Hype</h2>
<p>Every day, while browsing through tweets and blogs, I find fascinated people spreading the word about &#8220;<a href="http://graphicpeel.com/cssiosicons">iPhone icons with just CSS3 and no images</a>&#8220;, &#8220;<a href="http://media.smashingmagazine.com/cdn_smash/wp-content/uploads/uploader/images/css3-designs/css3-monsters-dragon/index.html">CSS3 only monster drawing</a>&#8220;, &#8220;<a href="http://media.smashingmagazine.com/cdn_smash/wp-content/uploads/uploader/images/css3-designs/css3-ipad-with-shadow/index.html">CSS3 iPad no images</a>&#8220;, &#8220;<a href="http://media.smashingmagazine.com/cdn_smash/wp-content/uploads/uploader/images/css3-designs/css3-charts/index.html">CSS3 pie chart</a>&#8220;, &#8220;<a href="http://media.smashingmagazine.com/cdn_smash/wp-content/uploads/uploader/images/css3-designs/css3-image-less-3d-menu/index.html">3D page layout with CSS3</a>&#8220;, &#8220;<a href="http://media.smashingmagazine.com/cdn_smash/wp-content/uploads/uploader/images/css3-designs/css3-under-the-sea-in-css3/index.html">CSS3 Animated under sea world</a>&#8220;, &#8220;<a href="http://cordobo.com/wp-content/uploads/pure-css-animated-3d-super-mario/">3D animated Super Mario, CSS3, no images</a>&#8221; and many many more. Recently <a href="http://www.smashingmagazine.com/" title="Smashing Magazine website">Smashing Magazine</a> even announced a CSS3 design competition and if you are interested in the results, please <a href="http://www.smashingmagazine.com/2010/07/12/css3-design-contest-results/">do check them out</a>.</p>
<p><img src="http://yavkata.co.uk/weblog/wp-content/uploads/CSS3_examples.jpg" alt="CSS3 examples" title="CSS3_examples" width="618" height="150" class="alignnone size-full wp-image-532" /></p>
<p>All these examples are great little experiments, but they do not quite show what CSS3 is all about. Somehow they seem to define as a great accomplishment the ability to create a picture (even an animated one) on the screen without a single image using just CSS as a drawing and animating tool.</p>
<p>That, however, is completely off target. CSS is not a drawing tool and <strong>setting the <span class="code">background</span> property to a bunch of meaningless <span class="code">div</span>-s and arranging them together to form an image does not show you the strength of CSS3</strong>. On the contrary, it throws web design way back to square one <strong>when content and presentation were scrambled together in a hodgepodge of horrid mark-up</strong>.</p>
<p>The whole &#8220;no images, CSS only&#8221; concept might be in danger of going too far. CSS3 is not here to replace images on the web (I am not talking about content images, but <strong>styling images</strong>), not at all. It is here to <strong>replace old techniques</strong> of achieving round corners, shadows and gradients using images and poor mark-up. If someone needs a more complex graphic, then he/she should use an image and not try to &#8220;draw&#8221; one using CSS backgrounds and a bunch of DOM elements. Leave mark-up alone, its duties end when design starts. Besides, HTML5 will give us the <span class="code">canvas</span> where we can actually draw.</p>
<p><strong>Note:</strong> I realise that some of the aforementioned CSS3 examples are created probably just for fun and deprived of any serious meaning. However, they create the wrong hype around CSS3 and they fail to show its true advantages.</p>
<h2>CSS3 is about HTML semantics</h2>
<p>The mark-up, the mark-up, the mark-up! It is all about the mark-up. CSS3&#8242;s ultimate goal and reason for being is not to change the face of the web, <strong>but to smarten it</strong>. Despite all efforts and preachings of web gurus about web standards and semantic web, up until now &#8220;sleek Web 2.0&#8243; design with shadows and rounded corners could not be possible without staining the semantics of the mark-up with meaningless <span class="code">div</span>-s, <span class="code">spans</span>-s etc.</p>
<p>Some say Web 2.0 was a revolution. Although that might very well be true, I reckon Web 2.0 has been <strong>mediocre</strong> in terms of semantics, accessibility and cross-browser/cross-device compatibility, <strong>inefficient</strong> in terms of performance and <strong>somewhat good looking</strong> but in a very very <strong>artificial</strong> way. CSS3 is loaded with the potential to facilitate the emergence of the next iteration of the Web &#8211; fast, smart, accessible, ubiquitous and beautiful.</p>
<h2>CSS3 is about speed</h2>
<p>If CSS3 is about semantics, it is about performance as well. That is because achieving ultimate semantic mark-up means using the minimum necessary amount of DOM elements. And since <a href="http://developer.yahoo.com/yui/theater/video.php?v=zakas-hpjs" title="High Performance JavaScript talk by the Yahoo performance team">the DOM is slow</a>, reducing its elements will inevitably boost performance.</p>
<p>Another speed enhancing consequence of CSS3 is the reduced number of HTTP requests due to the smaller amount of images that are needed for styling (the upper-mentioned shadows, rounded corners, gradients, etc.) Less HTTP requests means smaller load on servers, more efficient bandwidth usage and ultimately faster websites.</p>
<h2>CSS3 is about subtleties</h2>
<p>Design should always obey content. Design is there to make content easier to spot, read and digest. Beyond that there is just a thin strip allowing design to solely serve creativity very subtly. The true beauty of design resides within this subtlety. Small and &#8220;quiet&#8221; visual effects like slight shadows, gradients, soft round corners and very light transitions can really change the look and feel of a page.</p>
<p>Up until now achieving those subtle design effects could not be done without getting in the way of content semantics. And it&#8217;s those subtleties that reveal the true potency of CSS3. CSS3 will give us a chance to clean the web and make it beautiful &#8220;inside&#8221;. Now that&#8217;s what I find exciting.</p>
]]></content:encoded>
			<wfw:commentRss>http://yavkata.co.uk/weblog/xhtml_css/the-pitfalls-of-css3/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Securing HTML hidden input fields</title>
		<link>http://yavkata.co.uk/weblog/php/securing-html-hidden-input-fields-using-encryption-and-hashing/</link>
		<comments>http://yavkata.co.uk/weblog/php/securing-html-hidden-input-fields-using-encryption-and-hashing/#comments</comments>
		<pubDate>Thu, 08 Jul 2010 22:13:25 +0000</pubDate>
		<dc:creator>Yavor Atanasov</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Server-side technologies]]></category>
		<category><![CDATA[XHTML and CSS]]></category>
		<category><![CDATA[decryption]]></category>
		<category><![CDATA[encryption]]></category>
		<category><![CDATA[Form]]></category>
		<category><![CDATA[hashing]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://yavkata.co.uk/weblog/?p=365</guid>
		<description><![CDATA[Input fields of type â€œhiddenâ€ are non-interactive form elements that are not rendered by the browser (remaining â€œhiddenâ€ from the user). This type of input element represents a value that is not intended to be examined or manipulated by the user. Its sole purpose is to facilitate data round-trips from and to the web server, [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://yavkata.co.uk/weblog/wp-content/uploads/Securing_Hidden_Input.jpg" alt="Securing Hidden Input" title="Securing HTML hidden input fields" class="alignleft size-full wp-image-466" />Input fields of type â€œhiddenâ€ are non-interactive form elements that are not rendered by the browser (remaining â€œhiddenâ€ from the user). This type of input element <cite><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#states-of-the-type-attribute" title="whatwg HTML5 specification">represents a value that is not intended to be examined or manipulated by the user</a></cite>. Its sole purpose is to facilitate data round-trips from and to the web server, thus, trying to solve implications  caused by the fact that web servers are <a href="http://en.wikipedia.org/wiki/Stateless_protocol" title="Definition of Stateless protocol">stateless</a>. In some respect, the role of the hidden input field intersects with the one of the cookie â€“ trying to maintain a state between http requests.<span id="more-365"></span></p>
<p>There are numerous examples and reasons why one would use hidden input fields in a form, but mainly they all boil down to the following â€“ the server sends out data it wants back <strong>unchanged</strong>.</p>
<div id="attachment_373" class="wp-caption alignnone" style="width: 630px"><img src="http://yavkata.co.uk/weblog/wp-content/uploads/hidden_input_general_case.jpg" alt="Hidden input general case" title="hidden_input_general_case" class="size-full wp-image-373" /><p class="wp-caption-text">Figure 1. General case of hidden input data round trip</p></div>
<p>The name â€œhiddenâ€, however, is very misleading because it creates a false sense of security. Nothing on the user machine can really be hidden and therefore virtually anything can be changed. That is why the upper definition says â€œnot intended to be examinedâ€ and not â€œcannot be examinedâ€. </p>
<p><strong>Bottom line:</strong> Hidden input fields are neither hidden, nor unchangeable. Once data has left the realm of the web server, it should be treated as possibly contaminated and potentially dangerous. Hidden fields are no exception.</p>
<h2>How to make hidden input fields truly hidden and unchangeable</h2>
<p>The simple answer is &#8211; you can&#8217;t. What you can do, however, is make the hidden input&#8217;s value unreadable and check to see if the value remained unchanged after the round trip to the user machine. Although web security is never trivial and requires careful assessment of the possible vulnerabilities , this particular task has a relatively trivial solution.</p>
<h5 class="entry_subtitle">Encryption and hashing</h5>
<p>When it comes to hiding (or protecting) information, we essentially talk about <strong>encryption</strong>. Encryption takes a piece of readable information and using a <strong>key</strong> and a special <strong>algorithm</strong> turns this information into a scrambled unreadable string. Later on, using an appropriate (not necessarily the same) key and algorithm, the scrambled string can be turned back into the original readable message (<strong>decryption</strong>).</p>
<p><strong>Hashing</strong>, also referred to as one-way-encryption, employs algorithms that turn the input into a <strong>unique</strong> value (digest) and make reversion back to the original input impossible (collisions are theoretically possible but computationally infeasible; that depends on the hashing algorithm and technique used, but that is a whole other discussion). The fact that no two inputs would produce the same digest makes hashing great for verifying data.</p>
<p>So, <strong>encryption</strong> makes data safe to travel and <strong>hashing</strong> ensures the data arrives unchanged. All it takes is for both the origin and destination to have the appropriate key and to know the encryption and hashing algorithms. That is what is needed to tackle the security issues with hidden input fields. </p>
<div id="attachment_374" class="wp-caption alignnone" style="width: 630px"><img src="http://yavkata.co.uk/weblog/wp-content/uploads/encrypt_decrypt.jpg" alt="encrypt-decrypt" title="encrypt_decrypt" class="size-full wp-image-374" /><p class="wp-caption-text">Figure 2. General case of encryption-decryption and hashing correspondence</p></div>
<h5 class="entry_subtitle">Applying encryption and hashing to hidden input fields</h5>
<p>If we need to translate Figure 2 to our specific case, the web server is both the origin and destination of the data, and the user machine is the untrusted medium that can compromise the data.</p>
<div id="attachment_375" class="wp-caption alignnone" style="width: 630px"><img src="http://yavkata.co.uk/weblog/wp-content/uploads/hidden_input_encrypt_hash_case.jpg" alt="Hidden input with encrypt and hash" title="hidden_input_encrypt_hash_case" class="size-full wp-image-375" /><p class="wp-caption-text">Figure 3. Applying encryption and hashing to hidden input</p></div>
<p>As Figure 3 indicates the necessary steps needed to be taken to implement the solution are as follows:</p>
<ul>
<li>Hash the original value</li>
<li>Encrypt the original value</li>
<li>Send the encrypted value along with the hash digest</li>
<li>Upon receiving back the data, decrypt the encryption, hash the result and compare it to the received hash digest to ensure the value remained unchanged</li>
</ul>
<p>All that is left is the implementation itself&#8230;</p>
<h2>Implementing the solution in PHP</h2>
<p>PHP provides functions and extensions that deal with encryption and hashing. There are many ways one can implement encryption and hashing &#8211; numerous algorithms and techniques. This is the time to say that there is not a right or wrong way of doing things. It all depends on the level of security one strives to achieve. The field of cryptography and security is pretty dynamic and one should always investigate current developments and recommendations.</p>
<p>That being said, the proposed PHP solution should not be taken as the only possible one nor the best (it certainly is not, although it is quite decent). It is just for practical illustration of the upper-described concept.</p>
<h5 class="entry_subtitle">Encryption-decryption in PHP using MCRYPT extension</h5>
<p><a href="http://php.net/manual/en/book.mcrypt.php" title="MCRYPT extension official page">The MCRYPT extension</a> provides an <cite>interface to the mcrypt library, which supports a wide variety of <a href="http://en.wikipedia.org/wiki/Block_cipher" title="Block cipher introduction from Wikipedia">block algorithms</a></cite> including DES, TripleDES, Blowfish and <a href="http://www.php.net/manual/en/mcrypt.ciphers.php" title="Full list of supported algorithms and cipher modes">many more</a>. This example will make use of the <a href="http://en.wikipedia.org/wiki/Blowfish_(cipher)" title="Introduction to Blowfish cipher from Wikipedia">Blowfish cipher</a> (64-bit block size) with a 128 bit key. MCRYPT provides a function that implements the supported list of ciphers &#8211; <a href="http://www.php.net/manual/en/function.mcrypt-encrypt.php" title="Full description of the function">mcrypt_encrypt()</a>. Here is the function description and parameters:</p>
<div class="codesnip-container" >
<div class="php codesnip" style="font-family:monospace;">string <a href="http://www.php.net/mcrypt_encrypt"><span class="kw3">mcrypt_encrypt</span></a> <span class="br0">&#40;</span> string <span class="re0">$cipher</span> <span class="sy0">,</span> string <span class="re0">$key</span> <span class="sy0">,</span> string <span class="re0">$data</span> <span class="sy0">,</span> string <span class="re0">$mode</span> <span class="br0">&#91;</span><span class="sy0">,</span> string <span class="re0">$iv</span> <span class="br0">&#93;</span> <span class="br0">&#41;</span></div>
</div>
<p>The list of parameters that we are going to use is as follows:</p>
<ul>
<li><span class="code variable">$cipher</span> &#8211; this takes one of the <a href="http://www.php.net/manual/en/mcrypt.ciphers.php" title="The full list of predefined cipher constants">predefined constants</a> <span class="code">MCRYPT_ciphername</span>, in our case <span class="code">MCRYPT_BLOWFISH</span></li>
<li><span class="code variable">$key</span> &#8211; in order to generate a 128-bit key, we can use any string and hash it with the 128-bit <a href="http://php.net/manual/en/function.md5.php" title="md5 manual">md5 function</a> &#8211; <span class="code">md5(&#8216;ESP_guitars_rock&#8217;)</span>. This would produce the following key: <span class="code">6cf50d50aa1174778a0c24fffa558593</span></li>
<li><span class="code variable">$data</span> &#8211; this the message/value that needs to be encrypted, in our case we will encrypt the super secret message &#8211; <span class="code">&#8216;Bing is actually famous, check in Google&#8217;</span></li>
<li><span class="code variable">$mode</span> &#8211; one of the <span class="code">MCRYPT_MODE_modename</span> constants, in our case <span class="code">MCRYPT_MODE_CFB</span></li>
<li><span class="code variable">$iv</span> &#8211; <a href="http://en.wikipedia.org/wiki/Initialization_vector">initialisation vector</a> that needs to be the same size as the block size of the cipher. Blowfish has a 64-bit block size. However, we do not have to remember that. We can use the <a href="http://www.php.net/manual/en/function.mcrypt-get-iv-size.php" title="Function manual">mcrypt_get_iv_size()</a> function to get the necessary size.</li>
</ul>
<p>This is how the final implementation of <span class="code function">mcrypt_encrypt()</span> looks like:
</p>
<div class="codesnip-container" >
<div class="php codesnip" style="font-family:monospace;"><span class="kw2">&lt;?php</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$key</span> <span class="sy0">=</span> <a href="http://www.php.net/md5"><span class="kw3">md5</span></a><span class="br0">&#40;</span><span class="st_h">&#8216;ESP_guitars_rock&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$original_value</span> <span class="sy0">=</span> <span class="st_h">&#8216;Bing is actually famous, check in Google&#8217;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$iv</span> <span class="sy0">=</span> <a href="http://www.php.net/substr"><span class="kw3">substr</span></a><span class="br0">&#40;</span><a href="http://www.php.net/md5"><span class="kw3">md5</span></a><span class="br0">&#40;</span><span class="st_h">&#8216;Metallica&#8217;</span><span class="br0">&#41;</span><span class="sy0">,</span>0<span class="sy0">,</span><a href="http://www.php.net/mcrypt_get_iv_size"><span class="kw3">mcrypt_get_iv_size</span></a><span class="br0">&#40;</span>MCRYPT_BLOWFISH<span class="sy0">,</span> MCRYPT_MODE_CFB<span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$encrypted_value</span> <span class="sy0">=</span> <a href="http://www.php.net/base64_encode"><span class="kw3">base64_encode</span></a><span class="br0">&#40;</span><a href="http://www.php.net/mcrypt_encrypt"><span class="kw3">mcrypt_encrypt</span></a><span class="br0">&#40;</span>MCRYPT_BLOWFISH<span class="sy0">,</span> <span class="re0">$key</span><span class="sy0">,</span> <span class="re0">$original_value</span><span class="sy0">,</span> MCRYPT_MODE_CFB<span class="sy0">,</span> <span class="re0">$iv</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span></div>
</div>
<p><strong>Note:</strong> We need to encode the output of the <span class="code function">mcrypt_encrypt()</span> function with <a href="http://php.net/manual/en/function.base64-encode.php" title="base64_encode manual">base64_encode()</a>. This encodes the binary data with MIME base64 so it survives transportation when it travels from and to the web server. Otherwise, the data might (most probably will) arrive corrupted and this would break the decryption process. When the data arrives back at the server <a href="http://www.php.net/manual/en/function.base64-decode.php" title="base64_decode manual">base64_decode()</a> is used to decode the data back to the original output of <span class="code function">mcrypt_encrypt()</span>.</p>
<p>The decryption process is carried out in a similar way, this time using the <a href="http://www.php.net/manual/en/function.mcrypt-decrypt.php" title="mcrypt_decrypt manual">mcrypt_decrypt()</a> function, which takes the same parameters as <span class="code function">mcrypt_encrypt()</span>. Note that the <span class="code variable">$encrypted_value</span> has to be decoded first with <span class="code function">base64_decode()</span>.</p>
<div class="codesnip-container" >
<div class="php codesnip" style="font-family:monospace;"><span class="re0">$decrypted_value</span> <span class="sy0">=</span> <a href="http://www.php.net/mcrypt_decrypt"><span class="kw3">mcrypt_decrypt</span></a><span class="br0">&#40;</span>MCRYPT_BLOWFISH<span class="sy0">,</span> <span class="re0">$key</span><span class="sy0">,</span> <a href="http://www.php.net/base64_decode"><span class="kw3">base64_decode</span></a><span class="br0">&#40;</span><span class="re0">$encrypted_value</span><span class="br0">&#41;</span><span class="sy0">,</span> MCRYPT_MODE_CFB<span class="sy0">,</span> <span class="re0">$iv</span><span class="br0">&#41;</span><span class="sy0">;</span></div>
</div>
<h5 class="entry_subtitle">Hashing in PHP</h5>
<p>PHP provides several hashing options, most common (and strongest) of which are <span class="code function">md5()</span> and <span class="code function">sha1()</span>. The former generates a 128-bit hash, whereas the latter returns a 160-bit hash. Although that might sound like a lot of bits, modern hardware can generate hashes of this length pretty quickly (hundreds and even thousands per second). This way, using a dictionary (not only words, but also alpha-numeric combinations), an attacker can keep generating hashes until a <a href="http://en.wikipedia.org/wiki/Collision_%28computer_science%29" title="Definition of collision in Computer Science">collision</a> appears &#8211; meaning he can find the original value that generated your hash.</p>
<p>One solution to this weakness is simply using stronger hashing functions (more bits) in order to make brute force collision detection computationally infeasible. However, those functions will also put computational pressure on web servers and ultimately make web pages slow. On the other hand, as of this moment <span class="code function">md5()</span> and <span class="code function">sha1()</span> are the strongest functions implemented for PHP.</p>
<p>Therefore, a technique can be applied to those functions that makes them stronger &#8211; adding <strong>salts</strong>. Salts are random bits of string with sufficient length that are added to the hash. This results in a different hash generated each time from the same input value. Consequently, we need to know the salt value later in order to regenerate the same hash for the data verification.</p>
<p>This might sound a bit confusing at first, however, looking at an example should clear the confusion. For our hashing process, we will use the 160-bit <span class="code function">sha1()</span> function. This is how a plain normal hashing in PHP looks like:</p>
<div class="codesnip-container" >
<div class="php codesnip" style="font-family:monospace;"><span class="co1">//this would produce the followin hash &#8211; 3251d0991b55202abe9ede887efab662d3d57399</span><br />
<a href="http://www.php.net/sha1"><span class="kw3">sha1</span></a><span class="br0">&#40;</span><span class="st_h">&#8216;my_string&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span></div>
</div>
<p>Now let&#8217;s fortify this hash mixing it with a salt:</p>
<div class="codesnip-container" >
<div class="php codesnip" style="font-family:monospace;"><span class="re0">$original_value</span> <span class="sy0">=</span> <span class="st_h">&#8216;my_string&#8217;</span><span class="sy0">;</span><br />
<span class="re0">$salt</span> <span class="sy0">=</span> <a href="http://www.php.net/substr"><span class="kw3">substr</span></a><span class="br0">&#40;</span><a href="http://www.php.net/md5"><span class="kw3">md5</span></a><span class="br0">&#40;</span><a href="http://www.php.net/uniqid"><span class="kw3">uniqid</span></a><span class="br0">&#40;</span><a href="http://www.php.net/rand"><span class="kw3">rand</span></a><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">,</span> <span class="kw4">true</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">,</span> 0<span class="sy0">,</span> 10<span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$hashed_value</span> <span class="sy0">=</span> <span class="re0">$salt</span> <span class="sy0">.</span> <a href="http://www.php.net/substr"><span class="kw3">substr</span></a><span class="br0">&#40;</span><a href="http://www.php.net/sha1"><span class="kw3">sha1</span></a><span class="br0">&#40;</span><span class="re0">$salt</span> <span class="sy0">.</span> <span class="re0">$original_value</span><span class="br0">&#41;</span><span class="sy0">,-</span>10<span class="br0">&#41;</span><span class="sy0">;</span></div>
</div>
<p>Figure 4 illustrates the algorithm used for creating the <span class="code variable">$salt</span>. The algorithm uses the functions <a href="http://php.net/manual/en/function.rand.php" title="Function manual">rand()</a>, <a href="http://php.net/manual/en/function.uniqid.php" title="Function manual">uniqid()</a>, <a href="http://php.net/manual/en/function.md5.php" title="Function manual">md5()</a> and <a href="http://php.net/manual/en/function.substr.php" title="Function manual">substr()</a> to create a unique salt with length of 10. The illustration breaks the process into steps for better understanding of what is going on.</p>
<div id="attachment_434" class="wp-caption alignnone" style="width: 630px"><img src="http://yavkata.co.uk/weblog/wp-content/uploads/creating_salt_for_hashing.jpg" alt="Creating a salt for hashing" title="creating_salt_for_hashing" class="size-full wp-image-434" /><p class="wp-caption-text">Figure 4. Creating a salt for hashing</p></div>
<p>Then comes the algorithm for hashing &#8211; we concatenate the salt to the original string, create a 160-bit hash, take 10 characters of the resulting string (just so the final hash is not too long) and attach the salt to the beginning. This way, later we can extract the value of the salt again knowing it is the first 10 characters.</p>
<div id="attachment_437" class="wp-caption alignnone" style="width: 630px"><img src="http://yavkata.co.uk/weblog/wp-content/uploads/creating_hash_with_salt.jpg" alt="Creating a hash with salts" title="creating_hash_with_salt" class="size-full wp-image-437" /><p class="wp-caption-text">Figure 5. Creating a hash with salts</p></div>
<h5 class="entry_subtitle">Mixing it all together with hidden input fields</h5>
<p>Now it is time to put everything together. The starting point is just a very simple mark-up page with a form containing one hidden field and a submit button. We will create two php documents. One is <span class="code">form.php</span> where the encryption and the initial hashing will take place. The other is <span class="code">process_form.php</span> where the form will post to and where decryption and verification will take place.</p>
<p>This is the mark-up we are going to start with:</p>
<div class="codesnip-container" >
<div class="php codesnip" style="font-family:monospace;"><span class="sy0">&lt;!</span>DOCTYPE html<span class="sy0">&gt;</span><br />
<span class="sy0">&lt;</span>html lang<span class="sy0">=</span><span class="st0">&quot;en&quot;</span><span class="sy0">&gt;</span><br />
&nbsp; &nbsp; <span class="sy0">&lt;</span>head<span class="sy0">&gt;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="sy0">&lt;</span>meta charset<span class="sy0">=</span><span class="st0">&quot;utf-8&quot;</span><span class="sy0">/&gt;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="sy0">&lt;</span>title<span class="sy0">&gt;</span>Simple Form<span class="sy0">&lt;/</span>title<span class="sy0">&gt;</span><br />
&nbsp; &nbsp; <span class="sy0">&lt;/</span>head<span class="sy0">&gt;</span><br />
&nbsp; &nbsp; <span class="sy0">&lt;</span>body<span class="sy0">&gt;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="sy0">&lt;</span>form action<span class="sy0">=</span><span class="st0">&quot;process_form.php&quot;</span> method<span class="sy0">=</span><span class="st0">&quot;post&quot;</span><span class="sy0">&gt;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="sy0">&lt;</span>input type<span class="sy0">=</span><span class="st0">&quot;hidden&quot;</span> name<span class="sy0">=</span><span class="st0">&quot;my_value&quot;</span> value<span class="sy0">=</span><span class="st0">&quot;Bing is actually famous, check in Google&quot;</span><span class="sy0">/&gt;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="sy0">&lt;</span>input type<span class="sy0">=</span><span class="st0">&quot;submit&quot;</span> value<span class="sy0">=</span><span class="st0">&quot;Submit form&quot;</span><span class="sy0">/&gt;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="sy0">&lt;/</span>form<span class="sy0">&gt;</span><br />
&nbsp; &nbsp; <span class="sy0">&lt;/</span>body<span class="sy0">&gt;</span><br />
<span class="sy0">&lt;/</span>html<span class="sy0">&gt;</span></div>
</div>
<p>Below is the modified version (document <span class="code">form.php</span>) with added encryption and hashing. Note that there is an additional hidden field just for the hashed value. That is not necessary and is done just for clarity. The hashed value can be concatenated to the encrypted value.</p>
<div class="codesnip-container" >
<div class="php codesnip" style="font-family:monospace;">&lt;!DOCTYPE html&gt;<br />
&lt;html lang=&quot;en&quot;&gt;<br />
&nbsp; &nbsp; &lt;head&gt;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &lt;meta charset=&quot;utf-8&quot;/&gt;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &lt;title&gt;Simple Form&lt;/title&gt;<br />
&nbsp; &nbsp; &lt;/head&gt;<br />
&nbsp; &nbsp; &lt;body&gt;<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">&lt;?php</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$key</span> <span class="sy0">=</span> <a href="http://www.php.net/md5"><span class="kw3">md5</span></a><span class="br0">&#40;</span><span class="st_h">&#8216;ESP_guitars_rock&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$original_value</span> <span class="sy0">=</span> <span class="st_h">&#8216;Bing is actually famous, I checked in Google&#8217;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$iv</span> <span class="sy0">=</span> <a href="http://www.php.net/substr"><span class="kw3">substr</span></a><span class="br0">&#40;</span><a href="http://www.php.net/md5"><span class="kw3">md5</span></a><span class="br0">&#40;</span><span class="st_h">&#8216;Metallica&#8217;</span><span class="br0">&#41;</span><span class="sy0">,</span>0<span class="sy0">,</span><a href="http://www.php.net/mcrypt_get_iv_size"><span class="kw3">mcrypt_get_iv_size</span></a><span class="br0">&#40;</span>MCRYPT_BLOWFISH<span class="sy0">,</span> MCRYPT_MODE_CFB<span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$encrypted_value</span> <span class="sy0">=</span> <a href="http://www.php.net/base64_encode"><span class="kw3">base64_encode</span></a><span class="br0">&#40;</span><a href="http://www.php.net/mcrypt_encrypt"><span class="kw3">mcrypt_encrypt</span></a><span class="br0">&#40;</span>MCRYPT_BLOWFISH<span class="sy0">,</span> <span class="re0">$key</span><span class="sy0">,</span> <span class="re0">$original_value</span><span class="sy0">,</span> MCRYPT_MODE_CFB<span class="sy0">,</span> <span class="re0">$iv</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">//Now create a decent hash with a 10 character salt</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$salt</span> <span class="sy0">=</span> <a href="http://www.php.net/substr"><span class="kw3">substr</span></a><span class="br0">&#40;</span><a href="http://www.php.net/md5"><span class="kw3">md5</span></a><span class="br0">&#40;</span><a href="http://www.php.net/uniqid"><span class="kw3">uniqid</span></a><span class="br0">&#40;</span><a href="http://www.php.net/rand"><span class="kw3">rand</span></a><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">,</span> <span class="kw4">true</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">,</span> 0<span class="sy0">,</span> 10<span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$hashed_value</span> <span class="sy0">=</span> <span class="re0">$salt</span> <span class="sy0">.</span> <a href="http://www.php.net/substr"><span class="kw3">substr</span></a><span class="br0">&#40;</span><a href="http://www.php.net/sha1"><span class="kw3">sha1</span></a><span class="br0">&#40;</span><span class="re0">$salt</span> <span class="sy0">.</span> <span class="re0">$original_value</span><span class="br0">&#41;</span><span class="sy0">,-</span>10<span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="sy1">?&gt;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &lt;form action=&quot;process_form.php&quot; method=&quot;post&quot;&gt;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;input type=&quot;hidden&quot; name=&quot;encrypted_value&quot; value=&quot;<span class="kw2">&lt;?php</span> <span class="kw1">echo</span> <span class="re0">$encrypted_value</span><span class="sy0">;</span> <span class="sy1">?&gt;</span>&quot;/&gt;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;input type=&quot;hidden&quot; name=&quot;hashed_value&quot; value=&quot;<span class="kw2">&lt;?php</span> <span class="kw1">echo</span> <span class="re0">$hashed_value</span><span class="sy0">;</span> <span class="sy1">?&gt;</span>&quot;/&gt;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;input type=&quot;submit&quot; value=&quot;Submit form&quot;/&gt;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &lt;/form&gt;<br />
&nbsp; &nbsp; &lt;/body&gt;<br />
&lt;/html&gt;</div>
</div>
<p>And finally, below is the processing script (document <span class="code">process_form.php</span>). First a check is made to make sure that the form has been posted properly. Then the encrypted value is decrypted using the same <span class="code variable">$key</span> and <span class="code variable">$iv</span>. Then the <span class="code variable">$salt</span> is extracted from the posted hashed value (the first 10 characters). A new hash is created from the decrypted value and the salt using the same algorithm. Finally this new hash is compared to the original one posted by the form. If they match, this means the data came back valid and unchanged and further processing can continue (in this case just print). Otherwise, something went wrong and the data was corrupted, either intentionally or not.</p>
<div class="codesnip-container" >
<div class="php codesnip" style="font-family:monospace;"><span class="kw2">&lt;?php</span><br />
<span class="kw1">if</span> <span class="br0">&#40;</span><span class="sy0">!</span><a href="http://www.php.net/isset"><span class="kw3">isset</span></a><span class="br0">&#40;</span><span class="re0">$_POST</span><span class="br0">&#91;</span><span class="st_h">&#8216;encrypted_value&#8217;</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy0">||</span> <span class="sy0">!</span><a href="http://www.php.net/isset"><span class="kw3">isset</span></a><span class="br0">&#40;</span><span class="re0">$_POST</span><span class="br0">&#91;</span><span class="st_h">&#8216;hashed_value&#8217;</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; <a href="http://www.php.net/die"><span class="kw3">die</span></a><span class="br0">&#40;</span><span class="st_h">&#8216;Submission failed&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="br0">&#125;</span> <span class="kw1">else</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; <span class="re0">$key</span> <span class="sy0">=</span> <a href="http://www.php.net/md5"><span class="kw3">md5</span></a><span class="br0">&#40;</span><span class="st_h">&#8216;ESP_guitars_rock&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="re0">$iv</span> <span class="sy0">=</span> <a href="http://www.php.net/substr"><span class="kw3">substr</span></a><span class="br0">&#40;</span><a href="http://www.php.net/md5"><span class="kw3">md5</span></a><span class="br0">&#40;</span><span class="st_h">&#8216;Metallica&#8217;</span><span class="br0">&#41;</span><span class="sy0">,</span>0<span class="sy0">,</span><a href="http://www.php.net/mcrypt_get_iv_size"><span class="kw3">mcrypt_get_iv_size</span></a><span class="br0">&#40;</span>MCRYPT_BLOWFISH<span class="sy0">,</span> MCRYPT_MODE_CFB<span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp;<span class="re0">$decrypted_value</span> <span class="sy0">=</span> <a href="http://www.php.net/mcrypt_decrypt"><span class="kw3">mcrypt_decrypt</span></a><span class="br0">&#40;</span>MCRYPT_BLOWFISH<span class="sy0">,</span> <span class="re0">$key</span><span class="sy0">,</span> <a href="http://www.php.net/base64_decode"><span class="kw3">base64_decode</span></a><span class="br0">&#40;</span><span class="re0">$_POST</span><span class="br0">&#91;</span><span class="st_h">&#8216;encrypted_value&#8217;</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy0">,</span> MCRYPT_MODE_CFB<span class="sy0">,</span> <span class="re0">$iv</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="co1">//Now let&#8217;s recreate the hash</span><br />
&nbsp; &nbsp; <span class="co1">//We can extract the salt from the original hash</span><br />
&nbsp; &nbsp; <span class="re0">$salt</span> <span class="sy0">=</span> <a href="http://www.php.net/substr"><span class="kw3">substr</span></a><span class="br0">&#40;</span><span class="re0">$_POST</span><span class="br0">&#91;</span><span class="st_h">&#8216;hashed_value&#8217;</span><span class="br0">&#93;</span><span class="sy0">,</span> 0<span class="sy0">,</span> 10<span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="re0">$new_hashed_value</span> <span class="sy0">=</span> <span class="re0">$salt</span> <span class="sy0">.</span> <a href="http://www.php.net/substr"><span class="kw3">substr</span></a><span class="br0">&#40;</span><a href="http://www.php.net/sha1"><span class="kw3">sha1</span></a><span class="br0">&#40;</span><span class="re0">$salt</span> <span class="sy0">.</span> <span class="re0">$decrypted_value</span><span class="br0">&#41;</span><span class="sy0">,</span> <span class="sy0">-</span>10<span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="kw1">if</span><span class="br0">&#40;</span><span class="re0">$new_hashed_value</span> <span class="sy0">==</span> <span class="re0">$_POST</span><span class="br0">&#91;</span><span class="st_h">&#8216;hashed_value&#8217;</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">//This is where you process further the validated value. In our case just print</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">print</span> <span class="re0">$decrypted_value</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; <span class="kw1">else</span><span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">//The hidden value has been changed and is therefore invalid</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">print</span> <span class="st_h">&#8216;The message is corrupted&#8217;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span><br />
<span class="br0">&#125;</span></div>
</div>
<h2>Final words</h2>
<p>How far should a developer go with security depends on the situation at hand. Sometimes encryption of hidden fields may not be necessary &#8211; in case the developer does not care if the user will see the value or not. In any case, however, I strongly believe that <strong>hash verification should always be implemented</strong>. This would give the developer a piece of mind that data came back to the server unchanged and that no discrepancies would break his/her application.</p>
<h5 class="entry_subtitle">Resources and further readings</h5>
<ul>
<li><a href="http://php.net/">Official PHP page</a></li>
<li>Bret Mulvey, <a href="http://bretm.home.comcast.net/~bretm/hash/">Hash Functions</a>. Accessed July 6, 2010</li>
<li>Snyder, C. and Southwell, M. (2005). <a href="http://www.amazon.co.uk/Pro-PHP-Security-Chris-Snyder/dp/1590595084/ref=sr_1_1?ie=UTF8&#038;s=books&#038;qid=1278623997&#038;sr=8-1">Pro PHP Security</a>, New York, APRESS</li>
<li>Icons used in the illustrations courtesy of &#8211; <a href="http://pixel-mixer.com/">PixelMixer</a>, <a href="http://linux.softpedia.com/developer/Oliver-Scholtz-93.html">Oliver Scholtz</a> and <a href="http://www.everaldo.com/">Evelardo.com</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://yavkata.co.uk/weblog/php/securing-html-hidden-input-fields-using-encryption-and-hashing/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>PHP Singleton Design Pattern</title>
		<link>http://yavkata.co.uk/weblog/php/php-singleton-design-pattern/</link>
		<comments>http://yavkata.co.uk/weblog/php/php-singleton-design-pattern/#comments</comments>
		<pubDate>Sat, 01 May 2010 19:21:31 +0000</pubDate>
		<dc:creator>Yavor Atanasov</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Server-side technologies]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://yavkata.co.uk/weblog/?p=296</guid>
		<description><![CDATA[In software engineering, patterns simply suggest possible solution templates for re-occurring programming challenges. Patterns are not associated with any specific programming language. They just suggest a solution blueprint that can be implemented in any language. Depending on the level at which they operate within the application, software patterns can be divided into design patterns and [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://yavkata.co.uk/weblog/wp-content/uploads/thumb_singleton.jpg" alt="PHP Singleton Design Pattern" title="PHP Singleton Design Pattern" width="200" height="113" class="alignleft size-full wp-image-341" />In <a href="http://en.wikipedia.org/wiki/Software_engineering">software engineering</a>, patterns simply suggest possible solution templates for re-occurring programming challenges. Patterns are not associated with any specific programming language. They just suggest a solution blueprint that can be implemented in any language. Depending on the level at which they operate within the application, software patterns can be divided into <strong>design patterns</strong> and <strong>architectural patterns</strong>.<span id="more-296"></span></p>
<p><strong>Architectural Patterns</strong> operate on a higher level and define the entire system structure and work-flows. An example of an architectural pattern, extremely common in web development, is the <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">Model-View-Controller pattern</a>.</p>
<p><strong>Design Patterns</strong> dwell on a lower level and define the relationships and interactions of classes and objects. In object-oriented programming (OOP) design patterns help developers address challenges associated, for instance, with <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">responsibility</a> and <a href="http://en.wikipedia.org/wiki/Type_polymorphism">polymorphism</a>. Responsibility (<strong>single responsibility principle</strong>) deals with delegating specific tasks (responsibilities) to specific objects. It makes sure that there is exactly one object dealing with a given task. Polymorphism makes it possible to create a uniform interface to handle values of different data types. In other words, you can alter a given class without changing the rest of the code that interacts with it. This results in more flexible and portable applications with loosen interdependencies.</p>
<p>Two of the most commonly used design patterns with PHP are the Singleton and Factory patterns. The Singleton pattern is a responsibility pattern and the Factory pattern facilitates implementing polymorphism.</p>
<h5 class="entry_subtitle">The Singleton Pattern in PHP</h5>
<p>The Singleton pattern ensures that at any given time there will be just one instance of a given class within the application. It accomplishes that by limiting the object instantiation to just a single point within the object itself. In addition, it restricts its public constructor (by declaring it private) and also blocks the possibility of object cloning (by creating a blank private __clone() method). Thus a singleton class can only initialise itself and no other class can create a new instance or a copy of the object. The singleton class can provide a reference to its only instance if another object requires it.</p>
<p>The following hypothetical situation and sample code illustrate the purpose of the Singleton pattern.</p>
<p><span class="italic">Imagine a class of 4 students. Each student has one responsibility when the class starts &#8211; he/she must shout out loud his/her name for their teacher to write down in his attendance book.</span></p>
<p>Below is some sample code that implements the described task in the conventional way. Two classes are declared &#8211; <strong>Teacher</strong> and <strong>Student</strong>. The <strong>Teacher</strong> class has one protected property <strong>$_name</strong> and two public methods &#8211; one is the constructor and the other one marks a student as present. There is also another property <strong>$_number_of_instances</strong> which is static and it is just for the sake of keeping track of how many instances of the class are created. The <strong>Student</strong> class has two properties &#8211; the name of the student and the student&#8217;s teacher. Naturally, it has one public constructor and a public method <strong>shoutYourName</strong> that needs to tell the teacher that the student is present.</p>
<p>One thing to notice is that every time a student object is instantiated, a brand new teacher object is created as well. In other words, every student in this class has his/her own teacher. Going further down the sample code, four students are created and then they inform their teacher(s) of their presence.</p>
<div class="codesnip-container" >
<div class="php codesnip" style="font-family:monospace;"><span class="kw2">&lt;?php</span><br />
<span class="co4">/**<br />
&nbsp;Example of conventional implementation<br />
&nbsp;*/</span><br />
<span class="kw2">class</span> Teacher <span class="br0">&#123;</span><br />
&nbsp; &nbsp; <span class="kw2">private</span> <span class="re0">$_name</span><span class="sy0">;</span><br />
&nbsp; &nbsp; static <span class="re0">$_number_of_instances</span> <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="kw2">public</span> <span class="kw2">function</span> &nbsp;__construct<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">//initialise the object</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span>_name <span class="sy0">=</span> <span class="st_h">&#8216;James Hetfield&#8217;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">self</span><span class="sy0">::</span><span class="re0">$_number_of_instances</span> <span class="sy0">++;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">echo</span> <span class="st_h">&#8216;number of teachers:&#8217;</span> <span class="sy0">.</span> <span class="kw2">self</span><span class="sy0">::</span><span class="re0">$_number_of_instances</span> <span class="sy0">.</span> <span class="st_h">&#8216;&lt;br/&gt;&#8217;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; <span class="kw2">public</span> <span class="kw2">function</span> takeAttendance<span class="br0">&#40;</span><span class="re0">$studentName</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">//mark the student as present (insert to database)</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">echo</span> <span class="re0">$studentName</span> <span class="sy0">.</span> <span class="st_h">&#8216; is present.&lt;br/&gt;&#8217;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span><br />
<span class="br0">&#125;</span><br />
<span class="kw2">class</span> Student<span class="br0">&#123;</span><br />
&nbsp; &nbsp; <span class="kw2">private</span> <span class="re0">$_name</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="kw2">private</span> <span class="re0">$_teacher</span><span class="sy0">;</span> <span class="co1">//the teacher of the student</span><br />
&nbsp; &nbsp; <span class="kw2">public</span> <span class="kw2">function</span> &nbsp;__construct<span class="br0">&#40;</span><span class="re0">$name</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">//create a student</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span>_name <span class="sy0">=</span> <span class="re0">$name</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span>_teacher <span class="sy0">=</span> <span class="kw2">new</span> Teacher<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; <span class="kw2">public</span> <span class="kw2">function</span> shoutYourName<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span>_teacher<span class="sy0">-&gt;</span><span class="me1">takeAttendance</span><span class="br0">&#40;</span><span class="re0">$this</span><span class="sy0">-&gt;</span>_name<span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span><br />
<span class="br0">&#125;</span><br />
<span class="re0">$kirk</span> <span class="sy0">=</span> <span class="kw2">new</span> Student<span class="br0">&#40;</span><span class="st_h">&#8216;Kirk&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$lars</span> <span class="sy0">=</span> <span class="kw2">new</span> Student<span class="br0">&#40;</span><span class="st_h">&#8216;Lars&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$robert</span> <span class="sy0">=</span> <span class="kw2">new</span> Student<span class="br0">&#40;</span><span class="st_h">&#8216;Robert&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$jason</span> <span class="sy0">=</span> <span class="kw2">new</span> Student<span class="br0">&#40;</span><span class="st_h">&#8216;Jason&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$kirk</span><span class="sy0">-&gt;</span><span class="me1">shoutYourName</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$lars</span><span class="sy0">-&gt;</span><span class="me1">shoutYourName</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$robert</span><span class="sy0">-&gt;</span><span class="me1">shoutYourName</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$jason</span><span class="sy0">-&gt;</span><span class="me1">shoutYourName</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span></div>
</div>
<p>The code has the following output:</p>
<p>number of teachers:1<br/>number of teachers:2<br/>number of teachers:3<br/>number of teachers:4<br/>Kirk is present.<br/>Lars is present.<br/>Robert is present.<br/>Jason is present.</p>
<p>The picture below illustrates the result of the conventional implementation. It creates multiple unnecessary objects that do the same thing essentially (moreover, it does not recreate the described plot of 4 students and only 1 teacher).</p>
<p><img src="http://yavkata.co.uk/weblog/wp-content/uploads/conventional.jpg" alt="illustration of the conventional implementation" title="conventional" width="648" height="400" class="alignnone size-full wp-image-334" /></p>
<p>This is where the <strong>Singleton pattern</strong> comes into play. Below you can see a rewrite of the sample code. The <strong>Teacher</strong> class has been modified to become a, what is called, Singleton class. The modifications are as follows:</p>
<ul>
<li>Another static property has been added <strong>$_instance</strong> that will hold the self-created instance of the class.</li>
<li>The constructor method was changed from <strong>public</strong> to <strong>private</strong>, restricting its access from the outside.</li>
<li>A private method <strong>__clone()</strong> has been declared (doing nothing) to overwrite the PHP magic method <strong>__clone()</strong> in order to prevent object cloning</li>
<li>A public static method <strong>getInstance()</strong> has been created. Its function is to check if there is already an instance of the class, if there is not it creates one, stores it in the static <strong>$_instance</strong> variable and finally returns it to whoever requested it.</li>
<li>The Student object gets a reference to the teacher&#8217;s instance by calling the <strong>Teacher::getInstance</strong> method.</li>
</ul>
<div class="codesnip-container" >
<div class="php codesnip" style="font-family:monospace;"><span class="kw2">&lt;?php</span><br />
<span class="co4">/**<br />
&nbsp;Example of Singleton Pattern implementation<br />
&nbsp;*/</span><br />
<span class="kw2">class</span> Teacher <span class="br0">&#123;</span><br />
&nbsp; &nbsp; <span class="kw2">private</span> <span class="re0">$_name</span><span class="sy0">;</span><br />
&nbsp; &nbsp; static <span class="re0">$_instance</span><span class="sy0">;</span><br />
&nbsp; &nbsp; static <span class="re0">$_number_of_instances</span> <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="kw2">private</span> <span class="kw2">function</span> &nbsp;__construct<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">//initialise the object</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span>_name <span class="sy0">=</span> <span class="st_h">&#8216;James Hetfield&#8217;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">self</span><span class="sy0">::</span><span class="re0">$_number_of_instances</span> <span class="sy0">++;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">echo</span> <span class="st_h">&#8216;number of teachers:&#8217;</span> <span class="sy0">.</span> <span class="kw2">self</span><span class="sy0">::</span><span class="re0">$_number_of_instances</span> <span class="sy0">.</span><span class="st_h">&#8216;&lt;br/&gt;&#8217;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; <span class="kw2">private</span> <span class="kw2">function</span> &nbsp;__clone<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">//do nothing (this overwrites the special PHP method __clone())</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; <span class="kw2">public</span> static <span class="kw2">function</span> getInstance<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">if</span><span class="br0">&#40;</span><span class="sy0">!</span><span class="br0">&#40;</span><span class="kw2">self</span><span class="sy0">::</span><span class="re0">$_instance</span> instanceof <span class="kw2">self</span><span class="br0">&#41;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">self</span><span class="sy0">::</span><span class="re0">$_instance</span> <span class="sy0">=</span> <span class="kw2">new</span> <span class="kw2">self</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">return</span> <span class="kw2">self</span><span class="sy0">::</span><span class="re0">$_instance</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; <span class="kw2">public</span> <span class="kw2">function</span> takeAttendance<span class="br0">&#40;</span><span class="re0">$studentName</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">//mark the student as present (insert to database)</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">echo</span> <span class="re0">$studentName</span> <span class="sy0">.</span> <span class="st_h">&#8216; is present.&lt;br/&gt;&#8217;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span><br />
<span class="br0">&#125;</span><br />
<span class="kw2">class</span> Student<span class="br0">&#123;</span><br />
&nbsp; &nbsp; <span class="kw2">private</span> <span class="re0">$_name</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="kw2">private</span> <span class="re0">$_teacher</span><span class="sy0">;</span> <span class="co1">//the teacher of the student</span><br />
&nbsp; &nbsp; <span class="kw2">public</span> <span class="kw2">function</span> &nbsp;__construct<span class="br0">&#40;</span><span class="re0">$name</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">//create a student</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span>_name <span class="sy0">=</span> <span class="re0">$name</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span>_teacher <span class="sy0">=</span> Teacher<span class="sy0">::</span><span class="me2">getInstance</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; <span class="kw2">public</span> <span class="kw2">function</span> shoutYourName<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span>_teacher<span class="sy0">-&gt;</span><span class="me1">takeAttendance</span><span class="br0">&#40;</span><span class="re0">$this</span><span class="sy0">-&gt;</span>_name<span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span><br />
<span class="br0">&#125;</span><br />
<span class="re0">$kirk</span> <span class="sy0">=</span> <span class="kw2">new</span> Student<span class="br0">&#40;</span><span class="st_h">&#8216;Kirk&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$lars</span> <span class="sy0">=</span> <span class="kw2">new</span> Student<span class="br0">&#40;</span><span class="st_h">&#8216;Lars&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$robert</span> <span class="sy0">=</span> <span class="kw2">new</span> Student<span class="br0">&#40;</span><span class="st_h">&#8216;Robert&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$jason</span> <span class="sy0">=</span> <span class="kw2">new</span> Student<span class="br0">&#40;</span><span class="st_h">&#8216;Jason&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$kirk</span><span class="sy0">-&gt;</span><span class="me1">shoutYourName</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$lars</span><span class="sy0">-&gt;</span><span class="me1">shoutYourName</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$robert</span><span class="sy0">-&gt;</span><span class="me1">shoutYourName</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$jason</span><span class="sy0">-&gt;</span><span class="me1">shoutYourName</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span></div>
</div>
<p>The code outputs the following:</p>
<p>number of teachers:1<br/>Kirk is present.<br/>Lars is present.<br/>Robert is present.<br/>Jason is present.</p>
<p>The picture below shows the result. As you can see, using the Singleton pattern, the Teacher class has been instantiated just once and then each Student object receives a reference of that instance.</p>
<p><img src="http://yavkata.co.uk/weblog/wp-content/uploads/singleton.jpg" alt="illustration of the singleton implementation" title="singleton" width="648" height="400" class="alignnone size-full wp-image-335" /></p>
<h5 class="entry_subtitle">Benefits of the Singleton Pattern</h5>
<p>The Singleton pattern prevents memory duplication and, therefore, saves system resources. In addition, using the Singleton pattern, you can be sure that there is only one flow path for a certain task or data. This results in more controlled and secure application work flow as well as easier debugging and maintenance.</p>
<p><img src="http://yavkata.co.uk/weblog/wp-content/uploads/Singleton-Design-Pattern-PHP.jpg" alt="singleton design pattern illustration" title="Singleton-Design-Pattern-PHP" width="648" height="400" class="alignnone size-full wp-image-309" /></p>
<p>Further reading:</p>
<ul>
<li><a href="http://www.amazon.co.uk/Pro-PHP-Patterns-Frameworks-Testing/dp/1590598199/ref=sr_1_1?ie=UTF8&#038;s=books&#038;qid=1272741096&#038;sr=8-1">Pro PHP: Patterns, Frameworks, Testing &#038; More: Patterns, Frameworks, Testing and More </a></li>
<li><a href="http://www.killerphp.com/articles/php-design-patterns/">PHP Design Patterns â€“ when should they be used?</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://yavkata.co.uk/weblog/php/php-singleton-design-pattern/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Some great Google talks on front-end optimization</title>
		<link>http://yavkata.co.uk/weblog/xhtml_css/some-great-google-talks-on-optimization/</link>
		<comments>http://yavkata.co.uk/weblog/xhtml_css/some-great-google-talks-on-optimization/#comments</comments>
		<pubDate>Wed, 14 Apr 2010 01:21:21 +0000</pubDate>
		<dc:creator>Yavor Atanasov</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[XHTML and CSS]]></category>
		<category><![CDATA[optimization]]></category>
		<category><![CDATA[web performance]]></category>
		<category><![CDATA[ySlow]]></category>

		<guid isPermaLink="false">http://yavkata.co.uk/weblog/?p=256</guid>
		<description><![CDATA[Speeding up and optimizing JavaScript This is an excellent and extremely useful talk by Nicholas Zakas. He discusses JavaScript performance issues including scope management, data access, loops and the DOM. It&#8217;s the way these issues are approached that makes the difference between mere scripting and front-end engineering. High Performance Websites and YSlow Yahoo!&#8217;s Exceptional Performance [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-236" title="High performance websites" src="http://yavkata.co.uk/weblog/wp-content/uploads/high_performance_web.jpg" alt="high performance websites" width="200" height="113" /></p>
<h5 class="entry_subtitle">Speeding up and optimizing JavaScript</h5>
<p>This is an excellent and extremely useful talk by <a href="http://www.nczonline.net/about/">Nicholas Zakas</a>. He discusses JavaScript performance issues including scope management, data access, loops and the DOM. It&#8217;s the way these issues are approached that makes the difference between mere scripting and front-end engineering.<span id="more-256"></span></p>
<p><object type="application/x-shockwave-flash" style="width:620px; height:382px;" data="http://www.youtube.com/v/mHtdZgou0qU"><param name="movie" value="http://www.youtube.com/v/mHtdZgou0qU" /></object></p>
<h5 class="entry_subtitle">High Performance Websites and YSlow</h5>
<p>Yahoo!&#8217;s Exceptional Performance Team has identified 14 best practices for making web pages faster. These best practices have proven to reduce response times of Yahoo! properties by 25-50%. In this talk <a href="http://stevesouders.com/bio.php">Steve Souders</a> goes in-depth on these best practices and the research behind them. He demonstrates YSlow and does some live performance analysis of popular web sites. Enjoy the talk (the audio is bad only during the first 3-4 mins)</p>
<p><object type="application/x-shockwave-flash" style="width:620px; height:382px;" data="http://www.youtube.com/v/BTHvs3V8DBA&#038;hl=en_GB"><param name="movie" value="http://www.youtube.com/v/7_6B6vwE83U" /></object></p>
]]></content:encoded>
			<wfw:commentRss>http://yavkata.co.uk/weblog/xhtml_css/some-great-google-talks-on-optimization/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Bezier Curve Interactive Visualization with Actionscript 3</title>
		<link>http://yavkata.co.uk/weblog/actionscript_3/bezier-curve-interactive-visualization-with-actionscript-3/</link>
		<comments>http://yavkata.co.uk/weblog/actionscript_3/bezier-curve-interactive-visualization-with-actionscript-3/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 17:08:49 +0000</pubDate>
		<dc:creator>Yavor Atanasov</dc:creator>
				<category><![CDATA[Actionscript 3]]></category>
		<category><![CDATA[Bezier]]></category>
		<category><![CDATA[curve]]></category>
		<category><![CDATA[visualization]]></category>

		<guid isPermaLink="false">http://yavkata.co.uk/weblog/?p=218</guid>
		<description><![CDATA[Bezier curves, invented by french engineer Pierre Ã‰tienne BÃ©zier, play a crucial role in the world of computer graphics (and not only). They are used to create smooth and infinitely scalable curves (and surfaces in 3D) in vector graphics. In addition, in computer animation they are used to describe and control the velocity of an [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-236" title="Bezier curve visualization with actionscript" src="http://yavkata.co.uk/weblog/wp-content/uploads/bezier_curve_actionscript.jpg" alt="bezier curve actionscript image" width="200" height="113" /></p>
<p>Bezier curves, invented by french engineer <a href="http://en.wikipedia.org/wiki/Pierre_B%C3%A9zier" target="_blank">Pierre Ã‰tienne BÃ©zier</a>, play a crucial role in the world of computer graphics (and not only). They are used to create smooth and infinitely scalable curves (and surfaces in 3D) in vector graphics. In addition, in computer animation they are used to describe and control the velocity of an object, so that a more natural motion can be achieved via ease-in and ease-out effects. Those are just some of the applications of Bezier curves. <span id="more-218"></span></p>
<p>Understanding how Bezier curves work, however, can be mind-boggling if you just stare at the neat little formula that is used to describe them:</p>
<p><img class="alignnone size-full wp-image-232" title="bezier_formula" src="http://yavkata.co.uk/weblog/wp-content/uploads/bezier_formula.jpg" alt="bezier curves formula" width="370" height="60" /></p>
<p>I have always loved breaking complex things down into their smallest bits to bring out the beautiful simplicity hidden behind their intimidating mathematical facade. Do not get me wrong, I am not a math freak, not at all, but I always strive to actually <strong>see</strong> how things work. Therefore I dug a bit deeper into Bezier curves (just a bit) and I did some Actionscripting to create this simple interactive visualization that shows the mechanical beauty of the scary formula:</p>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_Bezier_Curves_772211645"
			class="flashmovie"
			width="620"
			height="400">
	<param name="movie" value="http://yavkata.co.uk/weblog/wp-content/uploads/Bezier_Curves.swf" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="http://yavkata.co.uk/weblog/wp-content/uploads/Bezier_Curves.swf"
			name="fm_Bezier_Curves_772211645"
			width="620"
			height="400">
	<!--<![endif]-->
		
<p><!-- Begin Alternate Content --></p>
<p><a href="http://adobe.com/go/getflashplayer"><br />
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /><br />
</a></p>
<p><!-- End Alternate Content --></p>

	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object>
<p>The maximum possible order number you can enter is 9, because higher degree curves get really expensive in terms of calculation. If you crank up the value to 9 you can notice how sluggish the application becomes (this of course depends on your machine&#8217;s characteristics). In general, the most commonly used Bezier curves in computer graphics are of order 2 and 3 (quadratic and cubic curves). If a more complex shape is required, Bezier curves are patched together forming <strong>paths</strong>.</p>
<p>The smoothness of the curve depends on how close the approximation is to the continuous interval [0,1]. This reflects the number of calculated points from the curve that get connected with a line segment. The more the points, the bigger their density and the smoother the raster curve.</p>
<h5 class="entry_subtitle">The Actionscript behind the application</h5>
<p>Those of you curious to see the Actionscript behind the application can check out the Bezier Actionscript class I wrote <a href="http://yavkata.co.uk/weblog/wp-content/uploads/Bezier.as" target="_blank">here</a><a></a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://yavkata.co.uk/weblog/actionscript_3/bezier-curve-interactive-visualization-with-actionscript-3/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Secure Forms with CodeIgniter and jQuery</title>
		<link>http://yavkata.co.uk/weblog/php/secure-forms-with-codeigniter-and-jquery/</link>
		<comments>http://yavkata.co.uk/weblog/php/secure-forms-with-codeigniter-and-jquery/#comments</comments>
		<pubDate>Sat, 27 Feb 2010 19:59:52 +0000</pubDate>
		<dc:creator>Yavor Atanasov</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Server-side technologies]]></category>
		<category><![CDATA[CodeIgniter]]></category>
		<category><![CDATA[Form]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://yavkata.co.uk/weblog/?p=148</guid>
		<description><![CDATA[1. Introduction In a dynamic web application the database is the heart that keeps it alive pumping data in and out. The database is the very core that holds the essence of that application &#8211; the data in its basic form. That core is then wrapped with the application layer that holds all logic and [...]]]></description>
			<content:encoded><![CDATA[<h5 class="entry_subtitle">1. Introduction</h5>
<p><img src="http://yavkata.co.uk/weblog/wp-content/uploads/CI_jQuery_validation.jpg" alt="CI_jQuery_validation" title="CI_jQuery_validation" width="200" height="113" class="alignleft size-full wp-image-212" /> In a dynamic web application the database is the heart that keeps it alive pumping data in and out. The database is the very core that holds the essence of that application &#8211; the data in its basic form. That core is then wrapped with the application layer that holds all logic and operations that seal that data and control its communication with the outer world. A web application is like a living cell and if something malignant enters its nucleus, it dies or becomes harmful.<br />
The web forms are a peculiar HTML element because they provide a pathway for external input leading to the data core of the web application. Therefore, what happens to that external input along the way before it enters the database is of crucial importance. <span id="more-148"></span>The input must be scanned and cleaned with great precision before it becomes pure data and &#8220;qualifies&#8221; for database insertion. This is what makes data pure:</p>
<ul>
<li>Its data type and format matches the one the database expects</li>
<li>Its length does not exceed the limit the database field can hold</li>
<li><a href="http://en.wikipedia.org/wiki/Escape_sequence">Escape sequences</a> and special characters should be filtered to prevent <a href="http://en.wikipedia.org/wiki/SQL_injection">SQL injections</a> which can be detrimental to the data integrity</li>
<li>Client-side scripts (JavaScript) should be recognized and filtered to prevent potential <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">cross-site scripting (XSS)</a></li>
</ul>
<p>This is where form validation kicks in. Form validation can be divided into two separate layers &#8211; client-side and server-side validation.</p>
<h5 class="entry_subtitle">2. Client-side vs Server-side validation</h5>
<p>Essentially both types of validation (client-side and server-side) are the very same thing, only the place where they are executed is different. Exactly that difference, however, defines the way we look at those two layers of validation. Client-side validation should be looked upon more like a usability enhancement that helps users with <strong>good intentions</strong> and <strong>bad typing</strong>. It is fast and users do not have to wait for a server response to understand they had input wrong data. JavaScript, however, can easily be disabled (presumably by users with <strong>bad intentions</strong>) thus removing the client-side layer of defense. Therefore, validation on the server is absolutely mandatory.</p>
<h5 class="entry_subtitle">3. CodeignIter and server-side validation</h5>
<p><a href="http://codeigniter.com/">Codeigniter</a> is a great open-source PHP <a href="http://codeigniter.com/user_guide/overview/mvc.html">MVC</a> framework that is loaded in terms of functionality and yet very light and excellently <a href="http://codeigniter.com/user_guide/">documented</a>. <a href="http://net.tutsplus.com/videos/screencasts/codeigniter-from-scratch-day-1/">Here</a> you can find an excellent tutorial to get you started with CodeIgniter if it is completely new for you.<br />
CodeIgniter comes with a built-in <a href="http://codeigniter.com/user_guide/libraries/form_validation.html">Form Validation Class</a> and a <a href="http://codeigniter.com/user_guide/helpers/form_helper.html">Form Helper</a> for fast and effective form building. This is how they can be used to quickly create a form and secure it on the server.</p>
<h5 class="entry_subtitle">3.1 Setting up the View</h5>
<div class="codesnip-container" >
<div class="php codesnip" style="font-family:monospace;">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;<br />
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;<br />
&lt;head profile=&quot;http://gmpg.org/xfn/11&quot;&gt;<br />
&lt;title&gt;CodeIgntier Form&lt;/title&gt;<br />
&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;<span class="kw2">&lt;?php</span> <span class="kw1">echo</span> <span class="re0">$base</span> <span class="sy0">.</span><span class="st_h">&#8216;css/main.css&#8217;</span><span class="sy0">;</span><span class="sy1">?&gt;</span>&quot;/&gt;<br />
&lt;script src=&quot;<span class="kw2">&lt;?php</span> <span class="kw1">echo</span> <span class="re0">$base</span> <span class="sy0">.</span><span class="st_h">&#8216;js/jquery-1.4.1.min.js&#8217;</span><span class="sy0">;</span><span class="sy1">?&gt;</span>&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;<span class="kw2">&lt;?php</span> <span class="kw1">echo</span> <span class="re0">$base</span> <span class="sy0">.</span><span class="st_h">&#8216;js/jquery.validate.min.js&#8217;</span><span class="sy0">;</span><span class="sy1">?&gt;</span>&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;<span class="kw2">&lt;?php</span> <span class="kw1">echo</span> <span class="re0">$base</span> <span class="sy0">.</span><span class="st_h">&#8216;js/additional-methods.js&#8217;</span><span class="sy0">;</span><span class="sy1">?&gt;</span>&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;<br />
&lt;script src=&quot;<span class="kw2">&lt;?php</span> <span class="kw1">echo</span> <span class="re0">$base</span> <span class="sy0">.</span><span class="st_h">&#8216;js/form_implementation.js&#8217;</span><span class="sy0">;</span><span class="sy1">?&gt;</span>&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
<span class="kw2">&lt;?php</span><br />
<span class="re0">$attributes</span> <span class="sy0">=</span> <a href="http://www.php.net/array"><span class="kw3">array</span></a><span class="br0">&#40;</span><span class="st_h">&#8216;id&#8217;</span> <span class="sy0">=&gt;</span> <span class="st_h">&#8216;myform&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="kw1">echo</span> form_open<span class="br0">&#40;</span><span class="st_h">&#8216;form/send&#8217;</span><span class="sy0">,</span> <span class="re0">$attributes</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$attributes</span> <span class="sy0">=</span> <a href="http://www.php.net/array"><span class="kw3">array</span></a><span class="br0">&#40;</span><span class="st_h">&#8216;id&#8217;</span> <span class="sy0">=&gt;</span> <span class="st_h">&#8216;personal_info&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="kw1">echo</span> form_fieldset<span class="br0">&#40;</span><span class="st_h">&#8216;Personal information&#8217;</span><span class="sy0">,</span> <span class="re0">$attributes</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="kw1">echo</span> form_label<span class="br0">&#40;</span><span class="st_h">&#8216;Your name&#8217;</span><span class="sy0">,</span> <span class="st_h">&#8216;name_field&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$attributes</span> <span class="sy0">=</span> <a href="http://www.php.net/array"><span class="kw3">array</span></a><span class="br0">&#40;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="st_h">&#8216;name&#8217;</span> &nbsp; &nbsp; &nbsp; &nbsp;<span class="sy0">=&gt;</span> <span class="st_h">&#8216;name&#8217;</span><span class="sy0">,</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="st_h">&#8216;id&#8217;</span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span class="sy0">=&gt;</span> <span class="st_h">&#8216;name_field&#8217;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="kw1">echo</span> form_input<span class="br0">&#40;</span><span class="re0">$attributes</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="kw1">echo</span> form_error<span class="br0">&#40;</span><span class="st_h">&#8216;name&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="kw1">echo</span> form_label<span class="br0">&#40;</span><span class="st_h">&#8216;Your email&#8217;</span><span class="sy0">,</span> <span class="st_h">&#8216;email_field&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="re0">$attributes</span> <span class="sy0">=</span> <a href="http://www.php.net/array"><span class="kw3">array</span></a><span class="br0">&#40;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="st_h">&#8216;name&#8217;</span> &nbsp; &nbsp; &nbsp; &nbsp;<span class="sy0">=&gt;</span> <span class="st_h">&#8216;email&#8217;</span><span class="sy0">,</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="st_h">&#8216;id&#8217;</span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span class="sy0">=&gt;</span> <span class="st_h">&#8216;email_field&#8217;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="kw1">echo</span> form_input<span class="br0">&#40;</span><span class="re0">$attributes</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="kw1">echo</span> form_error<span class="br0">&#40;</span><span class="st_h">&#8216;email&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="kw1">echo</span> form_submit<span class="br0">&#40;</span><span class="st_h">&#8216;submit&#8217;</span><span class="sy0">,</span> <span class="st_h">&#8216;Submit&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="kw1">echo</span> form_fieldset_close<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="kw1">echo</span> form_close<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="sy1">?&gt;</span><br />
&lt;/body&gt;<br />
&lt;/html&gt;</div>
</div>
<p>The output in the browser generated by this is view can be seen in figure 1. As CSS styling is not in the agenda of this article, I am not going to comment on it. The CSS file can be found with all source files <a href="http://yavkata.co.uk/weblog/wp-content/uploads/CodeIgniter_jQuery_Validation.rar">here</a>.<br />
<div id="attachment_190" class="wp-caption alignnone" style="width: 310px"><img src="http://yavkata.co.uk/weblog/wp-content/uploads/codeigniter_form-300x251.jpg" alt="codeigniter form view" title="codeigniter_form" width="300" height="251" class="size-medium wp-image-190" /><p class="wp-caption-text">Figure 1. The form generated by the view</p></div></p>
<h5 class="entry_subtitle">3.2 Setting up the Controller</h5>
<p>The first thing that needs to be done is setting up the appropriate controller object:</p>
<div class="codesnip-container" >
<div class="php codesnip" style="font-family:monospace;"><span class="kw2">&lt;?php</span><br />
<span class="kw2">class</span> Form <span class="kw2">extends</span> Controller <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">function</span> Form<span class="br0">&#40;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; parent<span class="sy0">::</span><span class="me2">Controller</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span><span class="me1">load</span><span class="sy0">-&gt;</span><span class="me1">helper</span><span class="br0">&#40;</span><span class="st_h">&#8216;form&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">function</span> index<span class="br0">&#40;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$data</span><span class="br0">&#91;</span><span class="st_h">&#8216;base&#8217;</span><span class="br0">&#93;</span> <span class="sy0">=</span> <span class="re0">$this</span><span class="sy0">-&gt;</span><span class="me1">config</span><span class="sy0">-&gt;</span><span class="me1">item</span><span class="br0">&#40;</span><span class="st_h">&#8216;base_url&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span><span class="me1">load</span><span class="sy0">-&gt;</span><span class="me1">view</span><span class="br0">&#40;</span><span class="st_h">&#8216;form_view&#8217;</span><span class="sy0">,</span> <span class="re0">$data</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw2">function</span> send<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span><span class="me1">load</span><span class="sy0">-&gt;</span><span class="me1">library</span><span class="br0">&#40;</span><span class="st_h">&#8216;form_validation&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span><span class="me1">form_validation</span><span class="sy0">-&gt;</span><span class="me1">set_error_delimiters</span><span class="br0">&#40;</span><span class="st_h">&#8216;&lt;div class=&quot;error&quot;&gt;&lt;p&gt;&#8217;</span><span class="sy0">,</span> <span class="st_h">&#8216;&lt;/p&gt;&lt;/div&gt;&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span><span class="me1">form_validation</span><span class="sy0">-&gt;</span><span class="me1">set_rules</span><span class="br0">&#40;</span><span class="st_h">&#8216;name&#8217;</span><span class="sy0">,</span> <span class="st_h">&#8216;Your name&#8217;</span><span class="sy0">,</span> <span class="st_h">&#8216;required|alpha_numeric|max_length[45]&#8216;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span><span class="me1">form_validation</span><span class="sy0">-&gt;</span><span class="me1">set_rules</span><span class="br0">&#40;</span><span class="st_h">&#8216;email&#8217;</span><span class="sy0">,</span> <span class="st_h">&#8216;Your email&#8217;</span><span class="sy0">,</span> <span class="st_h">&#8216;required|valid_email|max_length[45]&#8216;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span><span class="me1">form_validation</span><span class="sy0">-&gt;</span><span class="me1">set_message</span><span class="br0">&#40;</span><span class="st_h">&#8216;required&#8217;</span><span class="sy0">,</span> <span class="st_h">&#8216;Required field&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span><span class="me1">form_validation</span><span class="sy0">-&gt;</span><span class="me1">set_message</span><span class="br0">&#40;</span><span class="st_h">&#8216;max_length&#8217;</span><span class="sy0">,</span> <span class="st_h">&#8216;No more than 45 characters&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span><span class="me1">form_validation</span><span class="sy0">-&gt;</span><span class="me1">set_message</span><span class="br0">&#40;</span><span class="st_h">&#8216;valid_email&#8217;</span><span class="sy0">,</span> <span class="st_h">&#8216;Please enter a valid email&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span><span class="me1">form_validation</span><span class="sy0">-&gt;</span><span class="me1">set_message</span><span class="br0">&#40;</span><span class="st_h">&#8216;alpha_numeric&#8217;</span><span class="sy0">,</span> <span class="st_h">&#8216;Only letters and numbers are allowed here.&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="kw1">if</span> <span class="br0">&#40;</span><span class="re0">$this</span><span class="sy0">-&gt;</span><span class="me1">form_validation</span><span class="sy0">-&gt;</span><span class="me1">run</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">==</span> <span class="kw4">FALSE</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$data</span><span class="br0">&#91;</span><span class="st_h">&#8216;base&#8217;</span><span class="br0">&#93;</span> <span class="sy0">=</span> <span class="re0">$this</span><span class="sy0">-&gt;</span><span class="me1">config</span><span class="sy0">-&gt;</span><span class="me1">item</span><span class="br0">&#40;</span><span class="st_h">&#8216;base_url&#8217;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="re0">$this</span><span class="sy0">-&gt;</span><span class="me1">load</span><span class="sy0">-&gt;</span><span class="me1">view</span><span class="br0">&#40;</span><span class="st_h">&#8216;form_view&#8217;</span><span class="sy0">,</span> <span class="re0">$data</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#125;</span><br />
<span class="br0">&#125;</span><br />
<span class="coMULTI">/* End of file form.php */</span><br />
<span class="coMULTI">/* Location: ./system/application/controllers/form.php */</span><br />
<span class="sy1">?&gt;</span></div>
</div>
<p>This is a pretty generic and simple CodeIgniter controller consisting of a <strong>constructor</strong>, <strong>index</strong> function and a <strong>send</strong> function that will process the form later on. One thing to notice is that the <strong>Form</strong> helper is loaded in the constructor. The <strong>index</strong> function is the default function executed when the controller is called (unless a different function is specified in the URL). All we do in the <strong>index</strong> function in this case is load the <strong>base URL</strong> of our application from the <strong>config</strong> file so it can be passed to the <strong>view</strong> via the <strong>$data</strong> array. The <strong>send</strong> function is going to be the function called in the <strong>action</strong> attribute of the form.<br />
The <strong>send</strong> function loads the <strong>Form Validation</strong> class from the library and sets the rules for the corresponding form fields, specified by field name. The <strong>set_rules</strong> function takes three parameters:</p>
<ul>
<li>the field name as specified in your form</li>
<li>A &#8220;human&#8221; name for that field in case you want to store that in a language file (more on this <a href="http://codeigniter.com/user_guide/libraries/form_validation.html#translatingfn">here</a>)</li>
<li>the set of rules that will apply for the corresponding field (the full list of rules can be found <a href="http://codeigniter.com/user_guide/libraries/form_validation.html#rulereference">here</a>)</li>
</ul>
<p>If the validation fails (returns false), the controller returns the user to the form view again displaying the corresponding error messages.<br />
<div id="attachment_193" class="wp-caption alignnone" style="width: 310px"><img src="http://yavkata.co.uk/weblog/wp-content/uploads/ci_validation_form-300x251.jpg" alt="codeigniter validation form with errors" title="ci_validation_form" width="300" height="251" class="size-medium wp-image-193" /><p class="wp-caption-text">Figure 2. The form returned after failed validation</p></div></p>
<h5 class="entry_subtitle">4. jQuery validation</h5>
<p>A great way to validate a form on the client machine with jQuery is via a plug-in called <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">Validation</a>. This is how the implementation of this plug-in looks like:</p>
<div class="codesnip-container" >
<div class="javascript codesnip" style="font-family:monospace;">$<span class="br0">&#40;</span>document<span class="br0">&#41;</span>.<span class="me1">ready</span><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span><br />
&nbsp; &nbsp; $<span class="br0">&#40;</span><span class="st0">&quot;#myform&quot;</span><span class="br0">&#41;</span>.<span class="me1">validate</span><span class="br0">&#40;</span><span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; rules<span class="sy0">:</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw3">name</span><span class="sy0">:</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; required<span class="sy0">:</span><span class="kw2">true</span><span class="sy0">,</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alphanumeric<span class="sy0">:</span><span class="kw2">true</span><span class="sy0">,</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; maxlength<span class="sy0">:</span> 45<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#125;</span><span class="sy0">,</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; email<span class="sy0">:</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; required<span class="sy0">:</span> <span class="kw2">true</span><span class="sy0">,</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; email<span class="sy0">:</span> <span class="kw2">true</span><span class="sy0">,</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; maxlength<span class="sy0">:</span> 45<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#125;</span><span class="sy0">,</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; messages<span class="sy0">:</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="kw3">name</span><span class="sy0">:</span> <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; required<span class="sy0">:</span><span class="st0">&quot;It would be nice if I know who you are.&quot;</span><span class="sy0">,</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alphanumeric<span class="sy0">:</span><span class="st0">&quot;This field should not contain any funny characters&quot;</span><span class="sy0">,</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; maxlength<span class="sy0">:</span><span class="st0">&quot;My dissertation is shorter than your name <img src='http://yavkata.co.uk/weblog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Give me a nickname.&quot;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#125;</span><span class="sy0">,</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; email<span class="sy0">:</span> &nbsp;<span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; required<span class="sy0">:</span><span class="st0">&quot;Please enter your email address.&quot;</span><span class="sy0">,</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; email<span class="sy0">:</span><span class="st0">&quot;Oh, come on, this is not an email, you know that!&quot;</span><span class="sy0">,</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; maxlength<span class="sy0">:</span><span class="st0">&quot;Maximum characters allowed &#8211; 45&quot;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#125;</span><span class="sy0">,</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; invalidHandler<span class="sy0">:</span><span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#125;</span><span class="br0">&#41;</span><br />
<span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span><span class="co1">//document ready close</span></div>
</div>
<p>This way the user does not have to wait a trip to the server and back to understand he/she has entered something wrong.<br />
<div id="attachment_195" class="wp-caption alignleft" style="width: 310px"><img src="http://yavkata.co.uk/weblog/wp-content/uploads/jquery_validation2-300x251.jpg" alt="jQuery form validation example" title="jquery_validation2" width="300" height="251" class="size-medium wp-image-195" /><p class="wp-caption-text">Figure 3. Errors if nothing is submitted.</p></div> <div id="attachment_194" class="wp-caption alignleft" style="width: 310px"><img src="http://yavkata.co.uk/weblog/wp-content/uploads/jquery_validation-300x251.jpg" alt="jQuery form validation example" title="jquery_validation" width="300" height="251" class="size-medium wp-image-194" /><p class="wp-caption-text">Figure 4. Errors when the input is the wrong type</p></div></p>
<h5 class="entry_subtitle">5. Source files</h5>
<p>All source code files used in this example can be downloaded <a href="http://yavkata.co.uk/weblog/wp-content/uploads/CodeIgniter_jQuery_Validation.rar">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://yavkata.co.uk/weblog/php/secure-forms-with-codeigniter-and-jquery/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Apache URL rewriting and redirect</title>
		<link>http://yavkata.co.uk/weblog/server-side-technologies/apache-url-rewriting-and-redirect/</link>
		<comments>http://yavkata.co.uk/weblog/server-side-technologies/apache-url-rewriting-and-redirect/#comments</comments>
		<pubDate>Tue, 16 Feb 2010 02:19:38 +0000</pubDate>
		<dc:creator>Yavor Atanasov</dc:creator>
				<category><![CDATA[Server-side technologies]]></category>
		<category><![CDATA[Apache]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[redirect]]></category>
		<category><![CDATA[rewrite]]></category>

		<guid isPermaLink="false">http://yavkata.co.uk/weblog/?p=67</guid>
		<description><![CDATA[URL rewriting and redirecting helps web developers create websites that are more user and search engine friendly and even more secure. The URL is the pathway that leads the user (be it a human or a machine) to the valuable information your website has to offer. The longer and &#8220;dirtier&#8221; this pathway is, the more [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://yavkata.co.uk/weblog/wp-content/uploads/Apache_URL_mod_rewrite.png" alt="Apache URL mod_rewrite" title="Apache_URL_mod_rewrite" width="200" height="113" class="alignleft size-full wp-image-138" /><a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator">URL</a> rewriting and redirecting helps web developers create websites that are more user and search engine friendly and even more secure. The URL is the pathway that leads the user (be it a human or a machine) to the valuable information your website has to offer. The longer and &#8220;dirtier&#8221; this pathway is, the more difficult it is for your information to be discovered and reached. That is not something you would like to do to your website.</p>
<p>There are several scenarios in which you as a developer might want to use URL rewriting and redirecting. <span id="more-67"></span>You might need to:</p>
<ul>
<li>tidy up messy URLs which are the side effect of data intensive dynamic websites</li>
<li>temporarily redirect incoming requests due to maintenance</li>
<li>permanently redirect a certain request due to a changed location of a specific resource</li>
</ul>
<p>The Apache web server offers us an elegant and very powerful solution to URL manipulation in the face of <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html">mod_rewrite</a> module. It uses regular expressions to match any requested URL to the corresponding resource location on your server. It can be used on a per-server basis (via the httpd.conf) or on a per-directory basis (using .htaccess files). Per-server configuration is the recommended way (provided you have access to the server settings) mostly due to performance overhead when using .htaccess files (more on this <a href="http://httpd.apache.org/docs/2.2/howto/htaccess.html">here</a>). However, when you do not have direct access to your server .htaccess do the trick pretty well. Let&#8217;s have a look at how <strong>mod_rewrite</strong> would tackle the upper mentioned three scenarios.</p>
<h5 class="entry_subtitle">Messy URLs</h5>
<p>Dynamic website architectures by default come with a price &#8211; long URL paths containing variables and values that the server-side scripts need to get what the user requested.</p>
<p>Messy URL example: <strong>www.somewebsite.com/guitars.php?type=electric&amp;brand=esp&amp;year=2010</strong></p>
<p>That is what our web application needs to know to get to the needed information. However, that is something that the user does not care about and does not need to see or know. A much more visually appealing and easily remembered way of presenting the upper URL would be:</p>
<p>Tidy URL example: <strong>www.somewebsite.com/guitars/electric/esp/2010</strong></p>
<p>There are no special characters, no equal signs and no file extensions. It is more logical to the human eye and certainly more understandable to search engines. Now let&#8217;s see how Apache&#8217;s <strong>mod_rewrite</strong> can be used to map the tidy URL the user inputs to the &#8220;messy&#8221; URL your web application needs. All you need to do is create a .htaccess file in your base directory (or wherever the application is installed) and put the following magic code in it:</p>
<div class="codesnip-container" >
<div class="apache codesnip" style="font-family:monospace;"><span class="kw1">RewriteEngine</span> <span class="kw2">On</span><br />
<span class="kw1">RewriteRule</span> ^([a-z]+)/([a-z]+)/([a-z]+)/([<span class="nu0">0</span>-<span class="nu0">9</span>]{<span class="nu0">4</span>})$ /$1.php?type=$<span class="nu0">2</span>&amp;brand=$<span class="nu0">3</span>&amp;year=$<span class="nu0">4</span> [L]</div>
</div>
<p>The <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewriteengine">RewriteEngine</a> directive controls the status of the rewriting engine &#8211; whether it&#8217;s ON or OFF. The <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewriterule">RewriteRule</a> uses three arguments divided by space:</p>
<ul>
<li><em>pattern</em> &#8211; a regular expression to match the URL to be rewritten</li>
<li><em>substitution</em> &#8211; the location where the matched URL should be sent to</li>
<li><em>flags</em> &#8211; a set of options regarding the mod_rewrite operation (more on flags <a href="http://httpd.apache.org/docs/2.2/rewrite/rewrite_flags.html">here</a>)</li>
</ul>
<p>In our case the <strong>pattern</strong> part consists of &#8211; <strong><span class="highlight">^([a-z]+)/([a-z]+)/([a-z]+)/([0-9]{4})$</span></strong><br />
Let&#8217;s break it down:</p>
<p><strong><span class="highlight">^</span></strong> &#8211; this special character matches the beginning of the coming URL string. In our case this is <strong>www.somewebsite.com/</strong><br />
<strong><span class="highlight">[a-z]+</span></strong> &#8211; this regular expression matches any alphabetical string. In our case it matches <strong>guitars</strong>, <strong>electric</strong>, <strong>esp</strong>.<br />
<strong><span class="highlight">[0-9]{4}</span></strong> &#8211; this matches any combination of exactly 4 digits. We need this to match the year <strong>2010</strong>.<br />
Those regular expression segments are encapsulated with brackets <span class="highlight">()</span>. This way they can be back-referenced in the <strong>substitution</strong> argument using <strong>$1</strong>, <strong>$2</strong>, <strong>$3</strong>, <strong>$4</strong><br />
<strong><span class="highlight">$</span></strong> &#8211; this indicates the end of the string</p>
<p>The <strong>substitution</strong> argument in our RewriteRule directive is &#8211; <span class="highlight"><strong>/$1.php?type=$2&amp;brand=$3&amp;year=$4</strong></span>. The variables <span class="highlight"><strong>$1</strong></span>, <span class="highlight"><strong>$2</strong></span>, <span class="highlight"><strong>$3</strong></span>, <span class="highlight"><strong>$4</strong></span> are back-references to the pattern segments encapsulated with brackets and in our case they hold the values &#8211; <strong>guitars</strong>, <strong>electric</strong>, <strong>esp</strong>, <strong>2010</strong>.</p>
<p>The <strong>flag</strong> argument we are using is <span class="highlight"><strong>[L]</strong></span>. The L flag (&#8220;L&#8221; for last) tells the rewrite engine to stop processing further if the current rule is matched. More on the different flags you can use with <strong>mod_rewrite</strong> can be found on the <a href="http://httpd.apache.org/docs/2.2/rewrite/rewrite_flags.html">Apache mod_rewrite Flags</a> page.</p>
<h5 class="entry_subtitle">Temporary redirects due to maintenance</h5>
<p>Whenever a website needs to undergo a <strong>major</strong> maintenance procedure that would hinder its normal workings and possibly throw errors if someone tries to access it, it is recommended that the website is put offline until maintenance is finished. Putting a website offline requires informing its visitors why they cannot access it or parts of it so they know they can come back later. This is important because some of those visitors may be search engine crawlers and unless they are told to come back later, they will record the 404 errors your previously indexed URLs throw at them.</p>
<p>The elements of a temporary maintenance redirect with Apache are as follows:</p>
<ul>
<li>Customized maintenance message page</li>
<li>A .htaccess file with directives to redirect all incoming requests to the maintenance page and throw the necessary http status code</li>
</ul>
<p>This is how the .htaccess might look like:</p>
<div class="codesnip-container" >
<div class="apache codesnip" style="font-family:monospace;"><span class="kw1">RewriteEngine</span> <span class="kw2">On</span><br />
<span class="kw1">RewriteCond</span> %{REMOTE_ADDR} !^11\.111\.11\.111<br />
<span class="kw1">RewriteRule</span> ^(.*)$ maintenance.php [L]</div>
</div>
<p>The <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond">RewriteCond</a> directive defines a condition under which the rewrite should be executed and it should be placed before the RewriteRule line. In our case we use the RewriteCond with the server variable <strong>%{REMOTE_ADDR}</strong> which represents the IP address from which the website is accessed. Thus our condition tells Apache to redirect all requests except the ones coming from IP 11.111.11.111 (this could be the IP address of the machine that is used for testing the website). All requests coming from other IP addresses are redirected to our maintenance.php page.</p>
<p>Another important element of the redirect is the <strong>http status code</strong> that has to be sent with the maintenance message. That&#8217;s because the maintenance message is important for people, but the search engine crawlers understand the http status code in the header. Basically there are two options from the list of <a href="http://www.google.com/support/webmasters/bin/answer.py?hl=en&amp;answer=40132">http status codes</a>:</p>
<ul>
<li><strong>302</strong> (moved temporarilly) &#8211; it basically tells the requestor that the server responds with a resource from a different location, but the original location should be kept for future access</li>
<li><strong>503</strong> (service unavailable) &#8211; this tells the user agent that the server is unavailable due to overload or maintenance and it should come back later</li>
</ul>
<p>I personally prefer the <strong>503</strong> status code because it describes better the essence of the maintenance state. The http status code can be sent via the header php function in the maintenance.php file. Example:</p>
<div class="codesnip-container" >
<div class="php codesnip" style="font-family:monospace;"><span class="sy1">&lt;?</span><br />
<a href="http://www.php.net/header"><span class="kw3">header</span></a><span class="br0">&#40;</span><span class="st0">&quot;HTTP/1.1 503 Service Unavailable&quot;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="kw1">echo</span> <span class="st0">&quot;Server is down for maintenance. Please come back in an hour.&quot;</span><span class="sy0">;</span><br />
<span class="sy1">?&gt;</span></div>
</div>
<h5 class="entry_subtitle">Permanent redirect due to changed location</h5>
<p>Although frequent change of resource locations is not recommended, sometimes it is a needed action. In that case one needs to make sure that the user&#8217;s bookmarks of the old location will still work, and also inform the user agent that the change is permanent via an appropriate http status code. That http code is <strong>301</strong> (moved permanently). It tells the user agent to update its records of the location of that specific resource.<br />
Let&#8217;s say we want to redirect all requests for <strong>http://somewebsite.com/old.php?var=value</strong> to <strong>http://somewebsite.com/new.php?newvar=value</strong>. Then the .htaccess file in this case might look like this:</p>
<div class="codesnip-container" >
<div class="apache codesnip" style="font-family:monospace;"><span class="kw1">RewriteEngine</span> <span class="kw2">On</span><br />
<span class="kw1">RewriteCond</span> %{QUERY_STRING} var=(value)<br />
<span class="kw1">RewriteRule</span> ^old\.php$ http://somewebsite.com/new.php?newvar=%1 [R=<span class="nu0">301</span>]</div>
</div>
<p>Again the RewriteCond directive is used, this time with the <strong>%{QUERY_STRING}</strong> variable which represents the GET arguments passed via the URL. This way any request to the <strong>/old.php?var=value</strong> will be redirected to <strong>/new.php?newvar=value</strong>. That, however, is a little stiff redirect since it will match only one specific variable name and value. We can make the redirect a lot more flexible using a short but powerful regular expression:</p>
<div class="codesnip-container" >
<div class="apache codesnip" style="font-family:monospace;"><span class="kw1">RewriteEngine</span> <span class="kw2">On</span><br />
<span class="kw1">RewriteCond</span> %{QUERY_STRING} ^[^=]+([^&amp;]+) [OR] !%{QUERY_STRING}<br />
<span class="kw1">RewriteRule</span> ^old\.php$ http://somewebsite.com/new.php?newvar=%1 [R=<span class="nu0">301</span>]</div>
</div>
<p>This RewriteCond will match any call to the old.php page regardless of the name and value of the arguments passed. It will also match a call to the old.php page without any GET arguments supplied.<br />
The flag argument of the RewriteRule directive is [R=301]. The R flag (&#8220;R&#8221; for redirect) redirects the request with the supplied http status code.</p>
<p>Additional information:</p>
<ul>
<li><a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewriterule">RewriteRule</a></li>
<li><a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond">RewriteCond</a></li>
<li><a href="http://www.google.com/support/webmasters/bin/answer.py?hl=en&amp;answer=40132">HTTP Status Codes</a></li>
<li><a href="http://httpd.apache.org/docs/2.2/rewrite/rewrite_flags.html">Apache mod_rewrite Flags</a></li>
<li><a href="http://httpd.apache.org/docs/2.2/howto/htaccess.html">.htaccess files</a></li>
<li><a href="http://www.yourhtmlsource.com/sitemanagement/urlrewriting.html">URL rewriting (www.yourhtmlsource.com)</a></li>
<li><a href="http://en.wikipedia.org/wiki/URL_redirection">URL redirection (Wikipedia)</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://yavkata.co.uk/weblog/server-side-technologies/apache-url-rewriting-and-redirect/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
