<?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>Lateral Code &#187; php</title>
	<atom:link href="http://www.lateralcode.com/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.lateralcode.com</link>
	<description>A Web Development Blog Focused on Code and Technology</description>
	<lastBuildDate>Fri, 15 Jul 2011 03:00:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=abc</generator>
		<item>
		<title>Streamlining MySQL Insert Queries</title>
		<link>http://www.lateralcode.com/mysql-insert-queries/</link>
		<comments>http://www.lateralcode.com/mysql-insert-queries/#comments</comments>
		<pubDate>Fri, 31 Dec 2010 23:21:24 +0000</pubDate>
		<dc:creator>Karthik Viswanathan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.lateralcode.com/?p=1719</guid>
		<description><![CDATA[PHP and MySQL have often been known as two peas in a pod. Unfortunately, when you use PHP to insert information into a MySQL database, you often have to write large queries that take up much of your time. Not only that, but you also have to clean user input. This quick tip aims to [...]]]></description>
			<content:encoded><![CDATA[<p>PHP and MySQL have often been known as two peas in a pod. Unfortunately, when you use PHP to insert information into a MySQL database, you often have to write large queries that take up much of your time. Not only that, but you also have to clean user input. This quick tip aims to streamline your efficiency by writing a simple function to do this job for you.</p>
<h2>Write helper functions</h2>
<p><img src="http://www.lateralcode.com/wp-content/uploads2/mysql-insert-queries/1.jpg" alt="Helper functions" class="list-post-img"/></p>
<p>Before we start working on the main program, we first need to create two helper functions which will be used later on:</p>
<p><span id="more-1719"></span></p>
<pre><code>function query( $mysql ) {
	$result = mysql_query( $mysql ) or die( mysql_error() );
	return $result;
}</code></pre>
<p>This first function runs a MySQL query and returns the result. It will also exit if the query fails to execute.</p>
<pre><code>function clean( $input ) {
	if( get_magic_quotes_gpc() )
		$input = stripslashes( $input );
	return mysql_real_escape_string( $input );
}</code></pre>
<p>User input is never guaranteed to be safe. This function cleans input and prevents malicious attacks.</p>
<p>Now we&#8217;re ready to start the main program.</p>
<h2>Create the function prototype</h2>
<p>To begin, we will create a function that requires two parameters: a table name and an associative array (map) of MySQL field names and their respective values. </p>
<pre><code>function insertInto( $table, $info )</code></pre>
<p>After the function finishes executing, a new row of the database will be created with values corresponding to those in <code>$info</code>.</p>
<h2>Find the columns in the MySQL table</h2>
<p><img src="http://www.lateralcode.com/wp-content/uploads2/mysql-insert-queries/2.jpg" alt="MySQL columns" class="list-post-img"/></p>
<p>In order to run an insert query, we must know what columns are in the given MySQL table. This can be done using the following query:</p>
<pre><code>$cols = query( "SHOW COLUMNS FROM $table" );</code></pre>
<h2>Loop through the columns and store the necessary information</h2>
<p>For each column that is found, we need to store the value in the <code>$info</code> map that corresponds to the its name:</p>
<pre><code>$fields = array();
while( ( $row = mysql_fetch_assoc( $cols ) ) !== false ) {
	// ignore primary keys, which are often times auto-incremented ids
	if( $row[ 'Key' ] === 'PRI' )
		continue;

	$name = $row[ 'Field' ];
	$fields[ $name ] = clean( $info[ $name ] );
	if( strpos(  $row[ 'Type' ], 'int' ) === false )
		$fields[ $name ] = "'" . $fields[ $name ] . "'";
}</code></pre>
<p>Notice how the value is cleaned before being stored inside the <code>$fields</code> array. In addition, if the type of the MySQL field is some sort of string, the value must be enclosed in single quotes for the query to work properly.</p>
<h2>Construct the query and run it</h2>
<p><img src="http://www.lateralcode.com/wp-content/uploads2/mysql-insert-queries/3.jpg" alt="MySQL query" class="list-post-img"/></p>
<p>Now that we have all the information, we just need to construct a query based off of the keys (which are MySQL field names) and values (the corresponding information stored in each field) of the <code>$fields</code> array:</p>
<pre><code>$keys = array_keys( $fields );
$values = array_values( $fields );

$str = "INSERT INTO $table(" . implode( $keys, ', ' )  . " ) VALUES( " . implode( $values, ', ' ) . " )";
query( $str );</code></pre>
<p>PHP&#8217;s implode function is perfect in this situation, as it places all array elements into a string separated by a given delimiter. By using a comma and space as the delimiter, the MySQL query is easily formed.</p>
<h2>Conclusion</h2>
<p>The function is now complete. It can be used in a form handler by simply passing in the <code>$_POST</code> or <code>$_GET</code> array as a parameter:</p>
<pre><code>// post data
insertInto( 'tableName', $_POST );

// get data
insertInto( 'tableName', $_GET );</code></pre>
<p>And that&#8217;s really all there is to it. The full function along with the helpers can be found below:</p>
<pre><code>function insertInto( $table, $info ) {
	$cols = query( "SHOW COLUMNS FROM $table" );

	$fields = array();
	while( ( $row = mysql_fetch_assoc( $cols ) ) !== false ) {
		if( $row[ 'Key' ] === 'PRI' )
			continue;

		$name = $row[ 'Field' ];
		$fields[ $name ] = clean( $info[ $name ] );
		if( strpos(  $row[ 'Type' ], 'int' ) === false )
			$fields[ $name ] = "'" . $fields[ $name ] . "'";
	}

	$keys = array_keys( $fields );
	$values = array_values( $fields );

	$str = "INSERT INTO $table(" . implode( $keys, ', ' )  . " ) VALUES( " . implode( $values, ', ' ) . " )";
	query( $str );
}

function query( $mysql ) {
	$result = mysql_query( $mysql ) or die( mysql_error() );
	return $result;
}

function clean( $input ) {
	if( get_magic_quotes_gpc() )
		$input = stripslashes( $input );
	return mysql_real_escape_string( $input );
}</code></pre>
<p>For those of you who prefer something more MySQLi-related (MySQL Improved), take a look at my <a href="https://github.com/karthikv/silent-boss/blob/master/boss/dependencies/db.php">active records database class on GitHub</a>, which can streamline your select, insert, update, and delete queries. It supports where clauses, joins, ordering, limits, and more.</p>
<p>Thanks for reading!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lateralcode.com/mysql-insert-queries/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Under the Hood: Custom WordPress Pagination System</title>
		<link>http://www.lateralcode.com/wordpress-pagination/</link>
		<comments>http://www.lateralcode.com/wordpress-pagination/#comments</comments>
		<pubDate>Sun, 07 Nov 2010 19:07:36 +0000</pubDate>
		<dc:creator>Karthik Viswanathan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://www.lateralcode.com/?p=1641</guid>
		<description><![CDATA[If you use WordPress, you know that after a few months of blogging, there are far too many posts to display simultaneously. To reduce the loading time of your website, you could consider a pagination system, in which you display only a certain number of posts per page. By giving the user the ability to [...]]]></description>
			<content:encoded><![CDATA[<p>If you use WordPress, you know that after a few months of blogging, there are far too many posts to display simultaneously. To reduce the loading time of your website, you could consider a pagination system, in which you display only a certain number of posts per page. By giving the user the ability to navigate through pages, your posts will all be available and left intact.</p>
<p><img src="http://www.lateralcode.com/wp-content/uploads2/wordpress-pagination/1.jpg" alt="Pagination" class="list-post-img"/></p>
<h2>Pagination? How?</h2>
<p>Unfortunately, changing the posts per page option under your WordPress reading settings does not automatically create pagination; rather, you have two options:</p>
<ol>
<li>Use WordPress&#8217; in-built functions (<code>posts_nav_link</code>, <code>previous_posts_link</code> and/or <code>next_posts_link</code>) to allow the user to navigate between pages.</li>
<li>Create your own pagination system.</li>
</ol>
<p>The main problem with the first option is that WordPress only allows the user to go to the next or previous page; there is no way to jump a set of pages without having to visit everything in-between. Consequently, the bottleneck is in the user-experience.</p>
<p>With the second option, the burden is on the developer. Even though it requires more coding, the user experience is not compromised. As a result, today&#8217;s article will focus on how to write your own <strong>custom WordPress pagination system</strong>. To view a demo, see <a href="/#pagination">Lateral Code&#8217;s pagination</a>.</p>
<p><span id="more-1641"></span></p>
<h2>Specifications</h2>
<p>Before we begin coding, let&#8217;s lay out our specifications. Our pagination system will ensure that the user can visit the first and last page. It will also provide links to pages within a certain range of the current page. We will call this the scope.</p>
<p>For example, if we have twenty pages, our scope is set to two, and the user is currently on page 5, our pagination would look like this:</p>
<pre><code>1	...	3	4	5	6	7	...	20</code></pre>
<p>Note that the ellipses (&#8230;) are just used as visual indicators of a jump in page number.</p>
<p>Since three, four, six, and seven are two of less numbers away from five, they are displayed. In like manner, if we had our scope to set to one, the pagination would be:</p>
<pre><code>1	...	4	5	6	...	20</code></pre>
<p>In this example, three and seven are removed because their range from our current page number, five, is two. This is greater than the scope of one.</p>
<p>Although this system seems to work, what if the scope is two and the current page number is one? No previous page exists to link to. As a result, we can just add more pages to the other side:</p>
<pre><code>1	2	3	4	5	...	20</code></pre>
<p>Since we missed two pages to the left of one, we added them to the right. That&#8217;s why pages four and five are visible. Using the same principal, if our current page is twenty, the pagination would be:</p>
<pre><code>1	...	16	17	18	19	20</code></pre>
<p>In this case, the pages are added to the left since they can&#8217;t be placed to the right.</p>
<h2>Code</h2>
<p>Now that our specification is complete, let&#8217;s begin coding. We will create a pagination function in functions.php which will be later used in our index.php template. The scope, or range, will have a default value of two:</p>
<pre><code>function pagination( $scope = 2 )</code></pre>
<p>Our first task is to find the number of pages and the current page:</p>
<pre><code>global $wp, $posts_per_page;

$numPages = (int) ( wp_count_posts()->publish / $posts_per_page );
if( $numPages < = 1 )
	return; // no need for pagination with one page

$queryVars = $wp->query_vars;
$curPage = isset( $queryVars[ 'paged' ] ) ? (int) $queryVars[ 'paged' ] : 1;</code></pre>
<p><code>wp_count_posts()->publish</code> represents the total number of published posts. <code>$posts_per_page</code> is the posts per page setting under the reading area of the WordPress dashboard. Dividing the former by the latter will give us the number of pages.</p>
<p>To find the current page, we can use the <code>$wp->query_vars</code> array. If the <code>paged</code> key exists, its value will be the page. Otherwise, the user is on page one.</p>
<p>After finding the statistics, we need to create the pagination. Although we know that the first and last page will be included, the middle has yet to be found:</p>
<pre><code>// page bounds
$start = $curPage - $scope;
$end = $curPage + $scope;

// if we can't satisfy the scope (add enough pages) on one side,
// add pages to the other side
if( $start < = 1 ) {
	$end += ( 1 - $start );
	$start = 2;
}
else if( $end >= $numPages ) {
	$start -= ( $end - $numPages );
	$end = $numPages - 1;
}

// limit the start and end to their extreme values
$start = max( $start, 2 );
$end = min( $end, $numPages - 1 );</code></pre>
<p><code>$start</code> and <code>$end</code> correspond the left-most and right-most page value, respectively. The <code>if</code> block is used to display more pages on one side if they cannot be added to the other, as per the last two examples of the specification. Finally, <code>$start</code> and <code>$end</code> are capped at their boundary values to ensure they are within range.</p>
<p>Now that we have the pages, we can aggregate them into an array:</p>
<pre><code>$pagesToLinkTo = array( 1 );
for( $page = $start; $page < = $end; $page++ )
	$pagesToLinkTo[] = $page;
$pagesToLinkTo[] = $numPages;</pre>
<p></code></p>
<p>Finally, we have to process the array and output list elements corresponding to each page number:
</pre>
<pre><code>$prevPage = $pagesToLinkTo[0];
foreach( $pagesToLinkTo as $page ) {
	if( $page - $prevPage > 1 ) // skipped a few pages
		echo '&lt;li&gt;...&lt;/li&gt;'; // add a spacer

	// echo the link
	echo '&lt;li&gt;&lt;a href="' . get_bloginfo( 'home' ) . '/page/' . $page . '"&gt;' . $page . '&lt;/a&gt;&lt;/li&gt;';
	$prevPage = $page;
}</code></pre>
<p>The URL of each page is http://example.com/page/number, where http://example.com is the home of the WordPress site and number is the page number. We link to this URL for each page that we output.</p>
<p>To determine whether we need to add ellipses, we compare the current page with the previous page. If the difference is greater than one, we skipped a few pages and have to add the spacer.</p>
<p>Here is the pagination function as a whole:</p>
<pre><code>function pagination( $scope = 2 ) {
   	global $wp, $posts_per_page;

	$numPages = (int) ( wp_count_posts()->publish / $posts_per_page );
	if( $numPages < = 1 )
		return; // no need for pagination

	$queryVars = $wp->query_vars;
	$curPage = isset( $queryVars[ 'paged' ] ) ? (int) $queryVars[ 'paged' ] : 1;

	// page bounds
	$start = $curPage - $scope;
	$end = $curPage + $scope;

	// if we can't satisfy the scope (add enough pages) on one side,
	// add pages to the other side
	if( $start < = 1 ) {
		$end += ( 1 - $start );
		$start = 2;
	}
	else if( $end >= $numPages ) {
		$start -= ( $end - $numPages );
		$end = $numPages - 1;
	}

	// limit the start and end to their extreme values
	$start = max( $start, 2 );
	$end = min( $end, $numPages - 1 );

	$pagesToLinkTo = array( 1 );
	for( $page = $start; $page < = $end; $page++ )
		$pagesToLinkTo[] = $page;
	$pagesToLinkTo[] = $numPages;

	$prevPage = $pagesToLinkTo[0];
	foreach( $pagesToLinkTo as $page ) {
		if( $page - $prevPage > 1 ) // skipped a few pages
		echo '&lt;li&gt;...&lt;/li&gt;'; // add a spacer

		// echo the link
		echo '&lt;li&gt;&lt;a href="' . get_bloginfo( 'home' ) . '/page/' . $page . '"&gt;' . $page . '&lt;/a&gt;&lt;/li&gt;';
		$prevPage = $page;
	}
}</code></pre>
<h2>Wrapping Up</h2>
<p>To finalize our system, we&#8217;ll have to call this function in our index.php template:</p>
<pre>&lt;ul id="pagination"&gt;
	&lt;?php pagination(); ?&gt;
&lt;/ul&gt;</pre>
<p>Well, that was easy, eh? Remember to style the pagination in accordance to your site&#8217;s design. To view a demo, see the <a href="/#pagination">bottom of Lateral Code&#8217;s home page</a>.</p>
<p>Thanks for reading!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lateralcode.com/wordpress-pagination/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automated Uptime Verification</title>
		<link>http://www.lateralcode.com/automated-uptime-verification/</link>
		<comments>http://www.lateralcode.com/automated-uptime-verification/#comments</comments>
		<pubDate>Tue, 24 Aug 2010 22:58:17 +0000</pubDate>
		<dc:creator>Patrick Lin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.lateralcode.com/?p=1618</guid>
		<description><![CDATA[If you have ever administered a website, you know that downtime is unavoidable. Creating a system to automatically check if your website is up can help deal with downtime and provide a better user experience. Doing so is quite simple if you have the following tools available: A web server other that that on which [...]]]></description>
			<content:encoded><![CDATA[<p>If you have ever administered a website, you know that downtime is unavoidable. Creating a system to automatically check if your website is up can help deal with downtime and provide a better user experience. Doing so is quite simple if you have the following tools available:</p>
<p><img src="http://www.lateralcode.com/wp-content/uploads2/automated-uptime-verification/1.jpg" alt="Automated Uptime Verification" class="list-post-img" /></p>
<ul>
<li>A web server other that that on which the website is hosted</li>
<li>Cron (if you do not have this, you can use an online service)</li>
<li>PHP with libcurl support</li>
<li>PHP with mail support (optional)</li>
</ul>
<p><span id="more-1618"></span></p>
<h2>Setting up PHP and libcurl</h2>
<p>In case you don&#8217;t know, libcurl (and its cousin cURL) are tools for working with URLs and web pages. Provided that you have libcurl support and PHP, you can check if a site is active by using the following function:</p>
<pre><code>function checkURL($url) {
	$return = array();
	$curl = curl_init(); // Initialize libcurl
	// set options:
	curl_setopt ($curl, CURLOPT_URL, $url ); // URL to visit
	curl_setopt ($curl, CURLOPT_RETURNTRANSFER, TRUE); // returns a string instead of echoing to screen
	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); // follows redirects (recursive)
	curl_setopt($curl, CURLOPT_NOBODY, TRUE); // Only get headers, not content (saves on time)
	$result = curl_exec($curl);
	$errno = curl_errno($curl);
	if ( $errno != 0 ) { // curl_errno returns 0 if no error, otherwise returns the error code
		$return['message'] = "An error occurred while trying to $url! ".curl_err($curl); // If there was an error, return the error message
		$return['success'] = false;
	} else {
		$http = curl_getinfo($curl, CURLINFO_HTTP_CODE); // Get the HTTP return code
		$return['code'] = $http;
		if ( $http &gt;= 200 &#038;&#038; $http &lt; 300 ) { // An HTTP code greater than 200 and less than 300 means a successful load
			$return['message'] = "$url is up! ($http)";
			$return['success'] = true;
		} else {
			$return['message'] = "$url is down! ($http)";
			$return['success'] = false;
		}
	}
	curl_close($curl);
        return $return;
}
</code></pre>
<p>This function returns an array containing a success boolean (true, your site is up or false, your site is down) and a corresponding message string. Now that our checking works as specified, let&#8217;s move on to the notifications.</p>
<h2>Notifications</h2>
<p>In this section, we will present two ways to receive notifications.</p>
<h3>Notification by E-mail/SMS</h3>
<p>After checking the URL, you can use the PHP mail function to send the status to your e-mail account. On the other hand, you can find out the address for your SMS by sending a text to your own e-mail. For example, Verizon phones have the e-mail address &lt;phone number&gt;@vtext.com</p>
<p>The code:</p>
<pre><code>$result = checkURL($your_url);
if ( $result['success'] == true; )
	$subject = "Your site is still up!";
else
	$subject = "Oh no! Your site is down."
mail($your_email, $subject, $result['message']);
</code></pre>
<p>As you can see, this is a fairly easy method with minimal code.</p>
<h3>Push notifications for your iDevice</h3>
<p>If you have an iDevice, such as an iPhone or iPod Touch, you can use <a href="http://en.wikipedia.org/wiki/Apple_Push_Notification_Service">push notifications</a> as an alternative to e-mail or SMS.</p>
<p>First, download the app <a href="http://itunes.apple.com/us/app/pushme-to-free-instant-messages/id343341970?mt=8">pushme.to</a> and make and account. Take note of your username. This app will allow you to send pushed messages to your iDevice.</p>
<p>Then, you will need the following function:</p>
<pre><code>function pushmeto($username, $message) {
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, "http://pushme.to/$username/");
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($curl, CURLOPT_POST, TRUE);
	curl_setopt($curl, CURLOPT_POSTFIELDS, "message=".urlencode($message);
	curl_exec($ch);
	curl_close($ch);
}
</code></pre>
<p>Usage is simple:</p>
<pre><code>$result = checkURL($your_url);
pushmeto($your_username, $result['message']);
</code></pre>
<h2>Automation</h2>
<p>Cron can be used to automate the checking uptime process. If you don&#8217;t have cron on your server (which is rare), you can use an online service such as <a href="http://www.onlinecronjobs.com/">Online Cron Jobs</a>.</p>
<p>Cron jobs are set using the following format:</p>
<pre>
[min] [hour] [date] [month] [day_of_week] [command]
</pre>
<p>A cron job set to run at 7am every Tuesday would look like this:</p>
<pre>
0 7 * * 2 [command]
</pre>
<p>For more information on how to use cron, see this <a href="http://adminschoice.com/crontab-quick-reference">quick reference</a>.</p>
<p>As for the command, you can use the following (which assumes you saved the uptime verification code to a file called uptime.php):</p>
<pre>
php /path/to/uptime.php > /dev/null 2>&#038;1
</pre>
<p>Remember, of course, to change the path.</p>
<p>Once activated by the automated command, the code in the PHP file will check if your site is up and notify you. You can set this to occur as often as you want.</p>
<h2>Conclusion</h2>
<p>Do you have any other ways to monitor uptime? If so, please join the discussion below!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lateralcode.com/automated-uptime-verification/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Coding a Color Manager with Object-Oriented PHP</title>
		<link>http://www.lateralcode.com/color-manager/</link>
		<comments>http://www.lateralcode.com/color-manager/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 23:57:17 +0000</pubDate>
		<dc:creator>Karthik Viswanathan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.lateralcode.com/?p=1483</guid>
		<description><![CDATA[Colors are a vital part of web design. They can easily make or break a design. Often times, designers are interested in modifying colors by mixing, fading, or brightening them. This will be the basis for today&#8217;s article. We&#8217;re going to go through the process of creating a simple color manager with object-oriented PHP. Rather [...]]]></description>
			<content:encoded><![CDATA[<p>Colors are a vital part of web design. They can easily make or break a design. Often times, designers are interested in modifying colors by mixing, fading, or brightening them. This will be the basis for today&#8217;s article.</p>
<p><img src="http://www.lateralcode.com/wp-content/uploads2/color-manager/1.jpg" alt="Color Wheel" class="list-post-img"/></p>
<p>We&#8217;re going to go through the process of creating a simple color manager with object-oriented PHP. Rather than focusing on multiple forms of modification, our color manager will perform one basic function: fading. Given a base color (hexadecimal) and a fade percentage, we will calculate a new, faded color.</p>
<p><a href="http://demo.lateralcode.com/color-manager/" class="view button"><span>View the color manager</span></a> <a href="http://www.lateralcode.com/wp-content/uploads2/color-manager/color-manager.zip" class="dl button"><span>Download the files</span></a></p>
<p><span id="more-1483"></span></p>
<p>Fading, when taken from a red-green-blue (RGB) color perspective, only involves linear interpolation. In other words, to fade a color from blue <code>rgb( 0, 0, 255 )</code> to white <code>rgb( 255, 255, 255 )</code>, each color component must be increased by a percentage of the difference to the target component.</p>
<p>To elucidate this statement, consider the following example: if you wanted to fade 10% from blue to white, you would calculate the components as such:</p>
<pre><code>original color (blue) = rgb( 0, 0, 255 )
target color (white)  = rgb( 255, 255, 255 )
fade percent          = 10%

original color's red component = 0
target color's red component   = 255
difference in components       = 255 - 0
                               = 255

new red component = original red component + difference in components * fade percent
new red component = 0 + 255 * .10
                  = 25.5</code></pre>
<p>This process would be repeated with the two other components. The new color (after all calculations) would be:</p>
<pre><code>rgb( 25.5, 25.5, 255 );</code></pre>
<p>If you were to look at this color, it would be a faded blue.</p>
<p>Since we are working with a hexadecimal color, it would be beneficial to convert it to RGB, fade it, and then convert back. Although there are ways to fade directly in hexadecimal format, this path begs the use of object-oriented PHP and does not require a knowledge of bit manipulation.</p>
<p><img src="http://www.lateralcode.com/wp-content/uploads2/color-manager/2.jpg" alt="Hexadecimal" class="list-post-img"/></p>
<p>Before starting to code, you must first understand how to convert from hexadecimal to RGB and back. The first two letters/digits in a hex color represent the red component in an RGB color. In like manner, the third and fourth letters/digits represent the green component. Finally, the last two digits represent the blue component. After splitting the hex color into these three sets, each one must be converted from base 16 to base 10 to get the final RGB color:</p>
<pre><code>hex color (white) = FFFFFF

red component = FF (base 16)
              = 255 (base 10)

green component = FF (base 16)
                = 255 (base 10)

blue component = FF (base 16)
               = 255 (base 10)

hex color (white) = rgb( 255, 255, 255 )</code></pre>
<p>To go from RGB to hexadecimal, convert each component to base 16 and concatenate them:</p>
<pre><code>rgb color (white) = ( 255, 255, 255 )

red component = 255 (base 10)
              = FF (base 16)

green component = 255 (base 10)
                = FF (base 16)

blue component = 255 (base 10)
               = FF (base 16)

rgb color (white) = hex FFFFFF</code></pre>
<p>Now we can move on to the implementation. To begin, we will first write a <code>HexColor</code> class, which will hold a <code>$hex</code> variable representing the hex string. This class will provide a function to convert to an RGB color:</p>
<pre><code>class HexColor {
	private $hex;

	public function HexColor( $hex )
	{
		if( strpos( $hex, '#' ) === 0 )
			$this->hex = substr( $hex, 1 );
		else
			$this->hex = $hex;
	}

	public function getHexString()
	{
		return $this->hex;
	}

	public function convertToRGB()
	{
		// first two digits represent red, next two blue, and the last two green
		$red = substr( $this->hex, 0, 2 );
		$green = substr( $this->hex, 2, 2 );
		$blue = substr( $this->hex, 4, 2 );

		// convert from hexadecimal to base 10
		$red = (int) base_convert( $red, 16, 10 );
		$green = (int) base_convert( $green, 16, 10 );
		$blue = (int) base_convert( $blue, 16, 10 );

		return new RGBColor( $red, $green, $blue );
	}

	public static function isValid( $hex )
	{
		return (bool) preg_match( '/^(#)?[a-zA-Z0-9]{6}$/', $hex );
	}

	public function __toString()
	{
		return $this->hex;
	}
}</code></pre>
<p>Note that the <code>isValid</code> function is used to check whether a given string is a valid hex color.</p>
<p><img src="http://www.lateralcode.com/wp-content/uploads2/color-manager/3.jpg" alt="RGB" class="list-post-img"/></p>
<p>Next is the <code>RGBColor</code> class, which contains similar functionality and a <code>fadeTo</code> function based off of the calculations explained at the beginning of this article:</p>
<pre><code>class RGBColor {
	private $red, $green, $blue;

	public function RGBColor( $red, $green, $blue )
	{
		$this->red = $this->clamp( $red );
		$this->green = $this->clamp( $green );
		$this->blue = $this->clamp( $blue );
	}

	public function getRed()
	{
		return $this->red;
	}

	public function getGreen()
	{
		return $this->green;
	}

	public function getBlue()
	{
		return $this->blue;
	}

	public function fadeTo( $rgbColor, $percent )
	{
		$newRed = ( 1 - $percent ) * $this->red + $percent * $rgbColor->getRed();
		$newGreen = ( 1 - $percent ) * $this->green + $percent * $rgbColor->getGreen();
		$newBlue = ( 1 - $percent ) * $this->blue + $percent * $rgbColor->getBlue();

		return new RGBColor( (int) $newRed, (int) $newGreen, (int) $newBlue );
	}

	public function convertToHex()
	{
		$newRed = base_convert( $this->red, 10, 16 );
		$newGreen = base_convert( $this->green, 10, 16 );
		$newBlue = base_convert( $this->blue, 10, 16 );

		$newRed = $this->addZero( $newRed );
		$newGreen = $this->addZero( $newGreen );
		$newBlue = $this->addZero( $newBlue );

		return new HexColor( $newRed . $newGreen . $newBlue );
	}

	private function addZero( $colorValue )
	{
		if( strlen( $colorValue ) == 1 )
			$colorValue = '0' . $colorValue;
		return $colorValue;
	}

	private function clamp( $colorValue )
	{
		// clamp colorValue in interval [0, 255]
		return max( 0, min( 255, $colorValue ) );
	}

	public function __toString()
	{
		return '(' . $this->red . ', ' . $this->green . ', ' . $this->blue . ')';
	}
}</code></pre>
<p>Since RGB color values can only be in the 0-255 range, the <code>clamp</code> function is used to ensure this is true. In addition, the <code>addZero</code> function makes sure the hex color is six digits long by prepending the necessary 0s.</p>
<p>Given these classes, a <code>$hex</code> string, and a <code>$fade</code> percentage, the process to fade a hex color is as follows:</p>
<ol>
<li>Instantiate a <code>HexColor</code> object with the <code>$hex</code> string</li>
<li>Convert it to an <code>RGBColor</code></li>
<li>Call the <code>fadeTo</code> function with the given <code>$fade</code> percentage and the color white</li>
<li>Convert the <code>RGBColor</code> back to a <code>HexColor</code> and display it</li>
</ol>
<p>In addition, to make this more flexible, we can change the third step to darken the color (fade to black) if the fade percentage is negative. These instructions lead to the following code:</p>
<pre><code>$hexColor = new HexColor( $hex );

// target color is white by default
$targetColor = new RGBColor( 255, 255, 255 );

// want to darken the color--target is black
if( $fade < 0 ) {
	$targetColor = new RGBColor( 0, 0, 0 );
	$fade = -$fade; // make fade positive
}

$rgbColor = $hexColor->convertToRGB();

// fade / 100 is the percentage
$fadedColor = $rgbColor->fadeTo( $targetColor, $fade / 100 );
echo $fadedColor->convertToHex();</code></pre>
<p>Combined with some AJAX, form handling, and CSS (which I won&#8217;t be going over, as this was a lesson in object-oriented PHP), this code ultimately results in a simple color manager, which you may view/download using the buttons below:</p>
<p><a href="http://demo.lateralcode.com/color-manager/" class="view">View the color manager</a> <a href="http://www.lateralcode.com/wp-content/uploads2/color-manager/color-manager.zip" class="dl">Download the files</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.lateralcode.com/color-manager/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Store Arrays in a Database</title>
		<link>http://www.lateralcode.com/store-array-database/</link>
		<comments>http://www.lateralcode.com/store-array-database/#comments</comments>
		<pubDate>Wed, 16 Jun 2010 07:01:39 +0000</pubDate>
		<dc:creator>Karthik Viswanathan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.lateralcode.com/?p=1475</guid>
		<description><![CDATA[When working with databases, it is sometimes necessary to store an array in a MySQL field. Unfortunately, there is no way to directly pass in an array as a parameter. As a result, storing these data structures is a bit more complex, but by no means hard or impossible. To convert any array (or any [...]]]></description>
			<content:encoded><![CDATA[<p>When working with databases, it is sometimes necessary to store an array in a MySQL field. Unfortunately, there is no way to directly pass in an array as a parameter. As a result, storing these data structures is a bit more complex, but by no means hard or impossible.</p>
<p><img src="http://www.lateralcode.com/wp-content/uploads2/store-array-database/1.jpg" alt="Array" class="list-post-img"/></p>
<p><span id="more-1475"></span></p>
<p>To convert any array (or any object) into a string using PHP, call the <code>serialize</code> function:</p>
<pre><code>$array = array( 1, 2, 3 );
$string = serialize( $array );
echo $string;</code></pre>
<p><code>$string</code> will now hold a string version of the array. The output of the above code is as follows:</p>
<pre><code>a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}</code><code></code></pre>
<p>To convert back from the string to the array, use <code>unserialize</code>:</p>
<pre><code>// $array will contain ( 1, 2, 3 )
$array = unserialize( $string );</code></pre>
<p>Now let&#8217;s try serializing an array of 200 randomly generated integers from 1 to 1000:</p>
<pre>$array = array();
for( $i = 0; $i < 200; $i++ )
	$array[] = mt_rand( 1, 1000 );

$string = serialize( $array );
echo $string;</pre>
<p>This outputs something like:
</pre>
<pre>a:200:{i:0;i:465;i:1;i:202;i:2;i:9;i:3;i:448;i:4;i:887;i:5;i:844;i:6;i:230;i:7;i:785;i:8;i:892;i:9;i:949;i:10;i:864;i:11;i:29;i:12;i:239;i:13;i:521;i:14;i:632;i:15;i:115;i:16;i:903;i:17;i:331;i:18;i:732;i:19;i:192;i:20;i:487;i:21;i:297;i:22;i:1000;i:23;i:674;i:24;i:301;i:25;i:208;i:26;i:819;i:27;i:690;i:28;i:906;i:29;i:544;i:30;i:316;i:31;i:932;i:32;i:458;i:33;i:64;i:34;i:268;i:35;i:590;i:36;i:80;i:37;i:375;i:38;i:837;i:39;i:928;i:40;i:209;i:41;i:880;i:42;i:60;i:43;i:98;i:44;i:395;i:45;i:880;i:46;i:336;i:47;i:183;i:48;i:321;i:49;i:167;i:50;i:917;i:51;i:423;i:52;i:882;i:53;i:768;i:54;i:415;i:55;i:728;i:56;i:431;i:57;i:540;i:58;i:72;i:59;i:338;i:60;i:431;i:61;i:669;i:62;i:234;i:63;i:699;i:64;i:983;i:65;i:602;i:66;i:348;i:67;i:995;i:68;i:772;i:69;i:337;i:70;i:113;i:71;i:644;i:72;i:209;i:73;i:587;i:74;i:822;i:75;i:135;i:76;i:269;i:77;i:111;i:78;i:406;i:79;i:364;i:80;i:613;i:81;i:522;i:82;i:621;i:83;i:789;i:84;i:195;i:85;i:15;i:86;i:674;i:87;i:916;i:88;i:186;i:89;i:70;i:90;i:59;i:91;i:911;i:92;i:242;i:93;i:270;i:94;i:903;i:95;i:553;i:96;i:166;i:97;i:201;i:98;i:250;i:99;i:683;i:100;i:801;i:101;i:691;i:102;i:602;i:103;i:862;i:104;i:357;i:105;i:872;i:106;i:105;i:107;i:86;i:108;i:496;i:109;i:208;i:110;i:349;i:111;i:69;i:112;i:938;i:113;i:500;i:114;i:961;i:115;i:437;i:116;i:446;i:117;i:16;i:118;i:782;i:119;i:268;i:120;i:296;i:121;i:341;i:122;i:343;i:123;i:160;i:124;i:247;i:125;i:610;i:126;i:600;i:127;i:962;i:128;i:224;i:129;i:659;i:130;i:951;i:131;i:124;i:132;i:937;i:133;i:819;i:134;i:684;i:135;i:930;i:136;i:104;i:137;i:493;i:138;i:568;i:139;i:290;i:140;i:333;i:141;i:626;i:142;i:160;i:143;i:80;i:144;i:278;i:145;i:840;i:146;i:942;i:147;i:141;i:148;i:28;i:149;i:69;i:150;i:241;i:151;i:724;i:152;i:386;i:153;i:209;i:154;i:933;i:155;i:281;i:156;i:410;i:157;i:397;i:158;i:360;i:159;i:337;i:160;i:29;i:161;i:321;i:162;i:543;i:163;i:642;i:164;i:943;i:165;i:273;i:166;i:505;i:167;i:856;i:168;i:860;i:169;i:67;i:170;i:879;i:171;i:735;i:172;i:964;i:173;i:858;i:174;i:965;i:175;i:984;i:176;i:821;i:177;i:540;i:178;i:857;i:179;i:363;i:180;i:588;i:181;i:707;i:182;i:588;i:183;i:540;i:184;i:380;i:185;i:35;i:186;i:52;i:187;i:926;i:188;i:686;i:189;i:833;i:190;i:941;i:191;i:385;i:192;i:730;i:193;i:743;i:194;i:815;i:195;i:497;i:196;i:567;i:197;i:811;i:198;i:339;i:199;i:144;}</pre>
<p>These strings can easily be stored in a database and unserialized when the data is accessed. Often times, <code>base64_encode</code> is used in conjunction with <code>serialize</code> when storing arrays:</p>
<pre><code>$string = base64_encode( serialize( $array ) );</code></pre>
<p>The encrypted string can then be restored to an array by using <code>base64_decode</code>:</p>
<pre><code>$array = unserialize( base64_decode( $string ) );</code></pre>
<p>Unfortunately, these strings can grow to be quite large. To counter the size, you may want to use <code>gzcompress</code> to apply gzip compression and significantly reduce the size:</p>
<pre><code>$smallString = gzcompress( $string );</code></pre>
<p>Note that gzip compression can be undone with <code>gzuncompress</code>.</p>
<p>That&#8217;s really all there is to it. Now you can easily store an array of information in a database!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lateralcode.com/store-array-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Prevent Form Attacks with Basic Math Security</title>
		<link>http://www.lateralcode.com/basic-math-security/</link>
		<comments>http://www.lateralcode.com/basic-math-security/#comments</comments>
		<pubDate>Mon, 14 Jun 2010 23:43:33 +0000</pubDate>
		<dc:creator>Karthik Viswanathan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.lateralcode.com/?p=1470</guid>
		<description><![CDATA[Form security is a top priority these days due to the risks of losing sensitive information, getting spammed by bots, being exposed to viruses, and more. As a result, it is important to take steps to secure your forms in order to counter these risks. In this article, we&#8217;re going to create a PHP class [...]]]></description>
			<content:encoded><![CDATA[<p>Form security is a top priority these days due to the risks of losing sensitive information, getting spammed by bots, being exposed to viruses, and more. As a result, it is important to take steps to secure your forms in order to counter these risks.</p>
<p><img src="http://www.lateralcode.com/wp-content/uploads2/basic-math-security/1.jpg" alt="Security" class="list-post-img"/></p>
<p>In this article, we&#8217;re going to create a PHP class to help secure forms with basic math questions. This class will generate two random numbers that must be added by the user in order to ensure a human is submitting the form. Taken as a whole, this class only takes about 10 minutes to write. This begs the question: are you willing to secure your forms for a few minutes of work?</p>
<p><a href="http://demo.lateralcode.com/basic-math-security/" class="view">View a Demo</a> <a href="http://www.lateralcode.com/wp-content/uploads2/basic-math-security/basic-math-security.zip" class="dl">Download the Files</a></p>
<p><span id="more-1470"></span></p>
<p>This PHP class, which will be called BasicMathSecurity, will have three main functions:</p>
<ul>
<li><code>generateNumbers</code> &#8211; generates two random numbers from 1-9 that the user must add</li>
<li><code>getField</code> &#8211; returns the label and input tags that will be displayed</li>
<li><code>isCorrect</code> &#8211; checks whether the user input is correct</li>
</ul>
<p>Before we begin with these functions, let&#8217;s write a simple constructor:</p>
<pre><code>public function BasicMathSecurity( $name = 'math' )
{
	$this->name = $name;
	$this->generateNumbers();
}</code></pre>
<p><code>$name</code> will be the name of the user input field. Note that generate numbers is called during instantiation to eliminate the need for an extra call.</p>
<p><code>generateNumbers</code> is trivial through the use of PHP&#8217;s <a href="http://www.php.net/manual/en/function.mt-rand.php"><code>mt_rand</code></a> function:</p>
<pre><code>public function generateNumbers()
{
	$this->operand1 = mt_rand( 1, 9 );
	$this->operand2 = mt_rand( 1, 9 );
}</code></pre>
<p><code>getField</code> will create three HTML tags:</p>
<ul>
<li>A label for the math field with the question (ex. &#8220;1 + 1 =&#8221;)</li>
<li>The math field, which is a text input</li>
<li>A hidden input field for the answer to the math question</li>
</ul>
<p>Using the <code>$name</code> paramater asked for in the constructor, the following function can be produced:</p>
<pre><code>public function getField()
{
	$label = '&lt;label for=&quot;' . $this-&gt;name . '&quot;&gt;' . $this-&gt;operand1 . ' + ' . $this-&gt;operand2 . ' = &lt;/label&gt;';
	$math = '&lt;input type=&quot;text&quot; name=&quot;' . $this-&gt;name . '&quot; value=&quot;&quot; id=&quot;' . $this-&gt;name . '&quot;&gt;&lt;/input&gt;';

	$answer = '&lt;input type=&quot;hidden&quot; name=&quot;' . $this-&gt;name . '-answer&quot; value=&quot;' . ( $this-&gt;operand1 + $this-&gt;operand2 ) . '&quot;&gt;&lt;/input&gt;';
	$string = $label . &quot;\n&quot; . $math . &quot;\n&quot; . $answer;

	return $string;
}</code></pre>
<p>An id is added to the math field for styling purposes. In addition, note that the answer field uses the same name as the math field with a &#8220;-answer&#8221; appended to it. This is important for the next function.</p>
<p>Finally, the <code>isCorrect</code> function will use the global <code>$_REQUEST</code> array to check whether the user input matches the answer:</p>
<pre><code>public function isCorrect()
{
	$answer = $this->name . '-answer';
	if( !isset( $_REQUEST[ $this->name ] ) || !isset( $_REQUEST[ $answer ] ) )
		return false;

	return (int) $_REQUEST[ $this->name ] == (int) $_REQUEST[ $answer ];
}</code></pre>
<p>The <code>$answer</code> index is based off the code in the <code>getField</code> function.</p>
<p>As a whole, the class is as follows:</p>
<pre><code>class BasicMathSecurity {

	private $name;
	private $operand1, $operand2;

	public function BasicMathSecurity( $name = 'math' )
	{
		$this->name = $name;
		$this->generateNumbers();
	}

	public function generateNumbers()
	{
		$this->operand1 = mt_rand( 1, 9 );
		$this->operand2 = mt_rand( 1, 9 );
	}

	public function getField()
	{
		$label = '&lt;label for=&quot;' . $this-&gt;name . '&quot;&gt;' . $this-&gt;operand1 . ' + ' . $this-&gt;operand2 . ' = &lt;/label&gt;';
		$math = '&lt;input type=&quot;text&quot; name=&quot;' . $this-&gt;name . '&quot; value=&quot;&quot; id=&quot;' . $this-&gt;name . '&quot;&gt;&lt;/input&gt;';

		$answer = '&lt;input type=&quot;hidden&quot; name=&quot;' . $this-&gt;name . '-answer&quot; value=&quot;' . ( $this-&gt;operand1 + $this-&gt;operand2 ) . '&quot;&gt;&lt;/input&gt;';
		$string = $label . &quot;\n&quot; . $math . &quot;\n&quot; . $answer;

		return $string;
	}

	public function isCorrect()
	{
		$answer = $this->name . '-answer';
		if( !isset( $_REQUEST[ $this->name ] ) || !isset( $_REQUEST[ $answer ] ) )
			return false;

		return (int) $_REQUEST[ $this->name ] == (int) $_REQUEST[ $answer ];
	}

}</code></pre>
<p>To use it, construct a BasicMathSecurity object and display the field:</p>
<pre><code>$math = new BasicMathSecurity( 'math' );
echo $math->getField();</code></pre>
<p>Subsequently, in your form handler, check if the input is correct. Remember to construct the object with the same name parameter:</p>
<pre><code>// construct the object with the same parameter
$math = new BasicMathSecurity( 'math' );
if( $math->isCorrect() ) {
	// process the form
}</code></pre>
<p>And that&#8217;s it! You may <a href="http://demo.lateralcode.com/basic-math-security/">view the demo</a> and <a href="http://www.lateralcode.com/wp-content/uploads2/basic-math-security/basic-math-security.zip">download the files used to create it</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lateralcode.com/basic-math-security/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>3 Easy Steps to Create Excel Spreadsheets in PHP</title>
		<link>http://www.lateralcode.com/excel-spreadsheets-php/</link>
		<comments>http://www.lateralcode.com/excel-spreadsheets-php/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 03:42:04 +0000</pubDate>
		<dc:creator>Karthik Viswanathan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.lateralcode.com/?p=1439</guid>
		<description><![CDATA[Spreadsheets are simple files that help you manage and organize data. They are used everywhere and have become quite popular. You can find them by using Microsoft Excel, Open Office, or even an online alternative such as Google Docs. Generating Spreadsheets Since computers and automation have become second nature, spreadsheet generation isn&#8217;t out of the [...]]]></description>
			<content:encoded><![CDATA[<p>Spreadsheets are simple files that help you manage and organize data. They are used everywhere and have become quite popular. You can find them by using Microsoft Excel, Open Office, or even an online alternative such as Google Docs.</p>
<p><img src="http://www.lateralcode.com/wp-content/uploads2/excel-spreadsheets-php/1.jpg" alt="Spreadsheet" class="list-post-img"/></p>
<h2>Generating Spreadsheets</h2>
<p>Since computers and automation have become second nature, spreadsheet generation isn&#8217;t out of the ordinary. With MySQL databases, it becomes even more imperative, as spreadsheets are perfect to represent the data located in these structures.</p>
<p>Upon searching for how to create excel spreadsheets using PHP, most of the results came back with libraries that do the job. This seemed to be too much of a hassle. That&#8217;s why I&#8217;ve created <strong>3 easy steps to create excel spreadsheets</strong> without any libraries.</p>
<p><a href="http://www.lateralcode.com/wp-content/uploads2/excel-spreadsheets-php/excel-spreadsheets-php.zip" class="dl">Download the Files</a></p>
<p><span id="more-1439"></span></p>
<h2>Step 1: The Content-Type</h2>
<p>The first thing you have to do is add an <code>application/vnd.ms-excel</code> content-type to your PHP file:</p>
<pre>header("Content-Type: application/vnd.ms-excel");</pre>
<p>Easy enough? Let&#8217;s move on to the actual data.</p>
<h2>Step 2: Adding the Data</h2>
<p>Data is just as simple. Separate cells/columns with tabs (&#8220;\t&#8221; in PHP) and move to the next row with a newline (&#8220;\n&#8221; in PHP).</p>
<p>Here are a few PHP echo statements that will do the trick:</p>
<pre>echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";</pre>
<p>I&#8217;ve separated the tabs (\t) and the new lines (\n) so you can easily see the structure. The above would create a spreadsheet that looks like this:</p>
<pre>First Name     Last Name     Phone
John           Doe           555-5555</pre>
<h2>Step 3: Downloading the Spreadsheet</h2>
<p>Now that you&#8217;ve set the content-type and created the data, just open up the PHP file in a browser. You&#8217;ll be asked to download the spreadsheet. If you would like to give a name to the spreadsheet, just add the following:</p>
<pre>header("Content-disposition: attachment; filename=spreadsheet.xls");</pre>
<p>All you need to do is change <code>spreadsheet.xls</code> to the name of your spreadsheet. Note that the above header also ensures that Internet Explorer will ask you to download the file rather than trying to display it.</p>
<h2>Conclusion</h2>
<p>That&#8217;s really all there is to create a spreadsheet. For those of you who are using Microsoft Excel 2007, you might see the following message when opening the spreadsheet:</p>
<blockquote><p>The file you are trying to open, &#8216;filename.xls&#8217;, is in a different format than specified by the file extension&#8230; [message condensed]</p></blockquote>
<p>If so, just hit the &#8220;Yes&#8221; button and you&#8217;re good to go!</p>
<h3>Comments? Questions? Concerns?</h3>
<p>It&#8217;s your time now. If you have any comments, questions, or concerns, please post them below!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lateralcode.com/excel-spreadsheets-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Force Download Dialog Boxes</title>
		<link>http://www.lateralcode.com/force-download-box/</link>
		<comments>http://www.lateralcode.com/force-download-box/#comments</comments>
		<pubDate>Thu, 04 Feb 2010 13:00:12 +0000</pubDate>
		<dc:creator>Patrick Lin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[htaccess]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.lateralcode.com/?p=1434</guid>
		<description><![CDATA[When we browse the web, we click on links. That&#8217;s what makes the web a web &#8211; the links between pages. Sometimes, those links lead us not to pages, but to files. Many types of files pop up dialog boxes prompting downloads &#8211; executables, videos, etc. However, certain filetypes, thanks to modern web browsers, are [...]]]></description>
			<content:encoded><![CDATA[<p>When we browse the web, we click on links. That&#8217;s what makes the web a web &#8211; the links between pages. Sometimes, those links lead us not to pages, but to files. Many types of files pop up dialog boxes prompting downloads &#8211; executables, videos, etc.</p>
<p>However, certain filetypes, thanks to modern web browsers, are rendered as an in-browser page, such as images, PDFs, and MP3s. While this may be a convenience, at times we may wish to force the user to download the files, not just view them in their browser.</p>
<p>In this article I will show two easy ways to do this. The first is using .htaccess, and the second is using PHP.</p>
<p><span id="more-1434"></span></p>
<h2>.htaccess</h2>
<p>In your .htaccess file, add the following line for each extension you wish to force download:</p>
<pre><code>AddType application/octet-stream <i>extension</i>
</code></pre>
<p>For example, if I wanted to force PDFs and MP3s to download, I would do this:</p>
<pre><code>AddType application/octet-stream .pdf
AddType application/octet-stream .mp3
</code></pre>
<p>It&#8217;s really quite simple, and can be done quickly.</p>
<h2>PHP</h2>
<p>The PHP version is a bit more complicated, but can be useful if you want to have a bit more control. For example, you can use download IDs instead of the filename to prevent direct hotlinking. For example, you can assign the ID &#8220;3148&#8243; to &#8220;BusinessPlan.pdf&#8221; and do a forced download.</p>
<p>The basic code looks like this:</p>
<pre><code>&lt;?php
header('Content-Disposition:inline;filename="'.$file.'"');
header('Content-Transfer-Encoding:Binary');
header('Content-length:'.filesize($file));
header('Content-Type:application/octet-stream');
header('Content-Disposition: attachment; filename="'.$file.'"');
readfile("$file");
?&gt;
</code></pre>
<p>Of course, this is a huge security hole if you use the structure <code>download.php?file=BusinessPlan.pdf</code>, as anyone can access any file on your webserver. Thus, steps should be taken to secure the user input, or use a database of IDs.</p>
<p>Of course, if you&#8217;re just forcing download and don&#8217;t need extra control over the download process, you should use the .htaccess version, as it is much simpler and easier to use.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lateralcode.com/force-download-box/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Intelligent Caching of the CSS Minifier</title>
		<link>http://www.lateralcode.com/caching-css-minifier/</link>
		<comments>http://www.lateralcode.com/caching-css-minifier/#comments</comments>
		<pubDate>Mon, 18 Jan 2010 23:44:09 +0000</pubDate>
		<dc:creator>Karthik Viswanathan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.lateralcode.com/?p=1410</guid>
		<description><![CDATA[A few months back, I presented a stunningly simple CSS minifier that enables you to pack your CSS while still maintaining format and readability. Soon after that, I presented a system called Lateral Cache that you could use to store the minified CSS and deliver it quickly. Although the Lateral Cache system works well and [...]]]></description>
			<content:encoded><![CDATA[<p>A few months back, I presented a <a href="http://www.lateralcode.com/css-minifer/">stunningly simple CSS minifier</a> that enables you to pack your CSS while still maintaining format and readability. Soon after that, I presented a system called <a href="http://www.lateralcode.com/lateral-cache/">Lateral Cache</a> that you could use to store the minified CSS and deliver it quickly.</p>
<p><img src="http://www.lateralcode.com/wp-content/uploads2/caching-css-minifier/1.jpg" alt="CSS" class="list-post-img"/></p>
<p>Although the Lateral Cache system works well and is great for general purposes, the CSS minifier can be aided by a more <strong>intelligent caching system</strong>. Well, what do I mean by that? That&#8217;s what you are going to find out.</p>
<p><a href="http://www.lateralcode.com/wp-content/themes/SimplyWhite/lateral-cache/css-styles.php" class="view">View a Demo</a> <a href="http://www.lateralcode.com/wp-content/uploads2/caching-css-minifier/caching-css-minifier.zip" class="dl">Download the Files</a></p>
<p>Please note that the demo link above directs you to Lateral Code&#8217;s own CSS file, where intelligent caching is used.</p>
<p><span id="more-1410"></span></p>
<h2>Re-caching for no reason? Say whaaat&#8230;?</h2>
<p>Any general caching system normally allows you to provide a time interval to cache. This interval is used in a simple manner:</p>
<ol>
<li>Store an initial cache of the data in a file.</li>
<li>Check if the time of the last cache is greater than the specified time interval.</li>
<li>If so, re-cache a new set of updated data and deliver it.</li>
<li>Otherwise, deliver the data in the cache</li>
<li>Repeat steps 2 &#8211; 4 indefinitely.</li>
</ol>
<p>This system is a basic standard and has been used with much success. By re-caching at a specified interval, data will eventually be updated and the user won&#8217;t have to wait excessively after each request to the website. Essentially, if this system is used, a website will not have to check for new data at each user request; rather, it will check only after the specified time interval.</p>
<p>Note that the above works very well for data that is updated at a specific time interval. For example, if new data arrives every 30 minutes, a cache is ideal because it can be configured to update only when new information is available.</p>
<p>Returning back to the CSS minifier, it&#8217;s important to realize that the need for re-minifying only occurs when the original CSS file has been modified. Only under this circumstance will the cache have to be updated. In essence, keeping a cache with a specified interval such as one day will produce excessive re-caching that is not useful. On the flip side, if you were to use a very large cache interval, such as 30 days, updating the CSS file would be a pain, as you would have two main choices:</p>
<ul>
<li>Wait 30 days until the cache refreshes</li>
<li>Change the code to temporarily stop caching</li>
</ul>
<p>The first option is much worse than the second, but both are still a pain.</p>
<h2>How can you check if a file is modified?</h2>
<p>Now there&#8217;s the golden question you were all waiting for. If you know that the cache should only be updated when the original CSS file is modified, how would you adapt the code to meet this criterion? Luckily, the answer is simple due to magic <a href="http://php.net/manual/en/function.filemtime.php"><code>filemtime</code></a> PHP function, which can tell you the last time the file was modified.</p>
<p>The algorithm to accomplish the task now becomes quite trivial:</p>
<ol>
<li>When caching, store both the last modified time and the minified CSS. This can be done by using two files or just one.</li>
<li>When checking what to deliver to the user, compare the stored time to the last modified time. If they are the same, return what is in the cache. Otherwise, re-cache and re-minify the CSS. Consequently, deliver the new data to the user.</li>
</ol>
<h2>Writing code using the algorithm</h2>
<p>From the algorithm comes the following code:</p>
<pre><code>header( "Content-type: text/css" );

// config --->
$dataFile = 'cache/styles'; // Make sure a cache directory exists
$timeFile = 'cache/styles-time';
$origFile = '/path/to/css/file'; // Change this
// < --- end config

$lastTime = -1;
if( file_exists( $timeFile ) )
	$lastTime = (int) file_get_contents( $timeFile );

$cache = false;
if( file_exists( $dataFile ) &#038;&#038; file_exists( $origFile ) &#038;&#038; $lastTime == filemtime( $origFile ) ) {
	$css = file_get_contents( $dataFile );
	$cache = true;
}
else {
	$css = file_get_contents( $origFile );
	$css = minify( $css );

	file_put_contents( $dataFile, $css );
	file_put_contents( $timeFile, filemtime( $origFile ) );
}

echo $css;</code></code></pre>
<p>Remember to change <code>$origFile</code> to point to your CSS file and also ensure that a <code>cache/</code> directory exists (you may change the name/placement of this directory by editing the <code>$dataFile</code> and <code>$timeFile</code> variables).</p>
<p>Note that the minify function used in the above code is present in the <a href="http://www.lateralcode.com/css-minifer/">original article</a>.</p>
<p>As a quick overview:</p>
<ol>
<li>The configuration options set the location of the original CSS file. They also point to the data files for storing minified CSS and the last modified time.</li>
<li>The time file is loaded into a variable and compared with the <code>filemtime</code> of the original CSS file.</li>
<li>If the two differ, minification is applied and the data is re-cached. It is then delivered.</li>
<li>Otherwise, the cached file with minifed CSS is delivered.</li>
</ol>
<h2>Conclusion</h2>
<p>So, with some simple analysis and one useful PHP function, caching can become much more intelligent for the CSS minifier.</p>
<p>Do you have any thoughts about the minifier? Do you know some way to make it better? It&#8217;s now your time to talk, so feel free to do so in a comment below!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lateralcode.com/caching-css-minifier/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Power of Options: Simple, yet Effective</title>
		<link>http://www.lateralcode.com/power-of-options/</link>
		<comments>http://www.lateralcode.com/power-of-options/#comments</comments>
		<pubDate>Sat, 16 Jan 2010 18:57:17 +0000</pubDate>
		<dc:creator>Karthik Viswanathan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.lateralcode.com/?p=1403</guid>
		<description><![CDATA[Options are extremely powerful when it comes to building a website. They provide strong flexibility and facilitate many changes. Furthermore, they are largely present in many CMS systems and blogging platforms, such as WordPress. WordPress Options For those of you who aren&#8217;t familiar with WordPress&#8217; options system, it acts in a simple way: // an [...]]]></description>
			<content:encoded><![CDATA[<p>Options are extremely powerful when it comes to building a website. They provide strong flexibility and facilitate many changes. Furthermore, they are largely present in many CMS systems and blogging platforms, such as WordPress.</p>
<p><img src="http://www.lateralcode.com/wp-content/uploads2/power-of-options/1.jpg" alt="Options" class="list-post-img"/></p>
<h2>WordPress Options</h2>
<p>For those of you who aren&#8217;t familiar with WordPress&#8217; options system, it acts in a simple way:</p>
<pre><code>// an option is stored with the specified $name and $value
add_option( $name, $value );

// an option is retrieved using the $name
get_option( $name );

// updates an option with $name, or creates a new one if it doesn't exist
// this is generally used more than add_option due to its flexibility
update_option( $name, $value );</code></pre>
<p>The ability of these functions stems from their storage of data. Even through multiple requests, the data that is passed as options will stay in-tact. This is because options are stored in a database.</p>
<p><span id="more-1403"></span></p>
<h2>Your Own Options</h2>
<p>Today&#8217;s article will focus on how to implement an options system very similar to WordPress through PHP and MySQL. We will be going through:</p>
<ul>
<li><a href="#create">Creating the Table</a></li>
<li><a href="#connect">Connecting to the Database</a></li>
<li><a href="#clean"><code>clean</code> Function</a></li>
<li><a href="#hasOption"><code>hasOption</code> Function</a></li>
<li><a href="#addOption"><code>addOption</code> Function</a></li>
<li><a href="#updateOption"><code>updateOption</code> Function</a></li>
<li><a href="#getOption"><code>getOption</code> Function</a></li>
<li><a href="#delOption"><code>delOption</code> Function</a></li>
<li><a href="#wrap">Wrapping Up</a></li>
</ul>
<p>You may download the source code if you wish:</p>
<p><a href="http://www.lateralcode.com/wp-content/uploads2/power-of-options/power-of-options.zip" class="dl">Download the Files</a></p>
<h2 id="create">Creating the Table</h2>
<p>To begin, you will have to create a table called &#8216;options&#8217; in your MySQL database with the following fields:</p>
<pre><code>id - unsigned int(10), NOT NULL, auto_increment, primary key
name - varchar(255), NOT NULL
value - longtext, NOT NULL</code></pre>
<p>If you just want to run a MySQL command to produce the database, use this:</p>
<pre><code>CREATE TABLE `options` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `value` longtext NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4;</code></pre>
<h2 id="connect">Connecting to the Database</h2>
<p>To connect to your database, you will need a server, username, and password. On my local server, I use the following:</p>
<pre><code>function connect() {
	mysql_connect( 'localhost:8888', 'root', 'root' );
	mysql_select_db( 'custom' );
}</code></pre>
<p>Note that you will have to change the three parameters of <code>mysql_connect( $server, $username, $password )</code> to suit your own database. In addition, pass in the name of your database to <code>mysql_select_db</code> (custom is the name of the database I am using).</p>
<h2 id="clean"><code>clean</code> Function</h2>
<p><img src="http://www.lateralcode.com/wp-content/uploads2/power-of-options/2.jpg" alt="Cleaning" class="list-post-img"/></p>
<p>Before you start running MySQL queries, it&#8217;s always necessary to have a function that makes the input safe. Consider the following:</p>
<pre><code>function clean( $input ) {
	if( get_magic_quotes_gpc() )
		$input = stripslashes( $input );

	return mysql_real_escape_string( $input );
}</code></pre>
<p>This function first removes any unnecessary slashes if they exist and then cleans the input through <a href="http://php.net/manual/en/function.mysql-real-escape-string.php"><code>mysql_real_escape_string</code></a>.</p>
<h2 id="hasOption"><code>hasOption</code> Function</h2>
<p>Before you start writing the majority of PHP, it&#8217;s nice to have a helper function. In this case, you can create a <code>hasOption</code> function that will check if an option with a given name exists:</p>
<pre><code>function hasOption( $name ) {
	$query = sprintf( "SELECT id FROM options WHERE name = '%s'", clean( $name ) );
	$result = mysql_query( $query );

	if( !$result )
		return false;
	return (bool) mysql_fetch_assoc( $result );
}</code></pre>
<p><code>$query</code> holds the MySQL query, which tries to select an id from the database that corresponds with the option name. <a href="http://php.net/manual/en/function.mysql-query.php"><code>mysql_query</code></a> is then used to run this query. Subsequently, the result is obtained and a boolean is returned that determines whether a row in the database corresponds with the parameter <code>$name</code>.</p>
<h2 id="addOption"><code>addOption</code> Function</h2>
<p>The <code>addOption</code> function will be used to store an option which can be retrieved at a later time. To implement this, you can use the <code>hasOption</code> function which you just created:</p>
<pre><code>function addOption( $name, $value ) {
	if( hasOption( $name ) )
		return false;

	$query = sprintf( "INSERT INTO options( name, value ) VALUES( '%s', '%s' )", clean( $name ), clean( serialize( $value ) ) );
	$result = mysql_query( $query );

	return (bool) $result;
}</code></pre>
<p>This function will try to add an option to the database and return true or false depending on its success. Note that this function is able to store data of <strong>any type</strong>. This is because it uses the PHP function <a href="http://php.net/manual/en/function.serialize.php"><code>serialize</code></a> to generate a string representation of any value.</p>
<p>From the code perspective, it does the following:</p>
<ol>
<li>If the option already exists, it returns false, as it only adds options (does not update them).</li>
<li>It then produces a MySQL query to insert a new option.</li>
<li>Using <code>mysql_query</code>, the query is run and, if successful, true is returned. Otherwise, the function returns false.</li>
</ol>
<h2 id="updateOption"><code>updateOption</code> Function</h2>
<p><code>updateOption</code> is very similar to <code>addOption</code>, but with a few changes:</p>
<pre><code>function updateOption( $name, $value ) {
	if( !hasOption( $name ) )
		return addOption( $name, $value );

	$query = sprintf( "UPDATE options SET value = '%s' WHERE name = '%s'", clean( serialize( $value ) ), clean( $name ) );
	$result = mysql_query( $query );

	return (bool) $result;
}</code></pre>
<p>If the option does not already exist, <code>updateOption</code> will create it by calling <code>addOption</code>. Otherwise, it will run a MySQL update command to change the value inside the database. It then returns whether it was successful or not.</p>
<h2 id="getOption"><code>getOption</code> Function</h2>
<p>The <code>getOption</code> function is almost the exact same as <code>addOption</code>, except that it will retrieve the value of the option and then <a href="http://php.net/manual/en/function.unserialize.php"><code>unserialize</code></a> it.</p>
<pre><code>function getOption( $name ) {
	if( !hasOption( $name ) )
		return false;

	$query = sprintf( "SELECT value FROM options WHERE name = '%s'", clean( $name ) );
	$result = mysql_query( $query );

	if( $result &#038;&#038; ( $row = mysql_fetch_assoc( $result ) ) )
		return unserialize( $row[ 'value' ] );
	return false;
}</code></pre>
<p>If the option does not exist, this function returns false. It then creates a select query and executes it. When returning the value, note that <code>getOption</code><code> uses </code><code>unserialize</code> to undo the storage that was used by <code>addOption</code>.</p>
<h2 id="delOption"><code>delOption</code> Function</h2>
<p><code>delOption</code> is used to delete an option. It runs a MySQL delete command to accomplish its job:</p>
<pre><code>function delOption( $name ) {
	if( !hasOption( $name ) )
		return false;

	$query = sprintf( "DELETE FROM options WHERE name = '%s'", $name );
	$result = mysql_query( $query );

	return (bool) $result;
}</code></pre>
<p>Note how this function returns false if the option doesn&#8217;t exist. Otherwise, it&#8217;ll run the delete command and then return true or false depending on its success.</p>
<h2 id="wrap">Wrapping Up</h2>
<p><img src="http://www.lateralcode.com/wp-content/uploads2/power-of-options/3.jpg" alt="Wrap Up" class="list-post-img"/></p>
<p>With a MySQL table and a few functions, you have produced a working options system. You may now use the functions like so:</p>
<pre><code>// connect to the database
connect();

// add an option that corresponds $name to $value
addOption( $name, $value );

// get an option with a specified name
getOption( $name );

// update an option to correspond $name to $value
updateOption( $name, $value );

// delete an option with a given $name
delOption( $name );

// check whether an option with a given $name exists
hasOption( $name );</code></pre>
<p>Questions? Comments? Please post them below and tell us what you think!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lateralcode.com/power-of-options/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

