<?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>PHP Starter &#187; Intermediate</title>
	<atom:link href="http://phpstarter.net/tag/intermediate/feed/" rel="self" type="application/rss+xml" />
	<link>http://phpstarter.net</link>
	<description>PHP Tips &#38; Tools From Starters to Experts</description>
	<lastBuildDate>Fri, 25 Jun 2010 14:14:24 +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>Send Print Jobs Directly from PHP</title>
		<link>http://phpstarter.net/2010/05/send-print-jobs-directly-from-php/</link>
		<comments>http://phpstarter.net/2010/05/send-print-jobs-directly-from-php/#comments</comments>
		<pubDate>Wed, 19 May 2010 16:04:25 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=524</guid>
		<description><![CDATA[I recently learned that you can send print jobs directly from a PHP server. How cool is that? This article will cover sending print jobs from a PHP server to a printer on the same LAN. This does not mean that someone viewing a page over the Internet can have something print on their local [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p>I recently learned that you can send print jobs directly from a PHP server.  How cool is that?  This article will cover sending print jobs from a PHP server to a printer on the same LAN.  This does <strong>not</strong> mean that someone viewing a page over the Internet can have something print on their local printer with these functions.  This <strong>does</strong> mean if you have PHP running on a Windows server in your internal network, you can print to printers that are configured on that Windows server <strong>only</strong>.</p>
<p><span id="more-524"></span></p>
<p>This article really only applies if you are hosting the web server in your local office or place of business.  If you are hosting your web server in a data center somewhere and you never see it, this article is probably not for you.  In the diagram below, pretend the server and attached printers are in your office building somewhere, and the computers in the red box are your clients out on the Internet somewhere.  Note that the printers at the client side are not used in this application.</p>
<p><img src="http://phpstarter.net/wp-content/uploads/2010/04/printing.png" alt="" title="Printing Diagram" width="600" height="400" class="aligncenter size-full wp-image-529" /></p>
<p>Another possible setup would be if everything is on a private internal network, like the diagram below.  In this case everything is in the green box because it is all on an internal network joined by a network switch.  The two printers are in yellow boxes because they are only visible to the server if shared from those attached network computers, and the computers are turned on.</p>
<p><img src="http://phpstarter.net/wp-content/uploads/2010/04/printing_lan.png" alt="" title="Printing Diagram - LAN" width="600" height="400" class="aligncenter size-full wp-image-529" /></p>
<p>So now that we have the big picture, there are a couple other things to note.  The web server needs to be running Windows, not Linux.  The PHP Printer functions are Windows only.  The printer(s) can be connected locally via USB/Parallel, over the network via IP JetDirect, or shared off of another server/computer.</p>
<h3>Printing Plain Text Documents</h3>
<p>Printing plain text documents are a piece of cake.  It&#8217;s going to be similar to echoing text out to the web browser with a couple differences.  This is the first test I did:</p>
<pre class="brush: php">
&lt;?php
	/* get the sample text */
	$lipsum = file_get_contents(&#039;lipsum.txt&#039;);

	/* open a connection to the printer */
	$printer = printer_open(&quot;Lexmark X850e XL V&quot;);

	/* write the text to the print job */
	printer_write($printer, $lipsum);

	/* close the connection */
	printer_close($printer);
?&gt;
</pre>
<p>The printer in line 6 is in my <a href="/wp-content/uploads/2010/04/printers.png">windows printer list</a>, and has to be matched exactly.  That function can be called without a printer parameter, and PHP will use the default printer specified in php.ini or try to detect it based on how it is set in Windows.  I wanted to do close to a full page of text, so I went to <a href="http://www.lipsum.com/">lipsum.com</a> and generated some sample text and saved it to a <a href="/samples/524/lipsum.txt">text file</a>.</p>
<p>So here is the <a href="/wp-content/uploads/2010/04/printer_test.jpg">printed result</a>, and the cool thing is that the text was almost exactly a full page.  The not-so-cool thing was that it doesn&#8217;t do simple things like word wrap.  Luckily, we can run the text through <a href="http://us2.php.net/manual/en/function.wordwrap.php">wordwrap()</a> before sending it to the printer to easily fix that.</p>
<p class="m_info">For future examples, I will be using my <a href="http://sourceforge.net/projects/pdfcreator/">PDFCreator</a> printer so I don&#8217;t waste paper (or money) during testing, and I encourage you to do the same.</p>
<h3>Printing a Custom Font</h3>
<p>If you want to print with a custom font, it is done using functions that are similar to the <a href="/tag/gd-library/">GD Library</a> functions.  You need to define the font, X/Y position, and other font weight properties.</p>
<p>In this example, I&#8217;m going to use the <a href="http://www.barcodesinc.com/free-barcode-font/">freely available barcode font</a> to print a barcode on a piece of paper.  In this example, I am also going to define the printer document and the individual page.</p>
<pre class="brush: php">
&lt;?php
	/* get the sample text */
	$lipsum = file_get_contents(&#039;lipsum.txt&#039;);

	/* open a connection to the printer */
	$printer = printer_open(&quot;PDFCreator&quot;);
	printer_start_doc($printer, &quot;Doc&quot;);
	printer_start_page($printer);

	/* font management */
	$barcode = printer_create_font(&quot;Free 3 of 9 Extended&quot;, 400, 200, PRINTER_FW_NORMAL, false, false, false, 0);
	$arial = printer_create_font(&quot;Arial&quot;, 148, 76, PRINTER_FW_MEDIUM, false, false, false, 0);

	/* write the text to the print job */
	printer_select_font($printer, $barcode);
	printer_draw_text($printer, &quot;*123456*&quot;, 50, 50);
	printer_select_font($printer, $arial);
	printer_draw_text($printer, &quot;123456&quot;, 250, 500);

	/* font management */
	printer_delete_font($barcode);
	printer_delete_font($arial);

	/* close the connection */
	printer_end_page($printer);
	printer_end_doc($printer);
	printer_close($printer);
?&gt;
</pre>
<h3>Drawing Images</h3>
<p>The printer functions only support writing bitmaps (bmp), so you will have to convert the images to that format before using it in this application.  The X,Y parameters in the printer_draw_bmp() function are in inches.</p>
<pre class="brush: php">
&lt;?php
	/* open a connection to the printer */
	$printer = printer_open(&quot;PDFCreator&quot;);
	printer_start_doc($printer, &quot;Doc&quot;);
	printer_start_page($printer);

	/* draw the image to the page */
	printer_draw_bmp($printer, &quot;c:\\path\\to\\image.bmp&quot;, 1, 1);

	/* close the connection */
	printer_end_page($printer);
	printer_end_doc($printer);
	printer_close($printer);
?&gt;
</pre>
<h3>Drawing Shapes</h3>
<p>Several shapes can be drawn as well.  The example will show two horizontal &#038; parallel lines of different length.</p>
<pre class="brush: php">
&lt;?php
	/* open a connection to the printer */
	$printer = printer_open(&quot;PDFCreator&quot;);
	printer_start_doc($printer, &quot;Doc&quot;);
	printer_start_page($printer);

	/* create the pen handle and set some properties */
	$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, &quot;000000&quot;);
	printer_select_pen($printer, $pen);

	/* draw some lines on the page */
	printer_draw_line($printer, 1, 100, 1000, 100);
	printer_draw_line($printer, 1, 200, 500, 200);

	/* delete the pen handle */
	printer_delete_pen($pen);

	/* close the connection */
	printer_end_page($printer);
	printer_end_doc($printer);
	printer_close($printer);
?&gt;
</pre>
<h3>Practical Uses</h3>
<p>Couple uses come to mind, and I&#8217;m sure there are others (post them if you have a good one!).</p>
<ul>
<li>Automatically print packing slips / invoices at a shipping center as customers place orders.</li>
<li>On an intranet website, have all the company printers configured at the server side so users can use the web application w/o worrying about setting up the printers at their workstation.</li>
<li>Automatically printing out reports generated by a CLI PHP script</li>
</ul>
<p>For more information, check out <a href="http://us.php.net/manual/en/book.printer.php">PHP print functions</a>.</p>
<h3>Printing from PHP on Linux Servers</h3>
<p>&#8220;But what about Linux servers!&#8221;, you say.  Well, as previously stated, the PHP functions don&#8217;t support anything other than Windows, but there is an alternative.  PHP4IT.com has an article titled <a href="http://php4it.com/a-1.html">Printing a form directly to a PCL printer (Linux)</a> that should help you with manually building the Postscript file and writing it through to the printer.  That should help get you started.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2010/05/send-print-jobs-directly-from-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making Google Static Maps a Little More Dynamic with PHP</title>
		<link>http://phpstarter.net/2010/03/making-google-static-maps-a-little-more-dynamic-with-php/</link>
		<comments>http://phpstarter.net/2010/03/making-google-static-maps-a-little-more-dynamic-with-php/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 14:00:24 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=501</guid>
		<description><![CDATA[If you have messed with the Google Maps API, you know that the JavaScript and API keys can be a real headache. Yes, there are very complex implementations that you can use, but what if you want&#8230;just a map? If you want just a map with no dynamic interface, Google Static Maps is just for [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p>If you have messed with the <a href="http://code.google.com/apis/maps/">Google Maps API</a>, you know that the JavaScript and API keys can be a real headache.  Yes, there are <a href="http://www.wunderground.com/wundermap/">very</a> <a href="http://www.packagemapping.com/">complex</a> <a href="http://sites.google.com/site/gmapsmania/100thingstodowithgooglemapsmashups">implementations</a> that you can use, but what if you want&#8230;just a map?  If you want just a map with no dynamic interface, Google Static Maps is just for you.  I will show how easy it is to use, and then spice it up with some PHP-powered enhancements.</p>
<p><span id="more-501"></span></p>
<p>Check out how easy this is.  If I want a map centered at a my zip code, I can create a JPEG image for that area with this link:</p>
<p><code>http://maps.google.com/maps/api/staticmap?sensor=false&#038;center=46311&#038;zoom=14&#038;size=600x400</code></p>
<p>And it generates this:</p>
<p><img src="http://maps.google.com/maps/api/staticmap?sensor=false&#038;center=46311&#038;zoom=14&#038;size=600x400" alt="" /></p>
<p>No API keys, no JavaScript, and the URL is even short enough to not have to wrap on the page.  As long as you don&#8217;t need the typical panning and zooming features, this is the best option.  There are a limited but practical set of features including map types (satellite, hybrid, regular, etc), markers, lines, shapes, custom icons, and all in different image formats.  View the <a href="http://code.google.com/apis/maps/documentation/staticmaps/">Google Static Maps API</a> page for the full details.</p>
<h3>Making it a Little More Dynamic</h3>
<p>This is a site on PHP.  I can&#8217;t show you how to create static maps and leave it at that.  There are several good reasons why we might want to dynamically generate that URL. </p>
<p><b>Simple &#8220;You Are Here&#8221; Map</b></p>
<p>For starters, how about a map that shows your local area based on your IP address geolocation?  This sample below uses the code from a previous article that showed how to <a href="http://phpstarter.net/2008/12/how-to-get-the-geographic-location-of-an-ip-address/">determine the geographic location from any IP address</a>.</p>
<p style="text-align: right; "><a href="/samples/501/geoip.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php">&lt;?php

/* replace with your own DB connection code */
require('../includes/database.php');
$db = db_connect();

/* get the IP address and make sure it is an unsigned integer */
$ip = sprintf('%u', ip2long($_SERVER['REMOTE_ADDR']));

/* fetch the location id and info */
$query = &quot;SELECT CityLocation.* FROM CityBlocks INNER JOIN CityLocation ON CityLocation.locId = CityBlocks.locId WHERE $ip BETWEEN CityBlocks.startIpNum AND CityBlocks.endIpNum LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$location = mysql_fetch_assoc($result);

?&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Static Map for Your Location&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h2&gt;Static map for your town:&lt;/h2&gt;
&lt;p&gt;If you are placed in the middle of an ocean, your IP address is probably not in the database.  The blue marker is your specific IP location (probably not exact).&lt;/p&gt;
&lt;img src=&quot;http://maps.google.com/maps/api/staticmap?sensor=false&amp;center=&lt;?=$location['postalCode']?&gt;&amp;markers=color:blue|&lt;?=$location['latitude']?&gt;,&lt;?=$location['longitude']?&gt;&amp;zoom=13&amp;size=600x400&quot; /&gt;

&lt;h2&gt;Details from IP GeoLocation:&lt;/h2&gt;
&lt;pre&gt;&lt;?php var_dump($location); ?&gt;&lt;/pre&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p><b>Show Your Position With Other Objects</b></p>
<p>We already know how to find a list of the closest items in our area from this post: <a href="http://phpstarter.net/2009/01/locate-the-nearest-radar-station-and-display-radar-images/">Locate the Nearest Radar Station and Display Radar Images</a>.  Now, let&#8217;s apply it to generating a Static Google Map.  This uses the &#8220;Implicit Positioning&#8221; feature where you can just list a bunch of points, and the map will automatically create a zoom level and center based on the created points.</p>
<p style="text-align: right; "><a href="/samples/501/radar_sites.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php">&lt;?php

/* replace with your own DB connection code */
require('../includes/database.php');
$db = db_connect();

/* get the IP address and make sure it is an unsigned integer */
$ip = sprintf('%u', ip2long($_SERVER['REMOTE_ADDR']));

/* fetch the location id */
$query = &quot;SELECT locId FROM CityBlocks 
			WHERE $ip BETWEEN startIpNum AND endIpNum LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$row = mysql_fetch_assoc($result);

/* now fetch the location */
$locId = $row['locId'];
$query = &quot;SELECT * FROM CityLocation WHERE locId = $locId LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$location = mysql_fetch_assoc($result);

/* offset the coordinates by 3, and find the closest station */
$lat = $location['latitude'] + 3;
$lon = $location['longitude'] - 3;
$query = &quot;SELECT *, SQRT(POW(69.1 * (lat - $lat), 2) + 
			POW(69.1 * ($lon - lon) * COS(lat / 57.3 ), 2 )) AS distance 
			FROM RadarSites ORDER BY distance ASC LIMIT 5&quot;;
$result = mysql_query($query, $db) or die(mysql_error());

$qs = '';
for ($i = 0; $i &lt; mysql_num_rows($result); $i++)
{
	$row = mysql_fetch_assoc($result);
	$rows[] = $row;
	
	/* remember - we want roughly the center of the radar coverage, not the top-left corner */
	$lat = $row['lat'] - 3;
	$lon = $row['lon'] + 3;
	
	/* forming the query string for the image URL */
	$markers[] = '&amp;markers=color:blue|label:' . $i . '|' . $lat . ',' . $lon;
}

$markers = implode('', $markers);

?&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Static Map for Your Location&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h2&gt;5 Closest Radar Sites to You&lt;/h2&gt;
&lt;p&gt;Red marker is you.&lt;/p&gt;
&lt;img src=&quot;http://maps.google.com/maps/api/staticmap?sensor=false&amp;maptype=roadmap&lt;?=$markers?&gt;&amp;markers=color:red|&lt;?=$location['latitude']?&gt;,&lt;?=$location['longitude']?&gt;&amp;size=600x400&quot; /&gt;

&lt;h2&gt;Details from IP GeoLocation:&lt;/h2&gt;
&lt;pre&gt;&lt;?php var_dump($location); ?&gt;&lt;/pre&gt;

&lt;h2&gt;Radar Sites:&lt;/h2&gt;
&lt;pre&gt;&lt;?php var_dump($rows); ?&gt;&lt;/pre&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>These examples are meant to get your creative juices flowing.  Have some other cool concepts for Google Static Maps?  Post them below.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2010/03/making-google-static-maps-a-little-more-dynamic-with-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Merge Image Layers in PHP</title>
		<link>http://phpstarter.net/2009/07/merge-image-layers-in-php/</link>
		<comments>http://phpstarter.net/2009/07/merge-image-layers-in-php/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 12:00:40 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Weather]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=455</guid>
		<description><![CDATA[In a previous article, I showed how to Locate the Nearest Radar Station and Display Radar Images. A commenter, mike, pointed out the idea of merging the image layers using PHP instead of layering all the images separately using CSS. Here is how to do it. Just like the previous article on finding the closest [...]


Related posts:<ul><li><a href='http://phpstarter.net/2010/03/making-google-static-maps-a-little-more-dynamic-with-php/' rel='bookmark' title='Permanent Link: Making Google Static Maps a Little More Dynamic with PHP'>Making Google Static Maps a Little More Dynamic with PHP</a></li>
<li><a href='http://phpstarter.net/2010/03/parse-zfp-zone-forecast-product-data-in-php-option-1/' rel='bookmark' title='Permanent Link: Parse ZFP (Zone Forecast Product) Data in PHP &#8211; Option 1'>Parse ZFP (Zone Forecast Product) Data in PHP &#8211; Option 1</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>In a previous article, I showed how to <a href="http://phpstarter.net/2009/01/locate-the-nearest-radar-station-and-display-radar-images/">Locate the Nearest Radar Station and Display Radar Images</a>.  A commenter, <a href="http://phpstarter.net/2009/01/locate-the-nearest-radar-station-and-display-radar-images/comment-page-1/#comment-332">mike</a>, pointed out the idea of merging the image layers using PHP instead of layering all the images separately using CSS.  Here is how to do it.</p>
<p><span id="more-455"></span></p>
<p>Just like the previous article on finding the closest radar station, I am going to use <a href="http://phpstarter.net/2008/12/how-to-get-the-geographic-location-of-an-ip-address/">IP geolocation</a> to find the closest radar site.  See that <a href="http://phpstarter.net/2009/01/locate-the-nearest-radar-station-and-display-radar-images/">previous article</a> for an explanation on how to do that.</p>
<p style="text-align: right; "><a href="/samples/455/radar_combined.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php">&lt;?php

/* replace with your own DB connection code */
require('../includes/database.php');
$db = db_connect();

/* get the IP address and make sure it is an unsigned integer */
$ip = sprintf('%u', ip2long($_SERVER['REMOTE_ADDR']));

/* fetch the location id */
$query = &quot;SELECT locId FROM CityBlocks 
			WHERE $ip BETWEEN startIpNum AND endIpNum LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$row = mysql_fetch_assoc($result);

/* now fetch the location */
$locId = $row['locId'];
$query = &quot;SELECT * FROM CityLocation WHERE locId = $locId LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$location = mysql_fetch_assoc($result);

/* offset the coordinates by 3, and find the closest station */
$lat = $location['latitude'] + 3;
$lon = $location['longitude'] - 3;
$query = &quot;SELECT *, SQRT(POW(69.1 * (lat - $lat), 2) + 
			POW(69.1 * ($lon - lon) * COS(lat / 57.3 ), 2 )) AS distance 
			FROM RadarSites ORDER BY distance ASC LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$radar = mysql_fetch_assoc($result);

/* we are using the snoopy class to download the images */
include('../includes/Snoopy.class.php');
$snoopy = new Snoopy();

/* cache the files locally */
function dl_cache($url, $filename)
{
	if (!file_exists($filename) || filemtime($filename) + 600 &lt; time())
	{
		global $snoopy;
		$snoopy-&gt;fetch($url);
		file_put_contents($filename, $snoopy-&gt;results);
		$snoopy-&gt;results = '';
	}
}

/* download the radar images */
$radar_id = $radar['id'];
dl_cache(&quot;http://radar.weather.gov/Overlays/Topo/Short/{$radar_id}_Topo_Short.jpg&quot;, &quot;maps/{$radar_id}_Topo_Short.jpg&quot;);
dl_cache(&quot;http://radar.weather.gov/RadarImg/N0R/{$radar_id}_N0R_0.gif&quot;, &quot;maps/{$radar_id}_N0R_0.gif&quot;);
dl_cache(&quot;http://radar.weather.gov/Overlays/County/Short/{$radar_id}_County_Short.gif&quot;, &quot;maps/{$radar_id}_County_Short.gif&quot;);
dl_cache(&quot;http://radar.weather.gov/Overlays/Highways/Short/{$radar_id}_Highway_Short.gif&quot;, &quot;maps/{$radar_id}_Highway_Short.gif&quot;);
dl_cache(&quot;http://radar.weather.gov/Overlays/Rivers/Short/{$radar_id}_Rivers_Short.gif&quot;, &quot;maps/{$radar_id}_Rivers_Short.gif&quot;);
dl_cache(&quot;http://radar.weather.gov/Overlays/Cities/Short/{$radar_id}_City_Short.gif&quot;, &quot;maps/{$radar_id}_City_Short.gif&quot;);
dl_cache(&quot;http://radar.weather.gov/Legend/N0R/{$radar_id}_N0R_Legend_0.gif&quot;, &quot;maps/{$radar_id}_N0R_Legend_0.gif&quot;);
dl_cache(&quot;http://radar.weather.gov/Warnings/Short/{$radar_id}_Warnings_0.gif&quot;, &quot;maps/{$radar_id}_Warnings_0.gif&quot;);

/* load the radar layers into an array */
$layers = array();
$layers[] = imagecreatefromjpeg(&quot;maps/{$radar_id}_Topo_Short.jpg&quot;);
$layers[] = imagecreatefromgif(&quot;maps/{$radar_id}_N0R_0.gif&quot;);
$layers[] = imagecreatefromgif(&quot;maps/{$radar_id}_County_Short.gif&quot;);
$layers[] = imagecreatefromgif(&quot;maps/{$radar_id}_Highway_Short.gif&quot;);
$layers[] = imagecreatefromgif(&quot;maps/{$radar_id}_Rivers_Short.gif&quot;);
$layers[] = imagecreatefromgif(&quot;maps/{$radar_id}_City_Short.gif&quot;);
$layers[] = imagecreatefromgif(&quot;maps/{$radar_id}_N0R_Legend_0.gif&quot;);
$layers[] = imagecreatefromgif(&quot;maps/{$radar_id}_Warnings_0.gif&quot;);

$image = imagecreatetruecolor(600, 550);


/* merge the layers */
for ($i = 0; $i &lt; count($layers); $i++)
{
	imagecopy($image, $layers[$i], 0, 0, 0, 0, 600, 550);
}

/* we're done! output the image... */
header('Content-type: image/jpeg');
imagejpeg($image);

/**
 * Why do I comment out the PHP closing tag?
 * See: http://phpstarter.net/2009/01/omit-the-php-closing-tag/
 */
/* ?&gt; */
</pre>
<p>The code from line ~31 on is pretty self-explanatory.  Basically, I am caching the maps locally, and then loading the images into PHP image resources.  I am putting the images in a PHP array because I want to make it easy add/delete/move layers.  For the application I&#8217;m using it for, it&#8217;s not likely, but your needs may differ.</p>
<p>The important function is imagecopy(), which is defined as:</p>
<p><em>bool imagecopy  ( resource $dst_im  , resource $src_im  , int $dst_x  , int $dst_y  , int $src_x  , int $src_y  , int $src_w  , int $src_h  )</em></p>
<p>Since I am copying whole pictures directly on top of each other &#8211; all the same size &#8211; it&#8217;s very easy.  You can specify image sizes and location in case you are copying a smaller image onto a larger image, like a logo copyright on a photo, for example.</p>
<p>So there you have it.  Although I believe the first method of layering the images via CSS works just fine, this method will work when you need to deliver a single image.</p>


<p>Related posts:<ul><li><a href='http://phpstarter.net/2010/03/making-google-static-maps-a-little-more-dynamic-with-php/' rel='bookmark' title='Permanent Link: Making Google Static Maps a Little More Dynamic with PHP'>Making Google Static Maps a Little More Dynamic with PHP</a></li>
<li><a href='http://phpstarter.net/2010/03/parse-zfp-zone-forecast-product-data-in-php-option-1/' rel='bookmark' title='Permanent Link: Parse ZFP (Zone Forecast Product) Data in PHP &#8211; Option 1'>Parse ZFP (Zone Forecast Product) Data in PHP &#8211; Option 1</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/07/merge-image-layers-in-php/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Loading INI Files in PHP</title>
		<link>http://phpstarter.net/2009/04/loading-ini-files-in-php/</link>
		<comments>http://phpstarter.net/2009/04/loading-ini-files-in-php/#comments</comments>
		<pubDate>Tue, 14 Apr 2009 12:00:23 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=424</guid>
		<description><![CDATA[PHP parses the php.ini file for the global PHP settings, but you can create an INI file that is specific to your own PHP application. You can also load those settings into as associate array with a native PHP function. How cool is that? Why? Having your config settings in a INI file makes it [...]


Related posts:<ul><li><a href='http://phpstarter.net/2010/03/parse-zfp-zone-forecast-product-data-in-php-option-1/' rel='bookmark' title='Permanent Link: Parse ZFP (Zone Forecast Product) Data in PHP &#8211; Option 1'>Parse ZFP (Zone Forecast Product) Data in PHP &#8211; Option 1</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>PHP parses the php.ini file for the global PHP settings, but you can create an INI file that is specific to your own PHP application.  You can also load those settings into as associate array with a native PHP function.  How cool is that?</p>
<p><span id="more-424"></span></p>
<h3>Why?</h3>
<p>Having your config settings in a INI file makes it easier to edit, especially for those that don&#8217;t have PHP experience.  It also comes in handy if you have protected PHP scripts, and you want someone to have the option of changing settings without having access to any of the PHP code.  There are a couple negative effects though.  Obviously, there is going to be some performance overhead because PHP will have to parse this file for each and every request made by a site visitor.  Also, you can&#8217;t assign any dynamic values here, like time(), etc.  You will have to make the call to determine if this method is best for you.</p>
<h3>How it Works</h3>
<p>Below is a sample INI file that the later examples will be loading.  Notice the syntax used.  The double quotes are not needed, but I am in the habit of using them because they are required if any special characters are in the values.</p>
<pre class="brush: php">
;some general settings not related to anything else
[general]
home_url = &quot;http://www.example.com/&quot;
contact_email = &quot;contact@example.com&quot;
app_path = &quot;/path/to/app/root&quot;
name = &quot;application name&quot;

;settings required to connect to a MySQL database
[database]
host = &quot;localhost&quot;
name = &quot;database_name&quot;
user = &quot;db_user&quot;
pass = &quot;db_password&quot;

;show we can have an array
[arrays]
test[] = &quot;value1&quot;
test[] = &quot;value2&quot;
test[] = &quot;value3&quot;
</pre>
<p>In the first load example, we are going to load all of the settings in one block.  In other words, we are going to ignore the sections, defined in the &#8216;[ ]&#8216; characters.</p>
<p style="text-align: right; "><a href="/samples/424/parse.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php">&lt;?php

/* load the config file and dump the values  */
$config = parse_ini_file('sample.ini');

header('Content-type: text/plain');
var_dump($config);

/**
 * Why do I comment out the PHP closing tag?
 * See: http://phpstarter.net/2009/01/omit-the-php-closing-tag/
 */
/* ?&gt; */
</pre>
<p>In the above example, we have a problem.  Notice that we have the setting &#8220;name&#8221; in more than one block, and because of that, we had a name conflict and lost one of the values.  To avoid this, we can put these setting blocks in their own associative array with the following statement.</p>
<p style="text-align: right; "><a href="/samples/424/parse_sep.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php">&lt;?php

/* load the config settings and dump the values */
$config = parse_ini_file('sample.ini', true);

header('Content-type: text/plain');
var_dump($config);

/**
 * Why do I comment out the PHP closing tag?
 * See: http://phpstarter.net/2009/01/omit-the-php-closing-tag/
 */
/* ?&gt; */
</pre>
<p>Now all the setting blocks are separated, and easily accessible.</p>
<p>So there you have it &#8211; a different type of configuration file that may be an option for your next PHP application.  It&#8217;s pretty simple, and you really only need one function call to load all the settings, so the learning curve is minimal.  If you want more information on this PHP function, check out the <a href="http://us3.php.net/parse_ini_file">function reference</a>.</p>


<p>Related posts:<ul><li><a href='http://phpstarter.net/2010/03/parse-zfp-zone-forecast-product-data-in-php-option-1/' rel='bookmark' title='Permanent Link: Parse ZFP (Zone Forecast Product) Data in PHP &#8211; Option 1'>Parse ZFP (Zone Forecast Product) Data in PHP &#8211; Option 1</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/04/loading-ini-files-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Working with AJAX</title>
		<link>http://phpstarter.net/2009/03/working-with-ajax/</link>
		<comments>http://phpstarter.net/2009/03/working-with-ajax/#comments</comments>
		<pubDate>Thu, 05 Mar 2009 06:00:24 +0000</pubDate>
		<dc:creator>Kurtis</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=409</guid>
		<description><![CDATA[AJAX is all over the internet today, and though completely unnecessary, a website with it can function much more quickly. Data can be transferred to and from users efficiently, but a major drawback is the extra code needed and some security issues inherent. Nevertheless, for certain applications, AJAX is great to know and take your [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p>AJAX is all over the internet today, and though completely unnecessary, a website with it can function much more quickly.  Data can be transferred to and from users efficiently, but a major drawback is the extra code needed and some security issues inherent.  Nevertheless, for certain applications, AJAX is great to know and take your project to a new level.<span id="more-409"></span>The truth is that tutorials for learning the basics of AJAX are all over the internet.  For the quick setup of JavaScript, check out <a href="http://www.google.com/search?q=php+ajax+tutorial&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla:en-US:official&amp;client=firefox-a" target="_blank">any of these</a>.  What I want to focus on are more practical applications of the PHP end of AJAX.  Surely you can understand the basics of passing variables to a PHP processing page, but let&#8217;s go over a few examples to understand what AJAX can accomplish for us.<br />
First of all, a soon-to-come feature on <a href="http://www.jeoreview.com">JeoReview</a> is on the page where boards can be created.  The issue is that there is a chance that someone will pick a board name that is already in use, and while the PHP is set up to catch the error, I would like for JavaScript to be able to handle it earlier and more quickly to prevent posting to pages over and over again.  So we will set up the JavaScript much like the examples show:</p>
<pre class="brush: javascript">
var xmlHttp;

function checkName(name) {
var url=&quot;checkName.php&quot;;
url=url+&quot;?n=&quot;+name;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open(&quot;GET&quot;,url,true);
xmlHttp.send(null);
}

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState==&quot;complete&quot;)
{
document.getElementById(&quot;nStatus&quot;).innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject(&quot;Msxml2.XMLHTTP&quot;);
}
catch (e)
{
xmlHttp=new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);
}
}

return xmlHttp;
}</pre>
<p>I would place this into a separate JavaScript file and link it to the page where the action takes place, but all that is really needed from this point is to add an event trigger to the form field to execute this function.  Something like this:</p>
<pre class="brush: php">

...

&lt;input type=&#039;text&#039; value=&#039;&#039; onchange=&#039;checkName(this.value);&#039; /&gt;

&lt;p id=&#039;nStatus&#039;&gt;Please enter a name for your board.&lt;/p&gt;

...
</pre>
<p>You can see then that the value from the form field will be checked in the function which will send the data to a PHP file which we must now define.  Whatever that PHP file &#8220;responds&#8221; with (or echoes back) will be displayed in the &#8216;p&#8217; tag we defined below the input field.  So let&#8217;s finish it off with the PHP file which must check the name entered against the boards already existing in the MySQL database, leading to something like this:</p>
<pre class="brush: php">

&lt;?php

//Connect to MySQL...

$name = mysql_real_escape_string($_GET[&#039;n&#039;]);

//We&#039;re using the GET method here, but there are applications of POST

$getBoards = mysql_query(&quot;SELECT `id` FROM `boards` WHERE `name`=&#039;$name&#039;&quot;);

if (mysql_num_rows($getBoards) == 0) { echo &quot;OK&quot;; }

else { echo &quot;Taken&quot;; }

?&gt;
</pre>
<p>Depending on your application, the echoed strings would be changed and perhaps even a bit more complex, but these work fine for the basic application we worked through.</p>
<p>As I noted above, we used the GET method, just like what is used in normal forms, where variables are passed through the URL to be accessed by the PHP file.  However, POST can be used and should be used in certain situations.  In general, they coincide with the general rules for form method choosing.  GET should be used for shorter requests of one or two variables and POST for multiple fields and especially those sent to the database.  Remember that the URL from GET can only be so long before cut off and may not be able to hold all the information from a long request.  Therefore, POST is certainly the most viable choice because it can be used in all applications by simply altering the method in the JavaScript and PHP and adding a few lines as noted on the tutorials listed above.</p>
<p>Still wondering where AJAX can come in handy?  We&#8217;ve all seen those handy &#8220;username checks&#8221; on registration pages and the suggestions provided by Google, Yahoo!, YouTube, and other big-name websites, and these all employ AJAX.   Whether you realized it or not because of their speed, these pages actually utilize more code than a typical PHP/ASP check, but they have certain disadvantages and will always be <a href="http://www.webmaster-forums.net/html-css-and-javascript/is-ajax-worth-it">up for debate</a>.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/03/working-with-ajax/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Regular Expressions May Cause Irregularity</title>
		<link>http://phpstarter.net/2009/02/regular-expressions-may-cause-irregularity/</link>
		<comments>http://phpstarter.net/2009/02/regular-expressions-may-cause-irregularity/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 06:00:14 +0000</pubDate>
		<dc:creator>Kurtis</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=379</guid>
		<description><![CDATA[Regular expressions seem rather complex, even like a foreign language to beginning programmers.  The mixture of symbols and characters can bring you to tears if you have a limited understanding, but with the knowledge of the significance of each symbol and construct, regular expressions can bring you from irregularity to peaceful contention bliss.


No related posts.]]></description>
			<content:encoded><![CDATA[<p>Regular expressions seem rather complex, even like a foreign language to beginning programmers.  The mixture of symbols and characters can bring you to tears if you have a limited understanding, but with the knowledge of the significance of each symbol and construct, regular expressions can bring you from irregularity to peaceful contention bliss.<span id="more-379"></span>A regular expression (regex for short) is a pattern describing a string of text.  There are levels of complexity for regular expressions, from simple strings of literal characters to repetition and grouping.</p>
<p>The most basic regular expression consists of a single <strong>literal character</strong> like <em>a</em>.  It will match that character in a string, but only on the first time, unless you apply repetitive properties to it or are more specific.  To use literal symbols, <em>[</em>, <em>\</em>,<em> ^</em>,<em> $</em>,<em> .</em>,<em> |</em>,<em> ?</em>,<em> *</em>,<em> (</em>,<em> )</em> you must escape them with a backslash (<em>\</em>).   For example, <strong>1\+1=2</strong> is the correct regular expression to match <strong>1+1=2</strong>.</p>
<p>Next are character classes or character sets.  Instead of specifying each letter of the alphabet or digit, it is possible instead to use sets of alphanumeric characters to match a string.  For instance <strong>six[a-z]+</strong> matches <strong>sixteen</strong>, <strong>sixty</strong>, and <strong>sixlet</strong>, among others.  Charcter sets should be placed within brackets and can include any range of lower-case characters, upper-case characters, digits from 0 to 9, hyphens, and underscores.</p>
<p>Regular expressions do have some shorthand character classes to ease your mind:  <strong>\d</strong> for all digits, <strong>\w</strong> for all alphanumeric characters or the underscore (&#8220;_&#8221;), <strong>\s</strong> for whitespace characters including tabs and line breaks, <strong>\t</strong> for tabs individually, <strong>\r</strong> for carriage returns, and <strong>\n</strong> for line feeds.  Remember that Windows text files use <strong>\r\n</strong> to terminate lines while UNIX text files simply use <strong>\n</strong>.</p>
<p>The dot or period (&#8220;.&#8221;) stands for any character except line break characters, meaning the same as <strong>[^\n]</strong>, where the <strong>^</strong> character means the negation of the following character (&#8220;anything but &#8230;&#8221;).  Often times a character class or negated character class is faster and more precise, so be cautious when using the dot.</p>
<p>Alternation allows for some choice in your regular expressions.  Using the vertical pipe bar (&#8220;|&#8221;), you can make <strong>sixteen</strong>, <strong>sixty</strong>, and <strong>sixlet</strong> all match the following regular expression: <strong>six(teen|ty|let)</strong>.  The question mark (&#8220;?&#8221;) allows for optional characters, for instance when dealing with British-English and American-English spellings (<strong>colou?r </strong>matches <strong>color</strong> and <strong>colour</strong>).</p>
<p>Lastly is the issue of repetition.  The asterisk (&#8220;*&#8221;) tells the engine to atempt to match the class zero or more times.  The plus sign (&#8220;+&#8221;) tries to match one or more times.  An integer in curly brackets following a class can specify an exact amount of instances.</p>
<p>Now for some examples.  The description above can seem quite weighty and boring, but some applications should solidify the ideas and clarify any confusion.</p>
<p><strong>Format of an e-mail address</strong></p>
<pre class="brush: php">

&lt;?php

$goodEmail = &quot;yourname@yourdomain.com&quot;;

$badEmail = &quot;thisIsNoEmailAtAll&quot;;

$niceTry = &quot;thisIsClose@domain&quot;;

$tooManyAts = &quot;thisIsCloseToo@@domain&quot;;

if (@preg_match(&#039;/[-a-zA-Z0-9]+@{1}[-a-zA-Z0-9]+[\.]{1}[a-zA-Z]{2,4}[\.]*[-a-zA-Z0-9]*/&#039;, $email)) {

echo &quot;Good email!&quot;;

}

else {

echo &quot;The format of your e-mail address is unacceptable.&quot;;

}

?&gt;
</pre>
<p>You can run through each e-mail address above, and the one named as good will work while the others will fail.  Notice that we allow for three or four letter domains as well as those like &#8220;co.uk&#8221; where the domain would have two periods (&#8220;.&#8221;).</p>
<p>Another common use of regular expressions is in URL rewriting.  For instance, on my website, JeoReview, when a user access a URL like &#8216;http://www.jeoreview.com/board/Board-Name&#8217; a different page is served to show the board itself.  In truth, that URL does not exist.  The regular expression, as placed in the <strong>.htaccess</strong> file, looks like this:</p>
<pre class="brush: php">

Options FollowSymLinks
RewriteEngine On
RewriteRule ^board/(.+)$ loadboard.php?name=$1
</pre>
<p>The caret (&#8220;^&#8221;) marks the beginning of the string and the dollar sign (&#8220;$&#8221;) marks the end.  Because nearly any character can be used for the board name, a dot (&#8220;.&#8221;) is used to match the name itself.  In truth, the better alternative would be to match exactly what characters can be used to increase speed and accuracy.  In any case, the <strong>$1</strong> refers to the first character case, and each subsequent integer is filled with the following character cases, though in this example there is only one.</p>
<p>There are plenty of other great uses of regular expressions.  Check some out by visiting these great resources and cheat sheets:</p>
<ul>
<li>Regular-Expressions Reference (<a href="http://www.regular-expressions.info/reference.html">http://www.regular-expressions.info/reference.html</a>)</li>
<li>Regular Expression Checker (<a href="http://regjex.com/">http://regjex.com/</a>)</li>
<li>Cheat Sheet (<a href="http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/">http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/</a>)</li>
<li>Using Regular Expressions and PHP (<a href="http://www.regular-expressions.info/php.html">http://www.regular-expressions.info/php.html</a><cite>)</cite></li>
</ul>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/02/regular-expressions-may-cause-irregularity/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Create Dynamic Banner Ads for Blogs &amp; News Sites</title>
		<link>http://phpstarter.net/2009/02/create-dynamic-banner-ads-for-blogs-news-sites/</link>
		<comments>http://phpstarter.net/2009/02/create-dynamic-banner-ads-for-blogs-news-sites/#comments</comments>
		<pubDate>Thu, 12 Feb 2009 12:00:48 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=248</guid>
		<description><![CDATA[When you visit a site, their usual advertisers might catch your eye once or twice, but after that, you forget it&#8217;s there. Designing a banner ad that automatically updates with information such as current sales or latest blog posts is a great way to get repeat clicks and return visitors. In this article, I&#8217;m going [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p>When you visit a site, their usual advertisers might catch your eye once or twice, but after that, you forget it&#8217;s there.  Designing a banner ad that automatically updates with information such as current sales or latest blog posts is a great way to get repeat clicks and return visitors.  In this article, I&#8217;m going to explain the code behind a dynamic ad implementation I use right here on this site.</p>
<p><span id="more-248"></span></p>
<p>If you go look at our <a href="/promote-this-site/">Promote this Site</a> page, you will see that a dynamic ad is offered that shows the most recent article on this site.  This is accomplished by creating a PHP script that reads this site&#8217;s <a href="/feed/">RSS Feed</a>, finding the latest post title, and overlaying it onto a graphic template.</p>
<p>I think this concept has potential with blogs and news sites because static banner ads become holes in the page to repeat visitors.  If I get somebody interested in this site once, then that banner will continue to catch their eyes when the article changes, and if they see a title that interests them again, they will visit the site again to read the latest article.</p>
<p>Here is some sample code based on what I have implemented on this site&#8217;s advertising page:</p>
<p style="text-align: right; "><a href="/samples/248/dyn_ad.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php">&lt;?php
	/* there is no need to call the feed up every time, so we will cache it for 1 hour */
	if (!file_exists('feed.cache') || filemtime('feed.cache') + 3600 &lt; time())
	{
		/**
		 * Looks like we don't have a recent copy, so we will use Snoopy to fetch the remote feed.
		 * See: http://phpstarter.net/2008/12/how-to-post-data-and-fetch-remote-pages-from-php-scripts/
		 */
		require('../includes/Snoopy.class.php');
		$snoopy = new Snoopy();
		
		/* set this to the RSS feed where we want to fetch the title from */
		$snoopy-&gt;fetch('http://phpstarter.net/feed/');
		
		/* save this to a local cache file so the RSS feed isn't called too often */
		file_put_contents('feed.cache', $snoopy-&gt;results);
	}
	
	/**
	 * We will use lastRSS to parse the feed.
	 * See: http://phpstarter.net/2009/01/load-rss-feeds-into-php-arrays-with-lastrss/
	 */
	require('../includes/lastRSS.php');
	$rss = new lastRss();
	
	/* load the cached file */
	$feed = $rss-&gt;get('feed.cache');
	
	/* this is the banner add that we will overlay the text on top of */
	$im = imagecreatefromgif('banner_ad_article.gif');
	
	/* set some colors */
	$black = imagecolorallocate($im, 0, 0, 0);
	$white = imagecolorallocate($im, 255, 255, 255);
	$orange = imagecolorallocate($im, 249, 160, 33);
	
	/* load the font we want to use */
	$f_domestic = '../includes/Domestic_Manners.ttf';
	
	/* this is the title taken from the RSS feed's first (or most recent) item */
	$title = $feed['items'][0]['title'];
	
	/* get the width of the to-be-printed text so we can center it */
	$bbox = imagettfbbox(12, 0, $f_domestic, $title);
	$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2);
	
	/* write the text to the base image */
	imagettftext($im, 12, 0, $x, 52, $orange, $f_domestic, $title);
	
	/* tell the browser that we are outputting a GIF image */
	header('Content-type: image/gif');
	
	/* render the image */
	imagegif($im);
?&gt;
</pre>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/02/create-dynamic-banner-ads-for-blogs-news-sites/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dynamically Converting Text to an Image</title>
		<link>http://phpstarter.net/2009/02/dynamically-converting-text-to-an-image/</link>
		<comments>http://phpstarter.net/2009/02/dynamically-converting-text-to-an-image/#comments</comments>
		<pubDate>Thu, 05 Feb 2009 06:00:28 +0000</pubDate>
		<dc:creator>Kurtis</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[GD Library]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=337</guid>
		<description><![CDATA[As CSS expands, so does web design as a whole, but where it still lacks (and most likely will always lack) is in the area of fonts.  Depending on the user's home computer and the actions he/she has taken on it, there are different fonts inherently available.  In this article, however, we will talk about bypassing the user's system and use the fonts you would like, via PHP and the GD library.


No related posts.]]></description>
			<content:encoded><![CDATA[<p>As CSS expands, so does web design as a whole, but where it still lacks (and most likely will always lack) is in the area of fonts.  Depending on the user&#8217;s home computer and the actions he/she has taken on it, there are different fonts inherently available.  In this article, however, we will talk about bypassing the user&#8217;s system and use the fonts you would like, via PHP and the GD library.<span id="more-337"></span></p>
<p>SEO experts would say using images to replace text is a bad idea because crawlers cannot read the text on images to analyze the content on your website, but this process will effectively use JavaScript to overcome that.  First, we&#8217;ll talk about the basic idea of creating an image with the text using a basic GD function, <a href="http://www.php.net/imageloadfont" target="_blank">imageloadfont()</a>.</p>
<pre class="brush: php">

&lt;?php

$font = imageloadfont(&quot;path/to/font.gdf&quot;);

?&gt;
</pre>
<p>You can see the file is in a strange format, but you can safely use <a href="http://www.wedwick.com/wftopf.exe" target="_blank">this program</a> to convert Windows font files to the necessary format.  Using this program within the spectrum of an image created with PHP, text can be written on the image with a certain font:</p>
<pre class="brush: php">

&lt;?php

$string = &quot;Your string goes here&quot;;

//You should define the next two based on the font you are using

$charwidth = ...;

$charheight = ...;

$imagewidth = ($charwidth*strlen($string));

$text = imagecreatetruecolor = ($imagewidth,$charheight);

$font = imageloadfont(&quot;path/to/font.gdf&quot;);

$white = imagecolorallocate($text,255,255,255);

$black = imagecolorallocate($text,0,0,0);

imagefill($text,0,0,$white);

imagestring($text,$font,0,0,$string,$black);

header(&quot;Content-type: image/png&quot;);

imagepng($text);

imagedestroy($text);

?&gt;
</pre>
<p>You can see the image is tailored to fit the text so there is no extra whitespace.  The only downside is that the &#8216;charwidth&#8217; and &#8216;charheight&#8217; variables have to be altered for different fonts.</p>
<p>With just this basic script you can turn text into an image, but how about returning to the overarching idea of dynamically turning text on a website into an image to utilize a desired font.  We&#8217;ll use some simple JavaScript for that.</p>
<p>Note: I&#8217;m using the most basic template of an HTML file to show the idea of the script.</p>
<pre class="brush: html">

&lt;html&gt;

&lt;head&gt;
&lt;title&gt;Text to Image Conversion&lt;/title&gt;

&lt;script type=&#039;text/javascript&#039;&gt;

function text2img() {

htwo = document.getElementsByTagName(&quot;h2&quot;);

for (i=0,tot=htwo.length;i&lt;tot;i++) {

text = htwo.innerHTML;

htwo.innerHTML = &quot;&lt;img src=&#039;text2img.php?s=&quot;+text+&quot;&#039; alt=&#039;&quot;+text+&quot;&#039; /&gt;&quot;;

}

&lt;/script&gt;
&lt;body onload=&quot;text2img();&quot;&gt;

&lt;h2&gt;This will become an image&lt;/h2&gt;

&lt;p&gt;This won&#039;t become an image.&lt;/p&gt;

&lt;h2&gt;This will also become an image.&lt;/h2&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Referencing the PHP file we created in the JavaScript of this file will turn each &#8216;h2&#8242; element into an image.  As I mentioned earlier, this will not mess with most search engines, though, because the text will remain for those where JavaScript is turned off.  Note, though, that that also means that users with JavaScript disabled will not see the fancy image either, just the plain text, so be sure to style it with CSS as well to insure the design of your website.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/02/dynamically-converting-text-to-an-image/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Editing Images &#8211; Resizing, Cropping, and more!</title>
		<link>http://phpstarter.net/2009/01/editing-images-resizing-cropping-and-more/</link>
		<comments>http://phpstarter.net/2009/01/editing-images-resizing-cropping-and-more/#comments</comments>
		<pubDate>Thu, 29 Jan 2009 06:00:09 +0000</pubDate>
		<dc:creator>Kurtis</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[GD Library]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=295</guid>
		<description><![CDATA[We&#8217;ve seen the graphics PHP can create for you, but how extensive is PHP&#8217;s ability to edit preexisiting images? In this article, I will explore some common functions that image editing software provides, but I&#8217;ll only use PHP.  We&#8217;ll focus mainly on cropping, resizing, flipping, and adding some effects to photos.Of course there are hundreds [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p>We&#8217;ve seen the graphics PHP can create for you, but how extensive is PHP&#8217;s ability to edit preexisiting images?  In this article, I will explore some common functions that image editing software provides, but I&#8217;ll only use PHP.  We&#8217;ll focus mainly on cropping, resizing, flipping, and adding some effects to photos.<span id="more-295"></span>Of course there are hundreds of image editing software packages available, many for free, but there is something to be said for editing images with PHP.  In fact, it just may be that working with graphics may mean utilizing internet programs to do what we typically do with programs like Photoshop.</p>
<p>First of all, let&#8217;s talk about cropping and resizing images as the two use the same function, just in a slightly different way.  The function is <a href="http://www.php.net/imagecopyresampled" target="_blank">imagecopyresampled()</a>.</p>
<pre class="brush: php">

&lt;?php

imagecopyresampled($new,$orig,$newX,$newY,$oldX,$oldY,$newWidth,$newHeight,$oldWidth,$oldHeight);

?&gt;
</pre>
<p>It&#8217;s quite a doozy, but all of the parameters are self-explanatory.  The variables &#8216;newX&#8217; and &#8216;oldX&#8217; refer to the new starting x-coordinates and old coordinate, respectively, and so on for the y-coordinates as well.</p>
<p>To crop an image, the idea is that we select a rectangular section of the original image and copy it to a new image.  Realize that in this case the &#8216;oldWidth&#8217; and &#8216;oldHeight&#8217; variables refer to the selection cropped, not the entire original image.  The process looks like this:</p>
<pre class="brush: php">

&lt;?php

//Cropping an image
header(&quot;Content-type: image/jpeg&quot;);

$top = ...; //Define upper-most pixel of selection

$bottom = ...; //Define lower-most pixel of selection

$left = ...; //Define left-most pixel of selection

$right = ...; //Define right-most pixel of selection
$image = imagecreatefromjpeg(&quot;/path/to/image.jpg&quot;); //Function matches file type

$new = imagecreatetruecolor(($right-$left),($bottom-$top)); //Becomes width,height

imagecopyresampled($new,$image,0,0,$left,$top,($right-$left),($bottom-$top),($right-$left),($bottom-$top));

imagejpeg($new,null,100);

imagedestroy($new);

imagedestroy($image);

?&gt;
</pre>
<p>Next is the very similar resizing function.  The only difference with resizing is that you don&#8217;t need to pick a certain area of the image; the entire image will be copied, simply at a different width and height.</p>
<pre class="brush: php">

&lt;?php

//Resizing an image
header(&quot;Content-type: image/jpeg&quot;);

$newWidth = ...; //Define new image&#039;s width

$newHeight = ...; //Define new image&#039;s height
$image = imagecreatefromjpeg(&quot;/path/to/image.jpg&quot;); //Function matches file type

list($width,$height) = getimagesize(&quot;/path/to/image.jpg&quot;); //Get old width and height

$new = imagecreatetruecolor($newWidth,$newHeight);

imagecopyresampled($new,$image,0,0,0,0,$newWidth,$newHeight,$width,$height);

imagejpeg($new,null,100);

imagedestroy($new);

imagedestroy($image);

?&gt;
</pre>
<p>You can see that these two ideas are very closely related, so there isn&#8217;t much difference between the two functions.  Next, let&#8217;s talk about flipping images, both horizontally and vertically.</p>
<p>There are two new functions we&#8217;ll talk about here, one that gets the color of the image at a specified pixel, and the other sets the color of the image at a specified pixel.</p>
<pre class="brush: php">

&lt;?php

$color = imagecolorat($image,$x,$y); //Get color

imagesetpixel($image,$x,$y,$color); //Set color

?&gt;
</pre>
<p>The only other thing we need to talk about is the idea of rolling through each pixel, and we&#8217;ll do this using two simultaneous &#8216;for&#8217; statements, one that runs through the image pixel-by-pixel horizontally, and another one that runs through each vertically at the same time.  This will allow us to get and set the color of each pixel in the image.</p>
<p>To flip an image horizontally, the left-most pixel becomes the right-most and vice-versa.  The top-most and bottom-most pixels switch when we flip vertically.  The process looks like this:</p>
<pre class="brush: php">

&lt;?php

$type = ...; //Define flip type (horizontal or vertical)

$image = imagecreatefromjpeg(&quot;/path/to/image.jpg&quot;); //Function matches file type
list($width,$height) = getimagesize($imagepath); //Get width and height
$new = imagecreatetruecolor($width,$height);  //Becomes new width and height
for ($x=0; $x&lt;$width; $x++) {
for ($y=0; $y&lt;$height; $y++) {
$color = imagecolorat($image,$x,$y); //Get pixel color
if ($type == &quot;horizontal&quot;) {
imagesetpixel($new,(($width-1)-$x),$y,$color);
}
else { //Type is vertical
imagesetpixel($new,$x,(($height-1)-$y),$color);
}
}
}

imagejpeg($new,null,100);

imagedestroy($new);

imagedestroy($image);

?&gt;
</pre>
<p>Last, but not least, I&#8217;ll show you how to apply several different types of effects to an image, and this doesn&#8217;t require any special calculations, just one function, <a href="http://php.net/imagefilter" target="_blank">imagefilter()</a>.  You can read about all of the different filters available, but the main ones are blurring, converting to gray scale, and changing contrast/brightness.</p>
<p>With these GD functions in tow, there is very little you can&#8217;t do with PHP.  Alright, so there&#8217;s still quite a bit that PHP can&#8217;t do with images practically, but it&#8217;s only a matter of time before programmers are able to apply even the most complex Photoshop functions to PHP.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/01/editing-images-resizing-cropping-and-more/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sort Posts by Comment Count in WordPress</title>
		<link>http://phpstarter.net/2009/01/sort-posts-by-comment-count-in-wordpress/</link>
		<comments>http://phpstarter.net/2009/01/sort-posts-by-comment-count-in-wordpress/#comments</comments>
		<pubDate>Tue, 20 Jan 2009 12:00:10 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Wordpress]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=263</guid>
		<description><![CDATA[I use this technique to show the most popular posts on our homepage, and although this isn&#8217;t a core feature in WordPress, it&#8217;s not all that hard to do. All it takes is a little PHP and a single edit to one of your WordPress template files. I decided not to use a plugin because [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p>I use this technique to show the most popular posts on our homepage, and although this isn&#8217;t a core feature in WordPress, it&#8217;s not all that hard to do.  All it takes is a little PHP and a single edit to one of your WordPress template files.</p>
<p><span id="more-263"></span></p>
<p>I decided not to use a plugin because I find it easier to just edit the templates directly.  Here is the code:</p>
<pre class="brush: php">
&lt;?php
$results = $wpdb-&gt;get_results(&quot;SELECT ID, comment_count FROM wp_posts WHERE post_type = &#039;post&#039; &amp;&amp; post_status = &#039;publish&#039; ORDER BY comment_count DESC LIMIT 5&quot;);
foreach ($results as $r):
	query_posts(array(&#039;p&#039; =&gt; $r-&gt;ID));
	while (have_posts()):
		the_post();
?&gt;
&lt;!-- regular wordpress loop code goes here --&gt;
&lt;?php endwhile; endforeach; ?&gt;
</pre>
<p>This code manually calls a SQL query because there is no template tag that supports this method of sorting as of WordPress 2.7.  We are only querying for the post IDs because we will use that ID to call up the WordPress loop which will allow us to use the normal template tags inside the manual WordPress loop.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/01/sort-posts-by-comment-count-in-wordpress/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
