<?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>Tortoise IT &#187; PHP</title>
	<atom:link href="http://www.sean-barton.co.uk/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sean-barton.co.uk</link>
	<description>by Sean Barton, a freelance PHP website developer in Crewe, Cheshire</description>
	<lastBuildDate>Tue, 31 Jan 2012 17:34:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Converting any number to a Currency (or 2 decimal places)</title>
		<link>http://www.sean-barton.co.uk/2009/05/converting-any-number-to-a-currency-or-2-decimal-places/</link>
		<comments>http://www.sean-barton.co.uk/2009/05/converting-any-number-to-a-currency-or-2-decimal-places/#comments</comments>
		<pubDate>Fri, 29 May 2009 15:31:56 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Time Savers]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Convert Currency]]></category>
		<category><![CDATA[Converting Currency]]></category>

		<guid isPermaLink="false">http://www.sean-barton.co.uk/?p=287</guid>
		<description><![CDATA[Yes it sounds fairly elementary doesn&#8217;t it&#8230; yet I can&#8217;t find a PHP function to just do it? If, like me, you store your currency values in your database as integers (don&#8217;t ask why, I just do) then you need to multiply by 100 on the way in and divide by 100 on the way out. The obvious problem (or maybe not so obvious) is that when multiplying a number 100.1 is different to 100.10 and therefore the former needs to be converted to 100.10 for the resultant number to be correct. The following function simply does that whilst checking &#8230; <a class="continue_reading" href="http://www.sean-barton.co.uk/2009/05/converting-any-number-to-a-currency-or-2-decimal-places/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Yes it sounds fairly elementary doesn&#8217;t it&#8230; yet I can&#8217;t find a PHP function to just do it?</p>
<p>If, like me, you store your currency values in your database as integers (don&#8217;t ask why, I just do) then you need to multiply by 100 on the way in and divide by 100 on the way out.</p>
<p>The obvious problem (or maybe not so obvious) is that when multiplying a number 100.1 is different to 100.10 and therefore the former needs to be converted to 100.10 for the resultant number to be correct.</p>
<p>The following function simply does that whilst checking for the occurence of a decimal place and concatenating .00 in that situation.</p>
<pre>function convert_to_currency($num) {
    if (strpos($num, '.') == false) {
        $num = $num . '.00';
    } else {
        $num = sprintf("%01.2f", (float)$num);
    }
    return $num;
}</pre>
<p>This should reliably format the number ready to be manipulated for either a database or to be directly output.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sean-barton.co.uk/2009/05/converting-any-number-to-a-currency-or-2-decimal-places/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Turning an Array or Object into XML using PHP</title>
		<link>http://www.sean-barton.co.uk/2009/03/turning-an-array-or-object-into-xml-using-php/</link>
		<comments>http://www.sean-barton.co.uk/2009/03/turning-an-array-or-object-into-xml-using-php/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 14:57:58 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Plugins]]></category>
		<category><![CDATA[Time Savers]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Wordpress]]></category>
		<category><![CDATA[Object]]></category>
		<category><![CDATA[PHP Array]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.sean-barton.co.uk/?p=241</guid>
		<description><![CDATA[I have read a fair few tutorials written by others using classes and DOM functions to create XML from arrays. But what happens if you have an older PHP installation or prefer to keep things really simple as I do. The following function declarations generate an XML string from an associative array. In my scripts that use it, it&#8217;s usually coupled with a download function so that XML is generated on the fly and then downloaded to a file. The main advantage of this is that you can write a basic import script using the SimpleXML library to restore the &#8230; <a class="continue_reading" href="http://www.sean-barton.co.uk/2009/03/turning-an-array-or-object-into-xml-using-php/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have read a fair few tutorials written by others using classes and DOM functions to create XML from arrays. But what happens if you have an older PHP installation or prefer to keep things really simple as I do.</p>
<p>The following function declarations generate an XML string from an associative array. In my scripts that use it, it&#8217;s usually coupled with a download function so that XML is generated on the fly and then downloaded to a file. The main advantage of this is that you can write a basic import script using the SimpleXML library to restore the array at any time which makes it perfect for use as part of a backup/restore system.</p>
<p>WordPress stores alot of it&#8217;s sitewide data in a table called wp_options which stores a named key and a value string for each piece of information. Plugins can also use this table by using the add_option, update_option, delete_option and get_option functions passing values, arrays or objects along with a key name. This isn&#8217;t an ideal data structure but does mean that plugin writers can easily store information without bloating the database with unnecessary and often badly designed tables.</p>
<p><strong>The Code..</strong></p>
<pre>function generate_xml_from_array($array, $node_name) {
	$xml = '';

	if (is_array($array) || is_object($array)) {
		foreach ($array as $key=&gt;$value) {
			if (is_numeric($key)) {
				$key = $node_name;
			}

			$xml .= '&lt;' . $key . '&gt;' . "\n" . generate_xml_from_array($value, $node_name) . '&lt;/' . $key . '&gt;<!--' . $key . '-->' . "\n";
		}
	} else {
		$xml = htmlspecialchars($array, ENT_QUOTES) . "\n";
	}

	return $xml;
}

function generate_valid_xml_from_array($array, $node_block='nodes', $node_name='node') {
	$xml = '&lt;?xml version="1.0" encoding="UTF-8" ?&gt;' . "\n";

	$xml .= '&lt;' . $node_block . '&gt;' . "\n";
	$xml .= generate_xml_from_array($array, $node_name);
	$xml .= '<!--' . $node_block . '-->&lt;/' . $node_block . '&gt;' . "\n";

	return $xml;
}</pre>
<p><strong>Usage</strong></p>
<p>You can use the above functions by generating an array or object as normal and then using the following code. The function returns the XML and you can then do with it as you wish.</p>
<pre>$xml = generate_valid_xml_from_array($array);</pre>
<p><strong>Things to consider</strong></p>
<p>XML doesn&#8217;t allow for numeric tags so any numbers are replaced by the content of the $node_name variable. XML also doesn&#8217;t allow for certain special characters within it&#8217;s tags and ,for this reason, the <a title="PHP Manual htmlspecialchars" href="http://uk.php.net/htmlspecialchars" target="_blank">htmlspecialchars</a> function is passed over the raw data before it is placed into the string.</p>
<p>You can, however make use of cdata tags which tells XML readers to essentially &#8216;ignore whats coming next&#8217;. See the w3schools explanation of cdata here: <a title="w3schools cdata overview" href="http://www.w3schools.com/XML/xml_cdata.asp" target="_blank">http://www.w3schools.com/XML/xml_cdata.asp</a>. There is no right or wrong way to escape data but if you have problems with my script then factor in the cdata tags replacing the htmlspecialchars call and see how you get on.</p>
<p>Alternatively feel free to contact me by commenting on this post or using the contact form and I will work with you to get your script working.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sean-barton.co.uk/2009/03/turning-an-array-or-object-into-xml-using-php/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>XLS Download from PHP Class!</title>
		<link>http://www.sean-barton.co.uk/2009/01/xls-download-from-php-class/</link>
		<comments>http://www.sean-barton.co.uk/2009/01/xls-download-from-php-class/#comments</comments>
		<pubDate>Wed, 21 Jan 2009 15:21:06 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Time Savers]]></category>
		<category><![CDATA[PHP XLS Class]]></category>
		<category><![CDATA[Spreadsheet Download]]></category>
		<category><![CDATA[XLS]]></category>

		<guid isPermaLink="false">http://www.sean-barton.co.uk/?p=193</guid>
		<description><![CDATA[Following on from my last post on creating a proper XLS spreadsheet from PHP I have just written a small class which will do all the hard work for you if necessary. It will handle rows and columns automatically aswell as being able to be passed an array and then generating a spreadsheet download for you. Download: Sample usage is as follows: //Require the file require_once (SHARED_CLASSES_DIR . 'xls.class.php'); //Instantiate the class. $xls = new xls(); //Just build an example array out of test data $array = array( array(1,2,3,4,'five') , array('five','test' ,4,3, 0) ); //Triggers the download using the passed &#8230; <a class="continue_reading" href="http://www.sean-barton.co.uk/2009/01/xls-download-from-php-class/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Following on from my last post on creating a proper XLS spreadsheet from PHP I have just written a small class which will do all the hard work for you if necessary.</p>
<p>It will handle rows and columns automatically aswell as being able to be passed an array and then generating a spreadsheet download for you.</p>
<p><strong>Download</strong>: <a class="downloadlink" href="http://www.sean-barton.co.uk/wp-content/plugins/download-monitor/download.php?id=7" title="Version 1 downloaded 1213 times" >XLS from PHP Example Class (783 bytes)</a></p>
<p><strong>Sample usage</strong> is as follows:</p>
<pre>	//Require the file
	require_once (SHARED_CLASSES_DIR . 'xls.class.php');

	//Instantiate the class.
	$xls = new xls(); 

	//Just build an example array out of test data
	$array = array(
		array(1,2,3,4,'five')
		, array('five','test' ,4,3, 0)
	);

	//Triggers the download using the passed array
	$xls-&gt;download_from_array($array);</pre>
<p>Note that when instantiating the class you can pass a string as an argument and it will set the name of the XLS download. No need to add .xls to the end because it will do that for you.</p>
<p>Download: <a class="downloadlink" href="http://www.sean-barton.co.uk/wp-content/plugins/download-monitor/download.php?id=7" title="Version 1 downloaded 1213 times" >XLS from PHP Example Class (783 bytes)</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sean-barton.co.uk/2009/01/xls-download-from-php-class/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Creating a Downloadable Spreadsheet from PHP</title>
		<link>http://www.sean-barton.co.uk/2009/01/creating-a-downloadable-spreadsheet-from-php/</link>
		<comments>http://www.sean-barton.co.uk/2009/01/creating-a-downloadable-spreadsheet-from-php/#comments</comments>
		<pubDate>Fri, 16 Jan 2009 12:53:21 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Time Savers]]></category>
		<category><![CDATA[Downloadable Spreadsheet]]></category>
		<category><![CDATA[Microsoft Excel]]></category>

		<guid isPermaLink="false">http://www.sean-barton.co.uk/?p=183</guid>
		<description><![CDATA[I have written several systems that show data on a page but also provide a CSV download file either through a textarea with formatted data inside to copy and paste or via a download link and creates a file on the fly. I recently decided that this wasn&#8217;t the best way to do it seeing as the people will want to be using Microsoft Excel to view the data. It is possible to write a spreadsheet using PHP and using an example from AppServ I started to do it this way. The original link is included above but here is &#8230; <a class="continue_reading" href="http://www.sean-barton.co.uk/2009/01/creating-a-downloadable-spreadsheet-from-php/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have written several systems that show data on a page but also provide a CSV download file either through a textarea with formatted data inside to copy and paste or via a download link and creates a file on the fly.</p>
<p>I recently decided that this wasn&#8217;t the best way to do it seeing as the people will want to be using Microsoft Excel to view the data. It is possible to write a spreadsheet using PHP and using an example from <a title="AppServ Excel from PHP Example" href="http://www.appservnetwork.com/modules.php?name=News&amp;file=article&amp;sid=8" target="_blank">AppServ</a> I started to do it this way.</p>
<p>The original link is included above but here is my simplified version with smaller more understandable function naming:</p>
<p>Download the example script here: <a class="downloadlink" href="http://www.sean-barton.co.uk/wp-content/plugins/download-monitor/download.php?id=6" title="Version 1 downloaded 379 times" >XLS from PHP Example (723 bytes)</a></p>
<pre>&lt;?php

function xls_BOF() {
	echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
}

function xls_EOF() {
	echo pack("ss", 0x0A, 0x00);
}

function xls_write_cell($row, $col, $value='') {
	if (is_numeric($value)) {
		echo pack("sssss", 0x203, 14, $row, $col, 0x0);
		$value = pack("d", $value);
	} else {
		$l = strlen($value);
		echo pack("ssssss", 0x204, 8 + $l, $row, $col, 0x0, $l);
	}

	echo $value;
}

// Send Headers to set the Filename and force a download of the contents of the script
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");

 // Put the filename in \"'s if you want it to include spaces
header("Content-Disposition: attachment;filename=" . $filename . ".xls");
header("Content-Transfer-Encoding: binary ");

xlsBOF(); //Start the Spreadsheet

xls_write_cell(0, 1, 'Column 1');
xls_write_cell(0, 2, 'Column 2');
xls_write_cell(0, 3, 'Column 3');

$row = 1;
for ($i=0; $i&lt;2; $i++) {
	xls_write_cell($row, 0, 'Row ' . $row . ' Column ' . $i);
	xls_write_cell($row, 1, 'Row ' . $row . ' Column ' . $i);
	xls_write_cell($row, 2, 'Row ' . $row . ' Column ' . $i);

	$row++;
}

xlsEOF(); //End the Spreadsheet

exit(); //Exit the script after download

?&gt;</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.sean-barton.co.uk/2009/01/creating-a-downloadable-spreadsheet-from-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>IE Annoyance when downloading PDFs</title>
		<link>http://www.sean-barton.co.uk/2008/09/ie-annoyance-when-downloading-pdfs/</link>
		<comments>http://www.sean-barton.co.uk/2008/09/ie-annoyance-when-downloading-pdfs/#comments</comments>
		<pubDate>Wed, 24 Sep 2008 15:59:52 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Bug Fixes]]></category>
		<category><![CDATA[Annoyances]]></category>
		<category><![CDATA[internet explorer]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.sean-barton.co.uk/?p=60</guid>
		<description><![CDATA[I came across this error at work and it took me a good three hours to fix! The problem was when a user tried to download a pdf file from one of our sites in internet explorer. It worked fine in Firefox though! The error message was: The file could not be written to the cache Luckily a far low down on Google had a sensible answer which was to add the following code (PHP) before the call to session_start(); if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {     session_cache_limiter("public"); } Other sites were talking about security settings in versions of IE below 6 &#8230; <a class="continue_reading" href="http://www.sean-barton.co.uk/2008/09/ie-annoyance-when-downloading-pdfs/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I came across this error at work and it took me a good three hours to fix! The problem was when a user tried to download a pdf file from one of our sites in internet explorer. It worked fine in Firefox though! The error message was:</p>
<p><em>The file could not be written to the cache</em></p>
<p>Luckily a far low down on Google had a sensible answer which was to add the following code (PHP) before the call to session_start();</p>
<pre>if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
    session_cache_limiter("public");
}</pre>
<p>Other sites were talking about security settings in versions of IE below 6 but they didn&#8217;t really help. I thought I would post this in the hope that it helps anyone else that has the same problem.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sean-barton.co.uk/2008/09/ie-annoyance-when-downloading-pdfs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Zen Cart Welcome Email Editor</title>
		<link>http://www.sean-barton.co.uk/2008/07/zen-cart-welcome-email-editor/</link>
		<comments>http://www.sean-barton.co.uk/2008/07/zen-cart-welcome-email-editor/#comments</comments>
		<pubDate>Thu, 31 Jul 2008 14:39:25 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Time Savers]]></category>
		<category><![CDATA[Zen Cart]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.sean-barton.co.uk/?p=10</guid>
		<description><![CDATA[I&#8217;ve just dug up a script that I wrote a while back for someone. It&#8217;s not the most advanced thing in the world and it does what it says on the tin. Within Zen Cart there is a menu on the admin pages called &#8216;Tools&#8217; which has an option called &#8216;Email Welcome&#8217;. This script is a default Zen Cart page to simply show you what the welcome email looks like. hint: be sure to turn on html emails and it will show you both the html and text versions (default text only is set) I have modified this script to &#8230; <a class="continue_reading" href="http://www.sean-barton.co.uk/2008/07/zen-cart-welcome-email-editor/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just dug up a script that I wrote a while back for someone. It&#8217;s not the most advanced thing in the world and it does what it says on the tin.</p>
<p>Within Zen Cart there is a menu on the admin pages called &#8216;Tools&#8217; which has an option called &#8216;Email Welcome&#8217;. This script is a default Zen Cart page to simply show you what the welcome email looks like.</p>
<div style="float: right; margin: 0px 0px 5px 10px;"><img src="http://www.sean-barton.co.uk/wp-content/uploads/admin_menu.gif" alt="Screenshot 1" /></div>
<p><em>hint: be sure to turn on html emails and it will show you both the html and text versions (default text only is set)</em></p>
<p>I have modified this script to allow the editing of these pages if you have little or no knowledge of writing PHP although some HTML skill is required.</p>
<p>Zen Cart puts together a number of PHP <a href="http://uk.php.net/define">Defines</a> to build the welcome email and normally when you want to modify it then you have to trawl through three of four files of these defines to get to the one you want.</p>
<p>This script basically does that for you and parses/updates the files necessary with your new information. The following image shows the new page and i&#8217;m sure no explanation is needed to show you how to use it.</p>
<div style="float: left; margin-right: 10px;"><a href="http://www.sean-barton.co.uk/wp-content/uploads/welcome_email_editor_preview.gif" target="_blank" rel="lightbox[10]"><img src="http://www.sean-barton.co.uk/wp-content/uploads/welcome_email_editor_preview_thumb.gif" alt="Screenshot Thumbnail 2" /></a></div>
<p><em>Known Bugs:</em> <em>the only thing I know to be wrong with it is that some defnes reference other defines and this script doesn&#8217;t respect that. There are only one or two defines like this so nothing to worry about unless you intend to change the name of the shop owner frequently. If you do change it, however, then just make sure you use this system to update the welcome email at the same time. Nice and easy!</em></p>
<div style="clear: left; padding: 10px 0px;">Here&#8217;s the download link: <code><a class="downloadlink" href="http://www.sean-barton.co.uk/wp-content/plugins/download-monitor/download.php?id=3" title="Version 1.2 downloaded 907 times" >Welcome Email Editor for ZenCart (5.29 kB)</a></code></div>
<div style="clear: left; padding: 10px 0px;">UPDATE: Please make sure to chmod your languages/[language]/email_extras.php, languages/[language]/create_account.php and /languages/[language].php files (in both catalogue and admin) to be writable by apache if not this may not work.</div>
]]></content:encoded>
			<wfw:commentRss>http://www.sean-barton.co.uk/2008/07/zen-cart-welcome-email-editor/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Spoofing a Post Request</title>
		<link>http://www.sean-barton.co.uk/2008/07/spoofing-a-post-request/</link>
		<comments>http://www.sean-barton.co.uk/2008/07/spoofing-a-post-request/#comments</comments>
		<pubDate>Mon, 07 Jul 2008 08:51:12 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Time Savers]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.sean-barton.co.uk/?p=11</guid>
		<description><![CDATA[Ever needed to test what a form does on your site without having to go through and fill the thing in over and over? Alternatively have you ever needed to emulate a post request to a callback script or similar, something which is usually done by a secure server? Well I have! If this happens then you can emulate the request to yours (or someone elses) server from anywhere using the following code. &#60;?php $params = array('http'=&#62;array('method'=&#62;'POST','content'=&#62;$string)); $context = stream_context_create($params); $fp = @fopen($url, 'rb', false, $context); if (!$fp) { echo 'Failed to open file pointer.'; } else { $response = &#8230; <a class="continue_reading" href="http://www.sean-barton.co.uk/2008/07/spoofing-a-post-request/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Ever needed to test what a form does on your site without having to go through and fill the thing in over and over? Alternatively have you ever needed to emulate a post request to a callback script or similar, something which is usually done by a secure server? Well I have!</p>
<p>If this happens then you can emulate the request to yours (or someone elses) server from anywhere using the following code.</p>
<pre>&lt;?php

$params = array('http'=&gt;array('method'=&gt;'POST','content'=&gt;$string));
$context = stream_context_create($params);

$fp = @fopen($url, 'rb', false, $context);

if (!$fp) {
	echo 'Failed to open file pointer.';
} else {
	$response = @stream_get_contents($fp);
	if ($response === false) {
		echo 'POST Failed!';
	} else {
		echo $response;
	}
}

?&gt;</pre>
<p><strong>Usage</strong></p>
<p>Basically just pass the code above a URL in the variable $url and a formatted string in the format:</p>
<p>key1=var1&amp;key2=var2&amp;&#8230;</p>
<p>You should really stick it in a function and wrap in an HTML form but I&#8217;m not going to do it all for you! If all goes well then you should see the response from the post request, otherwise the appropriate error message will be shown.</p>
<p><strong>Security Issues</strong></p>
<p>Ever considered where else you could use this script? Ever though about how some people could use this script against your site? It could potentially be used for a DOS attack against anywhere but this is NOT what I recommend it be used for,  It&#8217;s just a handy tool for sending POST requests but if you are worried by this then there are a number of things you can do to prevent it.</p>
<p>The best I can think of is sending a DB stored random number with each POST. When your script receives it it should check the DB and delete that record if it exists then run the form, otherwise if it doesn&#8217;t exist then display the appropriate error message.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sean-barton.co.uk/2008/07/spoofing-a-post-request/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Geocoding Addresses using Google Maps</title>
		<link>http://www.sean-barton.co.uk/2008/05/geocoding-addresses-using-google-maps/</link>
		<comments>http://www.sean-barton.co.uk/2008/05/geocoding-addresses-using-google-maps/#comments</comments>
		<pubDate>Mon, 19 May 2008 08:10:07 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Google Maps]]></category>
		<category><![CDATA[Geocoding]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.sean-barton.co.uk/?p=6</guid>
		<description><![CDATA[In my previous post I showed you how to create a beautiful Google Map for your site with controls showing Google headquarters. Some might say that this isn&#8217;t very useful, I don&#8217;t know why they think that but for those that agree here is how to get it to show any postcode or address you like. I strongly suggest you read my other post first if you don&#8217;t know much about the Google Map API (read it here) So&#8230; The process of turning an address into latitude and longitude coordinates is called Geocoding and Google&#8217;s API makes it very easy &#8230; <a class="continue_reading" href="http://www.sean-barton.co.uk/2008/05/geocoding-addresses-using-google-maps/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In my previous post I showed you how to create a beautiful Google Map for your site with controls showing Google headquarters. Some might say that this isn&#8217;t very useful, I don&#8217;t know why they think that but for those that agree here is how to get it to show any postcode or address you like.</p>
<p><em>I strongly suggest you read my other post first if you don&#8217;t  know much about the Google Map API (read it <a title="read 'Google map basics'" href="http://www.sean-barton.co.uk/2008/05/google-map-basics/" target="_self">here</a>)</em></p>
<p>So&#8230;</p>
<p>The process of turning an address into latitude and longitude coordinates is called Geocoding and Google&#8217;s API makes it very easy to do so using a simple request to their server. We will go into the legal side later on in this post but for now lets just say that Geocoding is a server intensive process for Google and they recommend client side caching of added coordinates to avoid re-requesting coordinates if you already have them.</p>
<p>Getting the coordinates is actually very easy. Use the following URL in your browser (making sure to replace your API key and an address)</p>
<pre>http://maps.google.com/maps/geo?q= ## ADDRESS OR POSTCODE ## &amp;output=xml&amp;key= ## YOUR API KEY ##</pre>
<p>This URL will return some XML (if you have done it correctly) which will contain three pieces of useful information</p>
<ul>
<li>Latitude</li>
<li>Longitude</li>
<li>Geocode Accuracy</li>
</ul>
<p>If you know what country your going to be searching in then you can add another argument to the URL telling it the TLD or Top Level Domain (com, uk, etc..) to make it a little easier for Googles Geocoder:</p>
<pre>gl=uk</pre>
<p>We can use the returned data to create a Google map of that location but first we need to extract the coordinates. Yes we could use Javascript but where&#8217;s the fun in that (or the point)? Using PHP means all the processing is done server side so the client doesn&#8217;t need to do any sort of processing (useful for slower client computers).</p>
<p>Here&#8217;s how you get PHP to send the request:</p>
<pre>$ch = curl_init();</pre>
<pre>$url = "http://maps.google.com/maps/geo?q=" . urlencode($address) . "&amp;output=xml&amp;key=" . $api_key;
curl_setopt($ch, CURLOPT_URL, $url);</pre>
<pre>curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);</pre>
<pre>curl_close($ch);</pre>
<p>Why why why are you using CURL you ask? (<a title="PHP.net, the bible for PHP programmers explains what CURL is" href="http://uk3.php.net/manual/en/intro.curl.php" target="_blank">what is CURL anyway?</a>) Well..</p>
<p>A fair few server administrators are blocking the use for file handling functions to URLs (fopen, file, file_get_contents, etc..); This is sensible because there are exploits that malicious programmers can use to gain access to your site and start causing trouble. CURL is a little slower (I&#8217;m told) but safer (apparently).</p>
<p>The querystring we sent to Google passes the type of return we want (<code>XML</code>, <code>KML</code>, <code>CSV</code>, <code>JSON</code>), the address or postcode (<span style="text-decoration: underline;">urlencoded</span> string) and of course our API key.</p>
<p>The curl options (specifically CURLOPT_RETURNTRANSFER) mean that whatever comes back from your CURL request can be stored in a variable and worked on (as opposed to echoing to the screen).</p>
<p>Although XML parsing in PHP is really easy (<a title="PHP.net reference page for xml_parse_into_struct" href="http://uk.php.net/manual/en/function.xml-parse-into-struct.php" target="_blank">xml_parse_into_struct</a> if your interested), it&#8217;s a bit overkill for what we need; Instead specify the output as CSV which returns a simple string that is incredibly easy to use. Something like:</p>
<pre class="prettyprint"><span class="lit">200</span><span class="pun">,</span><span class="lit">6</span><span class="pun">,</span><span class="lit">42.730070</span><span class="pun">,-</span><span class="lit">73.690570
</span></pre>
<p>This breaks down into the following:</p>
<ul>
<li>Request status code (success is 200, anything else means it&#8217;s broken)</li>
<li>Accuracy of search result (5 is postcode level, higher is better as far as 9 which is premise level)</li>
<li>Latitude</li>
<li>Longitude</li>
</ul>
<p>The easiest way to get split the returned CSV string is the PHP <a title="PHP.net reference page for explode" href="http://uk.php.net/manual/en/function.explode.php" target="_blank">explode</a> function:</p>
<pre>$array = explode(',', $csv_string);</pre>
<p>This returns an array of values split on the delimiter specified (in this case the comma). Now the latitude and longitude can be accessed at positions 2 and 3 respectively ($array[2] and $array[3]).</p>
<p><strong>So whats next?:</strong><em> Use the code I gave in my previous example to generate a map for an address we actually want by passing the latitude and longitude into my </em><em>render_map function ($map-&gt;render_map($array[2], $array[3]);).</em></p>
<p>Some things to bear in mind:</p>
<p>The next step in theory would be to build up a database of geocoded coordinates next to addresses and use Google maps literally everywhere. Unfortunately (to my understanding (May 2008)) the Post Office have licensed their data and Google have to follow through on this. Basically it means that in every country except the UK you can save the coordinates wherever you like whereas here you have to geocode Google&#8217;s data on the fly EVERY page load.</p>
<p>If you decide this is unacceptable but don&#8217;t want to break the Terms &amp; Conditions of Google&#8217;s API you can use a geocoding service and pay per postcode. It costs about 5 pence per geocode (<a title="A pay for geocoding service. beware: crap API but friendly staff" href="http://www.postcodeanywhere.co.uk/" target="_blank">Postcodeanywhere</a> May 2008) and they allow you to store the data wherever you like.</p>
<p><strong>Coming next: </strong>A find my nearest &#8230; search using google maps</p>
<p><em>If you want more information on the geocoding process then Googles explanation is <a title="Google Map API reference" href="http://code.google.com/apis/maps/documentation/services.html" target="_blank">here</a></em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sean-barton.co.uk/2008/05/geocoding-addresses-using-google-maps/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Google Map basics</title>
		<link>http://www.sean-barton.co.uk/2008/05/google-map-basics/</link>
		<comments>http://www.sean-barton.co.uk/2008/05/google-map-basics/#comments</comments>
		<pubDate>Thu, 15 May 2008 22:22:49 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Google Maps]]></category>
		<category><![CDATA[Google API]]></category>
		<category><![CDATA[Google Map]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.sean-barton.co.uk/?p=4</guid>
		<description><![CDATA[This post will give you a basic idea of how to add your very own Google map to your site and do it do it can be reused by whatever framework you are working within very easily. <a class="continue_reading" href="http://www.sean-barton.co.uk/2008/05/google-map-basics/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have been toying with Google maps for a week or so now and have found them tricky if you don&#8217;t immediately understand what the hell is going on.</p>
<p>First things first, you need to register an API key (<a title="Link to sign up for a google map api key" href="http://code.google.com/apis/maps/signup.html" target="_blank">here</a>) so that you can send requests off to their server and get a response that doesn&#8217;t read something like &#8216;Invalid API Key&#8217;. Google map API keys are domain specific but you can always register localhost or your internal domain ip which will still work.</p>
<p>The most logical thing to want to do when you have the key is display a map (<em>Really?</em>). Google offer a nice piece of JS to get you started so ill start with that:</p>
<pre>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
  &lt;head&gt;
    &lt;meta http-equiv="content-type" content="text/html; charset=utf-8"/&gt;
    &lt;title&gt;Google Maps JavaScript API Example&lt;/title&gt;
    &lt;script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=##YOUR-KEY-HERE##"
      type="text/javascript"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;

    //&lt;![CDATA[

    function load() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(37.4419, -122.1419), 13);
      }
    }

    //]]&gt;
    &lt;/script&gt;
  &lt;/head&gt;
  &lt;body onload="load()" onunload="GUnload()"&gt;
    &lt;div id="map" style="width: 500px; height: 300px"&gt;&lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>
<p>Simple eh? of course this code is great if you only ever want one map per page in a div called &#8216;map&#8217; but this isn&#8217;t really very dynamic now is it. Once you get it running you&#8217;ll find out its just displaying a map of google headquarters somewhere in america with no map controls or anything useful (unless of course you wanted to know where google headquarters was).</p>
<p>So&#8230; to make this map usable we can do a number of things:</p>
<ol>
<li>Make the div name dynamic</li>
<li>De-fluff the code and put it into a php template</li>
<li>Sort out the &amp;&#8217;s in their script call</li>
<li>Pass the coordinates as a function argument to make it <span style="text-decoration: line-through;">easier to use</span> usable</li>
</ol>
<p>Following my above points we are left with the following:</p>
<pre>&lt;?php</pre>
<pre>class map_test {</pre>
<pre>	function __construct($google_api_key) {</pre>
<pre>		$js = "&lt;script src=\"http://maps.google.com/maps?file=api&amp;v=2&amp;key=" . $google_api_key . "\" /&gt;";</pre>
<pre>		$js .= "&lt;script type=\"text/javascript\"&gt;</pre>
<pre>		function load() {</pre>
<pre>			if (GBrowserIsCompatible(mapName, latitude, longitude)) {</pre>
<pre>				var map = new GMap2(document.getElementById(\"mapName\"));</pre>
<pre>				map.setCenter(new GLatLng(latitude, longitude), 13);</pre>
<pre>			}</pre>
<pre>		}</pre>
<pre>    		&lt;/script&gt;";</pre>
<pre>		echo $js;</pre>
<pre>	}</pre>
<pre>	function render_map($latitude, $longitude) {</pre>
<pre>		$div_id = 'map' . mt_rand(1000,9999);</pre>
<pre>		$html = "&lt;div id=\"" . $div_id . "\" style=\"width: 500px; height: 300px\"&gt;&lt;/div&gt;";</pre>
<pre>		$html .= "	&lt;script&gt;</pre>
<pre>					load(" . $div_id . ", " . $latitude . ", " . $longitude . ");</pre>
<pre>				&lt;/script&gt;";</pre>
<pre>		echo $html;</pre>
<pre>	}</pre>
<pre>}</pre>
<pre>$google_api_key = "##YOUR-KEY-HERE##";</pre>
<pre>$latitude = 37.4419;</pre>
<pre>$longitude = -122.1419;</pre>
<pre>$map = new map_test($google_api_key);</pre>
<pre>$map-&gt;render_map($latitude, $longitude);</pre>
<pre>?&gt;</pre>
<p>Ok, so what we have here is just a longer way of rendering to the screen yet another map of Google&#8217;s headquarters. Look a little closer at the code and you will see that I have extracted the hard coded parts of the JS into variables that something like PHP can manipulate to display a map of pretty much anywhere you want to see. Just change the API key to yours and toy with the coordinates to see a map of anywhere you like.</p>
<p>The render_map function can be called as many times as you like, each time displaying another map of the coordinates you pass it.</p>
<p>The next logical addition to this script is to add controls for zoom and pan. These are surprisingly easy to integrate. Simply add the following lines to the JS &#8216;load&#8217; function just after the line that defines the new GMap2:</p>
<pre>map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());</pre>
<p>These will work assuming of course that you haven&#8217;t renamed the &#8216;map&#8217; variable.</p>
<p>Next you will probably want to add a marker (for Google headquarters) to show the thing you are looking at in more detail. These are done in the form of those pushpin things you usually see or as Google calls them, &#8216;markers&#8217;. The followng JS function will add a marker at the coordinates passed:</p>
<pre>function addMarker(map, latitude, longitude, description) {</pre>
<pre>    var point = new GLatLng(latitude, longitude);</pre>
<pre>    var marker = new GMarker(point);</pre>
<pre>    if (description.length &gt; 0) {</pre>
<pre>        GEvent.addListener(marker, "click", function() {</pre>
<pre>            marker.openInfoWindowHtml(description);</pre>
<pre>        });</pre>
<pre>    }</pre>
<pre>    map.addOverlay(marker);
}</pre>
<p>You may want to put your JS code into a .js file and store it appropriately at this point because really large functions written in different languages can be confusing&#8230; Either way, put the above code below your &#8216;load&#8217; function and call it using this line:</p>
<pre>addMarker(map, latitude, longitude, desc);</pre>
<p>Simple enough to understand really but it passes the map object we created earlier, the longitude, latitude and a description to the function to add a marker. If you don&#8217;t want a description for the marker then just pass an empty string or <em>null</em>.</p>
<p>You now know how to show visitors to your site where google headquarters is. Handy I know! See my future post for &#8216;Geocoding&#8217; an address to get those all important coordinates for any location on the globe onto a google map.</p>
<p>Sean</p>
<p><em>For more Google map API help, who better than to ask than Google themselves: <a title="Link to google api reference homepage" href="http://code.google.com/apis/maps/" target="_blank">API Page</a></em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sean-barton.co.uk/2008/05/google-map-basics/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk
Page Caching using disk (enhanced)
Database Caching 10/61 queries in 0.120 seconds using disk
Object Caching 665/761 objects using disk

Served from: www.sean-barton.co.uk @ 2012-02-05 12:12:03 -->
