<?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>Strawberrysoup Blog &#38; News &#187; Labs</title>
	<atom:link href="http://blog.strawberrysoup.co.uk/category/labs/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.strawberrysoup.co.uk</link>
	<description>Creative web and design consultants in Chichester, Bournemouth and London</description>
	<lastBuildDate>Fri, 27 Aug 2010 13:59:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Building Location Aware Sites with Geo-IP</title>
		<link>http://blog.strawberrysoup.co.uk/2010/01/14/building-location-aware-sites-with-geo-ip/</link>
		<comments>http://blog.strawberrysoup.co.uk/2010/01/14/building-location-aware-sites-with-geo-ip/#comments</comments>
		<pubDate>Thu, 14 Jan 2010 11:13:36 +0000</pubDate>
		<dc:creator>Stuart</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Labs]]></category>
		<category><![CDATA[Strawberrysoup]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://blog.strawberrysoup.co.uk/?p=685</guid>
		<description><![CDATA[One of the most powerful features of the internet is the power to connect and share from opposite poles of the earth; no longer does your geographic location affect who you talk to or what you read. Companies that were once specific to a certain location now have access to the whole online market; with - <a href="http://blog.strawberrysoup.co.uk/2010/01/14/building-location-aware-sites-with-geo-ip/"> Read more.</a>]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.strawberrysoup.co.uk%2F2010%2F01%2F14%2Fbuilding-location-aware-sites-with-geo-ip%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.strawberrysoup.co.uk%2F2010%2F01%2F14%2Fbuilding-location-aware-sites-with-geo-ip%2F&amp;source=strawberrysoup&amp;style=normal&amp;service=bit.ly" height="61" width="50" /><br />
			</a>
		</div>
<p>One of the most powerful features of the internet is the power to connect and share from opposite poles of the earth; no longer does your geographic location affect who you talk to or what you read. Companies that were once specific to a certain location now have access to the whole online market; with 1.4 billion people currently connected it opens up whole new revenue streams.</p>
<p><a href="http://blog.strawberrysoup.co.uk/wp-content/uploads/2010/01/Screen-shot-2010-01-14-at-11.10.25.png"><img class="alignleft size-full wp-image-687" title="Screen shot" src="http://blog.strawberrysoup.co.uk/wp-content/uploads/2010/01/Screen-shot-2010-01-14-at-11.10.25.png" alt="" width="234" height="69" /></a>The final product will simply tell you where it thinks you are and allows you to set a new default location.</p>
<p>However with this global access there becomes another problem, not all data is global; the weather in London is most likely different to the current weather in New York. What about shopping? Currencies often change between borders and tax makes things even more complex. There have been countless solutions to this problem; the most glaringly obvious is a splash page or a form asking for the users location.</p>
<p>There’s nothing wrong with these solutions but there’s also nothing special about them, just more distractions and obstacles between the user and their final destination. In this tutorial we’ll be building a simple function and demo which solves this problem and should be easily pluggable into any new or existing project.</p>
<h2>Location Uses?</h2>
<p>As previously mentioned there are several uses for location based sites; simply looking through the days history in your favourite browser will probably reveal several sites that have asked for your location before, whether it be for simple data collection or put to use to give you more relevant information; local news, weather, messages from people close by or maybe to warn you about bad traffic in your area.</p>
<p>How many times in the last month have you entered your address or country? Whenever you&#8217;ve bought anything online or registered to a new site you&#8217;ve doubtless had to put in a variety of location based answers.</p>
<h2>So what is GeoIP?</h2>
<p>GeoIP is the common name given to the technique of determining a visitors Geographical location based on their visiting IP. It requires a database which pairs IP blocks to a country and/or city, these are available from several places online however for this tutorial to work than you will have to use the IPinfoDB SQL, available and updated monthly at http://www.ipinfodb.com/ip_database.php we’ll be specifically using the country only version with only one table, this is for performance and simplicity reasons &#8211; once you have the tutorial working with the country only version, modifying the script to work with the other versions should be simple. So go ahead and create a blank MySQL database and import the SQL straight into it.</p>
<p><strong>1. Set up project</strong></p>
<p>Create a blank index.php somewhere on your PHP enabled server and write the following lines into it, replacing all the variables to whatever username, password and database name you have chosen to use.</p>
<pre>&lt;?php
mysql_connect('localhost', '%USERNAME%', '%PASSWORD%');
mysql_select_db('%DBNAME%');
?&gt;</pre>
<p><strong>2. Building the detection script</strong></p>
<p>The first actual fresh code we need to do write is the script which detects the users location &#8211; surprisingly this is actually quite simple and straightforward once you have a simple database to query. All the function is going to do is query the database for the closest result and then return the country name.</p>
<pre>function detect_location($ip=false) {
 if(!$ip) $ip = $_SERVER['REMOTE_ADDR'];
 $parts = explode('.', $ip);
 $iph = (($parts[0]*256+$parts[1])*256+$parts[2])*256 + $parts[3];
 $result = mysql_query('SELECT country_name FROM `ip_group_country` where `ip_start` &lt;= '.$iph.'order
by ip_start desc limit 1');
 while ($row = mysql_fetch_assoc($result)) {
 return $row['country_name'];
 }
}
?&gt;</pre>
<p>So what does all of this do? Well let’s go through it bit by bit:</p>
<pre>if(!$ip) $ip = $_SERVER['REMOTE_ADDR'];</pre>
<p>This sets the first $ip to the visitors IP if the function receives no parameter</p>
<pre>$parts = explode('.', $ip);
$iph = (($parts[0]*256+$parts[1])*256+$parts[2])*256 + $parts[3];</pre>
<p>This bit is the most confusing bit, the first line splits the IP into it’s four sections, the second line put’s it into a format usable for the database.</p>
<p>After that the rest is a simple SQL query to get the first result which matches the IP closest and then returns the country name.</p>
<p><strong>3. Displaying results to the user</strong></p>
<p>This is where we actually start using our function and giving it a purpose, we’ll start simple and just display where we think the user is coming from, underneath the PHP block write the following below:</p>
<pre>&lt;?php
$country = detect_location();
?&gt;
&lt;h1&gt;Are you from: &lt;?=$country?&gt;&lt;/h1&gt;</pre>
<p><strong>4. Is it wrong?</strong></p>
<p>Now you can visit your file in a browser and see if it guesses your location is correct; it’s wrong? Well if you run the file locally then it will always be wrong because it detects your local IP (127.0.0.1 or ::1). So what can you do? Short of testing it by placing it on a public machine elsewhere we can modify our code to force an IP:</p>
<pre>Change $country = detect_location(); to read $country = detect_location('74.125.45.100');.</pre>
<p>Testing it again should return &#8220;United States&#8221; &#8211; this is because the IP is one of Googles US servers IP&#8217;s. From here on we could just carry on but from seeing that error it exposes a simple problem; as with most programming things it will not be 100% correct every time. So how can we fix this? Well in the unlikely event it is wrong we can give the user some way of changing it. Modify the current code to match that of below and afterwards it will be explained.</p>
<pre>&lt;?php
session_start();
mysql_connect(‘localhost’, ‘%USERNAME%’, ‘%PASSWORD%’);
mysql_select_db(‘%DBNAME%’);
function detect_location($ip=false) {
 if(!$ip) $ip = $_SERVER['REMOTE_ADDR'];
 $parts = explode('.', $ip);
 $iph = (($parts[0]*256+$parts[1])*256+$parts[2])*256 + $parts[3];
 $result = mysql_query('SELECT country_name FROM `ip_group_country` where `ip_start` &lt;= '.$iph.'order
by ip_start desc limit 1');
 while ($row = mysql_fetch_assoc($result)) {
 return $row['country_name'];
 }
}
if($_POST &amp;&amp; $_POST[‘country’]) {
 $_SESSION[‘country’] = $_POST[‘country’];
}
$country = (isset($_SESSION[‘country’])) ? $_SESSION[‘country’] :
detect_location($_SERVER['REMOTE_ADDR']);
?&gt;
&lt;h1&gt;Are you from: &lt;?=$country?&gt;&lt;/h1&gt;
&lt;p&gt;Change Region:
&lt;form action="" method="post"&gt;
 &lt;select name="country"&gt;
 &lt;option value="United Kingdom"&gt;United Kingdom&lt;/option&gt;
 &lt;option value="France"&gt;France&lt;/option&gt;
 &lt;/select&gt;
 &lt;input type="submit" value="Go" /&gt;
&lt;/p&gt;</pre>
<p>For now there is only the option to change your country to either the UK or France, but it should be easily changeable to list all countries &#8211; either by finding the select HTML from somewhere online or plugging it into a database table of all countries<strong> </strong></p>
<p><strong>4a &#8211; Making sense of it all</strong></p>
<p>As you can tell the size of the code has suddenly doubled, so it’s probably time to inspect what is actually happening in each section to dispel all claims of magic. Each addition is documented below in enough detail for you to understand it&#8217;s purpose.</p>
<pre>session_start();</pre>
<p>This tells the PHP engine that our script will be using sessions so needs to give the visitor a session to use, or retrieve their current session off the filesystem.</p>
<pre>if($_POST &amp;&amp; $_POST[‘country’]) {
 $_SESSION[‘country’] = $_POST[‘country’];
}</pre>
<p>This detects if a new country name has been submitted to the page via POST, if this occurs than the data is saved into a session &#8211; if this wasn&#8217;t done than the user would have to tell the site where they are for every page request which would be extremely bad usability.</p>
<pre>$country = (isset($_SESSION[‘country’])) ? $_SESSION[‘country’] :
detect_location($_SERVER['REMOTE_ADDR']);</pre>
<p>To those that have not seen a ternary if statement in PHP this may seem like a daunting piece of code however once explained it&#8217;s actually very simple. In PHP as well as a lot of other C based languages you can write single line if/else statements using something called a ternary statement. The syntax is as follows:</p>
<pre>(expression) ? true : false</pre>
<p>So applying that to our code above gives the explanation; first it checks to see if $_SESSION['country'] is set, if it is than $country is set to contain the sessions value, if not than it is retrieved out of the database.</p>
<p>Under the old &lt;h1&gt; there’s a form in which the important things to note is that the action is set to blank so it submits to whatever URL you are on and that the method is set to post. Inside the form there is only a select box which is where the visitor can choose what country they are in.</p>
<p><strong>5. Test, Play, Experiment</strong></p>
<p>After typing all of that above, fire up the page in your favourite browser and test the new drop down out; then make sure it saves when you refresh the page. It works? Finally. Now that this all works you should hopefully have enough basic knowledge about GeoIP to build it into a new project and even change the script to do some even more amazing things.</p>
<p><a href="http://blog.strawberrysoup.co.uk/wp-content/uploads/2010/01/Screen-shot-2010-01-14-at-11.11.541.png"><img class="alignleft size-full wp-image-690" title="Screen shot" src="http://blog.strawberrysoup.co.uk/wp-content/uploads/2010/01/Screen-shot-2010-01-14-at-11.11.541.png" alt="" width="634" height="315" /></a></p>
<p>At only 28 lines of code you can see how simple it is to build such useful functionality.</p>
<h2>Online API’s</h2>
<p>If you don’t have access to a SQL database or don’t want to host the database locally, IPinfoDB hosts a simply web API for submitting an IP and getting back it’s information in a variety of formats including JSON and XML. The downside of this is it means you are reliant on their servers being online 100% of the time and also that they keep the service available and free. The upside though is that all maintenance is done by them so you don’t have to update your IP tables every month or so. For documentation on this API documentation is available at: http://www.ipinfodb.com/ip_location_api.php The easiest way to use this is with the simple code below:</p>
<pre>&lt;?php
 session_start();
 if(!isset($_SESSION['country'])) {
 $file = file_get_contents('http://ipinfodb.com/ip_query.php?ip='.$_SERVER['REMOTE_ADDR'].
'&amp;format=json');
 $data = json_decode($file);
 $_SESSION['country'] = $data['CountryName'];
 }
 $country = $_SESSION['country'];
 echo 'You live in: '.$country;
?&gt;</pre>
<p>This also saves the users location in a session so that you don’t have to keep sending requests to the API’s server &#8211; this has a number of advantages; speeding up your page loads, lowering bandwidth usage and decreasing the chance of ever going over any fair usage policy.</p>
<h2>HTML5 Geolocation API</h2>
<p>One of the recent additions to the HTML5 specification is a new javascript API for retrieving geographical information about the visitor, this includes the ability to gain coordinates for the visitor but also to watch the visitors location for changes. Currently it is already supported in Firefox 3.5 as well as a similar available for the Google Gears API. Being able to retrieve more precise information from the visitor (especially on the client-side) could lead to some interesting uses and web applications. More information and documentation on it’s features can be found at: http://www.w3.org/TR/geolocation-API/</p>
<p>Although there aren’t a lot of public examples of this new HTML5 API, it’s only time before people start creating games played on smartphones which interact with each others position or some other imaginative use.</p>
<h2>Sites Using GeoIP</h2>
<p>The newly launched irregular choice store uses GeoIP to display localised stock lists and prices at <a href="http://shop.irregularchoice.com" target="_blank">http://shop.irregularchoice.com</a></p>
<p>GeoIP isn’t just restricted to PHP and conventional HTML;  an example of GeoIP in a flex app using python exists at: <a href="http://blog.pyamf.org/archives/geoip-example" target="_blank">http://blog.pyamf.org/archives/geoip-example</a></p>
<h2>Resources</h2>
<p>If your using Lighttpd then you can use mod_geoip to handle all the logic for you enabling you to focus on what you do with a visitors location. You can find a tutorial at: <a href="http://www.cyberciti.biz/tips/linux-lighttpd-install-mod_geoip-tutorial.html" target="_blank">http://www.cyberciti.biz/tips/linux-lighttpd-install-mod_geoip-tutorial.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.strawberrysoup.co.uk/2010/01/14/building-location-aware-sites-with-geo-ip/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Dynamic CSS &#8211; Creating Time Sensitive Sites</title>
		<link>http://blog.strawberrysoup.co.uk/2010/01/07/dynamic-css-creating-time-sensitive-sites/</link>
		<comments>http://blog.strawberrysoup.co.uk/2010/01/07/dynamic-css-creating-time-sensitive-sites/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 16:32:20 +0000</pubDate>
		<dc:creator>Stuart</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Labs]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://blog.strawberrysoup.co.uk/?p=667</guid>
		<description><![CDATA[Create subtle CSS changes to your site based on time and date In todays modern web design environment it takes more and more to attract visitors visually, and even more to make them keep coming back. Of course this mostly depends on content as there has to be a purpose to the visit, however small - <a href="http://blog.strawberrysoup.co.uk/2010/01/07/dynamic-css-creating-time-sensitive-sites/"> Read more.</a>]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.strawberrysoup.co.uk%2F2010%2F01%2F07%2Fdynamic-css-creating-time-sensitive-sites%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.strawberrysoup.co.uk%2F2010%2F01%2F07%2Fdynamic-css-creating-time-sensitive-sites%2F&amp;source=strawberrysoup&amp;style=normal&amp;service=bit.ly" height="61" width="50" /><br />
			</a>
		</div>
<p><strong>Create subtle CSS changes to your site based on time and date</strong></p>
<div id="attachment_672" class="wp-caption alignleft" style="width: 310px"><a href="http://blog.strawberrysoup.co.uk/wp-content/uploads/2010/01/Screen-shot-2010-01-07-at-16.37.03.png"><img class="size-medium wp-image-672" title="Screen shot 2010-01-07 at 16.37.03" src="http://blog.strawberrysoup.co.uk/wp-content/uploads/2010/01/Screen-shot-2010-01-07-at-16.37.03-300x233.png" alt="" width="300" height="233" /></a><p class="wp-caption-text">Oasis Overland uses time sensitive stylesheets</p></div>
<p>In todays modern web design environment it takes more and more to attract visitors visually, and even more to make them keep coming back. Of course this mostly depends on content as there has to be a purpose to the visit, however small subtle details to the site can make any visitor become excited.</p>
<p>In this tutorial, you will create a site that changes it’s background based on the time a person visits the site, afterwards you should have the knowledge to adapt the script to be based on any other data you want to use.</p>
<p>All server-side examples in this tutorial will be based on PHP, so make sure you have a working test environment with PHP5 enabled. If you are using any other server-side scripting tool it is likely there will be a guide to accomplish a similar effect online; however reading through this guide you will likely recognise similar syntax and functions allowing you to convert it to the language you’re using.</p>
<p><strong>Opening the Folders</strong></p>
<p>Included <a href="http://blog.strawberrysoup.co.uk/wp-content/uploads/2010/01/dynamic_css.zip" target="_blank">in this download</a> is a folder called dynamic_css which contains all of the base files needed to complete this project. Move the folder into your testing servers root directory. Open the folder in your preferred IDE and then view index.php in a browser. If you’ve got PHP enabled and everything was copied successfully then you should see a basic white page with a header, navigation on the left and lorem ipsum on the right; it’s now time to start the dynamic styles.</p>
<p><strong>PHP Sunsets and Sunrises</strong></p>
<p>Using PHP to retrieve and make decisions based on time has it’s advantages and disadvantages. The largest disadvantage is the fact that PHP can’t access the users computer time and can only get the time of the server, the advantage however is that PHP has a large set of functions that make dealing with time that little less painfull. If you open up index.php, before the start &lt;html&gt; tag type the following PHP. Afterwards I will explain the key parts of the script.</p>
<pre>&lt;?php
 $time = date('G');
 $sunrise = date_sunrise(time(), SUNFUNCS_RET_DOUBLE);
 $sunset = date_sunset(time(), SUNFUNCS_RET_DOUBLE) + 1;
 if($time &gt;= $sunrise &amp;&amp; $time &lt; $sunrise + 2) $style = 'sunrise';
 elseif($time &gt;= $sunrise + 2 &amp;&amp; $time &lt; $sunset) $style = 'day';
 elseif($time &gt;= $sunset &amp;&amp; $time &lt; $sunset + 2) $style = 'sunset';
 else $style = 'night';
?&gt;</pre>
<p>Lines 2 &#8211; 4 set three variables; $time is set to the current hour, <em>$sunrise</em> is set to the sunrise time for today and <em>$sunset</em> is set to one hour later than the sunset time (from my experience, official sunset times start an hour or two before what most people would call sunset starts).</p>
<p>Lines 5 &#8211; 8 runs a set of standard if statement to determine which style to show; sunrise, day, sunset or night, this is then set to the variable <em>$style</em>. This can now be used whenever a reference to the time of day is needed, as you will be shown below.</p>
<p><strong>Dynamic CSS Techniques; One, Two and Three</strong></p>
<p>There are three main ways of achieving dynamic CSS &#8211; which one you use depends on several factors; the amount of styles that change per data, amount of style sheets that get loaded into the page and the amount of customisation you have on your server.</p>
<p><strong>Setting a body id/class</strong></p>
<p>The most popular method of using dynamic CSS is to set the body id or class of the page depending on the styles needed. The advantages of this is that no server changes need to be made, you can use the same id/class across style sheets with no extra code and it’s easy to quickly prototype and debug. The disadvantage of this is that you can only use pre-defined constants, because of this you can’t have random colour pallates using this method.</p>
<p><strong>Including style sheets</strong></p>
<p>The second most popular method is to include extra style sheets depending on which styles you need, this can be beneficial when a lot of styles change depending on what is needed; this stops the stylesheet having to include styles for all other posible states of the site together. The disadvantages is that you have to create a stylesheet per state, this can be a large hassle if you are going to have a lot of different styles, it also inherits the flaw of not being able to access the data in the style sheet.</p>
<p><strong>PHP in the style sheet</strong></p>
<p>This approach can be done in several ways, when used successfully and appropiately this can create the largest amount of freedom with data being able to be directly accessed in the style sheet meaning there is no limit to the amount of states possible. The disadvantages is that if you want your style sheets to still have the .css file extension you need to customise the server, this also means you lose the portability of the style sheet. The other option is to use .php as the CSS extension. Another disadvantage is that you are limited to having all the rules in one file without having to duplicate and re-process the PHP.</p>
<p><strong>Setting a body ID</strong></p>
<p>In our example there are only a few things changing per state and there are only 4 states, based on the advantages and disadvantages outlined above, setting a body id is probably the best way of achieving the effect.</p>
<p>Change the &lt;body&gt; tag to be the following:</p>
<pre>&lt;body id="&lt;?=$style?&gt;"&gt;</pre>
<p>Then open base.css and add the following to the end of the file.</p>
<pre>/********** TIME SENSITIVE CSS **********/</pre>
<pre>#sunset {
background: url('../images/sunset.jpg') repeat-x #BE7001;
}
</pre>
<pre>#sunrise {
background: url('../images/sunrise.jpg') repeat-x #EFC501;
}</pre>
<pre>#day {
background: url('../images/day.jpg') repeat-x #0A6FBF;
}</pre>
<pre>#night {
background: url('../images/night.jpg') repeat-x #00123A;
}</pre>
<p>Open your page in a browser now and admire the scenery depending on what time of day it is.</p>
<p><strong>Including style sheets</strong></p>
<p>Including style sheets is another simple yet effect method, the practice involves having a separate style sheet for each state. To adapt the current site to use this method create 4 style sheets called, sunset.css, sunrise.css, day.css and night.css. Place the appropriate code for each state in it&#8217;s file, then remove the id on the body tag and instead place the below code in the &lt;head&gt; tag.</p>
<pre>&lt;link rel="stylesheet" href="css/&lt;?=$style?&gt;.css" type="text/css" media="screen" charset="utf-8" /&gt;</pre>
<p><strong>PHP in the style sheet</strong></p>
<p>Out of the three methods outlined this one is by far the most flexible and powerful however also requires the most work so if a stage doesn&#8217;t work for you go back and repeat again; if it still isn&#8217;t working as it should then a quick search online will normally end up in a solution to the same problem someone else had.</p>
<p><strong>Setting .css to be run as php</strong></p>
<p>This is a matter of personal opinion however, I feel that having a .css extension helps define what an external asset is doing; this stage isn&#8217;t required so if you don&#8217;t mind having css with the .php ending or your server doesn&#8217;t allow you to make the following changes then skip this step.</p>
<p>Create a .htaccess file in the root of your site, place the following line in it:</p>
<pre>AddHandler application/x-httpd-php .css</pre>
<p>This sets PHP to handle all files with a .css extension, allowing you to place php in a .css file as if it were exactly the same as a .php file. If it fails to do anything at first, restart apache and see if that solves the problem.</p>
<p><strong>Setting the Content-Type and Using the PHP</strong></p>
<p>The most important thing to do when using dynamic CSS is to stop PHP setting the content-type header as text/html, you need your css files to be sent to the browser with the content-type text/css. To do this place the following line at the top of base.css (or base.php if you didn&#8217;t complete the previous step).</p>
<pre>&lt;?php header('Content-Type: text/css'); ?&gt;</pre>
<p>To get the background to change now place this just below the line you just wrote at the top (you can remove all the PHP from the index.php):</p>
<pre>&lt;?php
 $time = date('G');
 $sunrise = date_sunrise(time(), SUNFUNCS_RET_DOUBLE);
 $sunset = date_sunset(time(), SUNFUNCS_RET_DOUBLE) + 1;
 if($time &gt;= $sunrise &amp;&amp; $time &lt; $sunrise + 2) $style = 'url(../images/sunrise_bg.jpeg) repeat-x orange';
 elseif($time &gt;= $sunrise + 2 &amp;&amp; $time &lt; $sunset) $style = 'url(../images/day_bg.jpeg) repeat-x blue';
 elseif($time &gt;= $sunset &amp;&amp; $time &lt; $sunset + 2) $style = 'url(../images/sunset_bg.jpeg) repeat-x black';
 else $style = 'url(../images/night_bg.jpeg) repeat-x black';
?&gt;
body {
 background: &lt;?=$style?&gt;;
}</pre>
<p>Opening the page in a browser should now show you a background simulating the great outdoors.</p>
<p><strong>The equivalent in javascript</strong></p>
<p>PHP isn&#8217;t the only way to add dynamic elements in your sites, javascript has been the raw base to site dynamics for years. Of the three methods above the first two will work fine in javascript with adaptations. Javascript has a few disadvantages; there&#8217;s a delay between page load and the new styles, javascript is also notorious for browser differences and it of course requires javascript</p>
<p>Javascript doesn&#8217;t have the same resources as PHP and so can&#8217;t provide sunrise and sunset times so in the examples below the state will be statically set to &#8216;day&#8217;.</p>
<p><strong>Setting a body id</strong></p>
<pre>var state = 'day';
document.getElementsByTagName('body')[0].id = state;</pre>
<p>A general breakdown of the code above is that it assigns the variable state a value of &#8216;day&#8217;, the second line then starts by selecting the document, finds all the elements with the tag name body (should always be just one) and then gives the first ( 0 nth element) the id of state.</p>
<p><strong>Including extra style sheets</strong></p>
<pre>var state = 'day';
var cssFile = 'css/' + state + '.css';
var link = document.createElement('link');
link.setAttribute('href', cssFile);
document.getElementsByTagName('head')[0].appendChild(link);</pre>
<p><strong>Enjoy and Explore</strong></p>
<p>Based on the three PHP methods demoed here there are a llimitless amount of different ways you can make your CSS dynamic, if you need some ideas though just see the taking it further boxout for more info.</p>
<p><strong>Taking it Further</strong></p>
<p>Dynamic CSS isn’t restricted to simple time and date manipulations. Any data that your server or the clients browser can access can be used. Whether it&#8217;s pre-determined states such as seasons or  based on data hosted elsewhere, a few extra ideas are below.</p>
<p><em>1) Location</em> &#8211; Retrieving the visitors location is a tricky thing although there are several popular libraries and snippets readily available to make things easier. Mozilla is also pioneering the methods in which a server and site can detect a users location. Having the background change to compliment your location could be an easy way to make your site more localised.</p>
<p><em>2) Weather</em> &#8211; Having your sites background change depending on the weather could add function as well as design to a site, visitors to a local harbour could quickly determine the current weather or water height before even getting to the page.<br />
RSS Feeds &#8211; Easily accessible and retrievable RSS feeds now span the spectrum of content on the web, colour palettes, political data, surveys and pretty much anything you could want is probably already in RSS format.</p>
<p><em>3) Local site data </em>- If your site has dynamic content why not compliment it with some dynamic styles. If you have a blog then you could have the background represent the category which was last blogged about.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.strawberrysoup.co.uk/2010/01/07/dynamic-css-creating-time-sensitive-sites/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
