<?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>dawnerd &#187; PHP</title>
	<atom:link href="http://dawnerd.com/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://dawnerd.com</link>
	<description>Just another WordPress site</description>
	<lastBuildDate>Fri, 13 Aug 2010 18:20:31 +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>Starting PHP: Looping Basics</title>
		<link>http://dawnerd.com/post/33_starting-php-looping-basics/</link>
		<comments>http://dawnerd.com/post/33_starting-php-looping-basics/#comments</comments>
		<pubDate>Fri, 15 Aug 2008 03:06:41 +0000</pubDate>
		<dc:creator>Troy Whiteley</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[basics]]></category>
		<category><![CDATA[loops]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://dawnerd.com/?p=33</guid>
		<description><![CDATA[I was searching the internet for PHP tutorials and quickly found out that the majority of are badly written, have errors in the example code, contain security holes, or are just outright outdated. This makes learning PHP hard for someone &#8230; <a href="http://dawnerd.com/post/33_starting-php-looping-basics/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I was searching the internet for PHP tutorials and quickly found out that the majority of are badly written, have errors in the example code, contain security holes, or are just outright outdated. This makes learning PHP hard for someone just starting out. The question I get a lot is about looping through arrays. <span id="more-33"></span></p>
<p>The following are the three possible ways to loop through data, with an example showing how I use them.</p>
<p><strong>The While Loop</strong><br />
The while loop is useful when running loop on data with an unknown size; a database result for example. here&#8217;s an example:</p>
<pre>
<code>
<?php
$sql = "SELECT `userid` FROM `users`";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query))
{
     echo $row['userid'].'<br/>';
}
?>
</code>
</pre>
<p>The above example will continue to check $row to see if it returns false. Each call to <code>mysql_fetch_array()</code> will increment the key. If you ran <code>mysql_fetch_array()</code> outside of the loop, you would get a full array of all the results at once. For example:</p>
<pre>
<code>
Array(
     0 => Array( 'userid' => 1),
     1 => Array( 'userid' => 2)
)
</code>
</pre>
<p>In this case, you could simply call <code>$row[0]['userid']</code>. But again you don&#8217;t know how many results there are so hand coding all the different keys would be just silly.</p>
<p><strong>The For Loop</strong><br />
Just like a while loop, a for loop runs until the expression returns false. Example:</p>
<pre>
<code>
<?php
$array = array('copper','gold','silver');
for($i=0;$i<count($array);$i++)
{
     echo $array[$i].'<br/>';
}
?>
</code>
</pre>
<p>For loops are probably the hardest types of loops for php beginners to grasp. The reason behind that is because of the expression used to keep the loop running. So what does <code>$i=0;$i<count($array);$i++</code> mean? When the loop is first started, the variable <code>$i</code> is set to 0, which happens to be the first key in the <code>$array</code> variable. Next, it checks if the <code>$i</code> variable is less than the total number of items in the array. If the count is greater than <code>$i</code>, the loop continues. Lastly, <code>$i</code> is incremented after one each loop. So after the first run, <code>$i</code> becomes 1, rather than 0.</p>
<p>We have 3 items in the array, so in english, that loop would look like:</p>
<pre>
<code>
i is zero.
if i less than three continue, otherwise break the loop.
add one to i.
</code>
</pre>
<p>The <code>$i</code> variable is accessible anywhere in the loop. It may seem that <code>$i</code> is incremented before any code in the loop is processed, but in reality, it is incremented after the code has been executed.</p>
<p>For loops are also extremely fast for small sets of data. Just keep that in mind if all you have to do are small loops and getting the length of an array or number is no issue.</p>
<p><strong>The Foreach Loop</strong><br />
This last method of looping is my favorite; mostly because it's easy to follow. Take for example:</p>
<pre>
<code>
<?php
$array = array('bob','joe','billy','rob');
foreach($array as $key => $value)
{
     echo $key.': '.$value.'<br/>';
}
?>
</code>
</pre>
<p>This will output:</p>
<pre>
<code>
0: bob
1: joe
2: billy
3: rob
</code>
</pre>
<p>The foreach loop takes each item in the array starting from the left and assigns it a key, or unique number; starting from 0. This is always the case. However, you can choose not to get the key of the current array item by not using the $key part of the foreach loop. Instead, the loop would look like:</p>
<pre>
<code>
$array = array('bob','joe','billy','rob');
foreach($array as $value)
{
     echo $value.'<br/>';
}
</code>
</pre>
<p>Now that you read this, the only way to make it stick is to put it to practice. If you need help trying to make something, here's a script you should try to make on your own:</p>
<pre>
<code>
Make an array of your favorite movies.
Each movie should contain the top 5 or more actors.
Make the script loop through and output each movie and the first three
actors, omitting any others.
</code>
</pre>
<p>If you need a little kickstart here you go:</p>
<pre>
<code>
<?php
$movies = array(
                    array('The Matrix',
                         array('Keanu Reeves',
                              'Laurence Fishburne',
                              'Carrie-Anne Moss',
                              'Hugo Weaving
                          )
                     )
);
</code>
</pre>
<p>Yes, you will need to nest the loops. I'm sure you can figure it out. Once you get this, I have a good feeling everything else will be a breeze.</p>
]]></content:encoded>
			<wfw:commentRss>http://dawnerd.com/post/33_starting-php-looping-basics/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Open Source PHP Data Validation Class</title>
		<link>http://dawnerd.com/post/26_open-source-php-data-validation-class/</link>
		<comments>http://dawnerd.com/post/26_open-source-php-data-validation-class/#comments</comments>
		<pubDate>Fri, 08 Aug 2008 01:32:55 +0000</pubDate>
		<dc:creator>Troy Whiteley</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[data validation]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://dawnerd.com/?p=26</guid>
		<description><![CDATA[I have created a PHP5 class that handles all POST and GET variables. It performs almost all of the validations functions you could need. In addition, it makes accessing the variables very convenient. Download here. Version 1.0 How To use: &#8230; <a href="http://dawnerd.com/post/26_open-source-php-data-validation-class/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have created a PHP5 class that handles all POST and GET variables. It performs almost all of the validations functions you could need. In addition, it makes accessing the variables very convenient.<span id="more-26"></span><br />
<a href="http://labs.dawnerd.com/validation/validation-class.zip"><br />
Download here.</a> Version 1.0</p>
<p><strong>How To use:</strong><br />
First, include the class and initiate it:</p>
<pre>
<code>
<?php
include("validation.class.php");
$validation = new Validation;
?>
</code>
</pre>
<p><em>Optionally, you can use new Validation(false) to not parse all input data through the xss filter. This is not recommended.</em></p>
<p>Available functions are:</p>
<ul>
<li><code>xss($string)</code></li>
<li><code>email($string)</code></li>
<li><code>phone($string)</code></li>
<li><code>url($string)</code></li>
<li><code>db_prep($string)</code></li>
</ul>
<p>All of the above functions return a boolean value with the exception of <code>xss()</code> and <code>db_prep()</code>. Those two return a modified version of <code>$string</code>.</p>
<p>Here is an example of form validation:</p>
<pre>
<code>
<?php
$db_user = "";
$db_pass = "";
$db_serv = "";
$db_name = "";
include("../database/database.class.php");
$db = new Database($db_user,$db_pass,$db_serv,true);
if(!$db){die($db->getErrorMessage());}

include("validation.class.php");
$validation = new Validation;

echo "SELECT * FROM users WHERE user='".$validation->db_prep($validation->database_input)."'";
echo "";

if($validation->email($validation->email)) echo "valid email";
else echo "not valid email";
echo "";

if($validation->phone($validation->phone)) echo "valid phone";
else echo "not valid phone";
echo "";

if($validation->url($validation->url)) echo "valid url";
else echo "not valid url";
echo "";
?>
<form action="test.php" method="post">

database input:
<input type="text" name="database_input" id="database_input" value="<?=$validation->database_input;?>" />

email:
<input type="text" name="email" id="email" value="<?=$validation->email;?>" />

phone:
<input type="text" name="phone" id="phone" value="<?=$validation->phone;?>" />

url:
<input type="text" name="url" id="url" value="<?=$validation->url;?>" />
<input type="submit" name="test" id="dtest" value="Test" />
</form>

</code>
</pre>
<p>A demo of the above test can be <a href="http://labs.dawnerd.com/validation/test.php">found here</a>.</p>
<p>As you can see from the example above, instead of calling <code>$_GET['username']</code>, you can now call <code>$validation->username</code> without worrying about the data being &#8216;dirty&#8217;.</p>
<p>If you need help using this class, post a comment and I will gladly help you out. Also remember that this class is licensed under the <a href="http://dawnerd.com/license/">Buy Me Dew License</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://dawnerd.com/post/26_open-source-php-data-validation-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Optimizing Dynamic Content With Memcached</title>
		<link>http://dawnerd.com/post/16_optimizing-dynamic-content-with-memcached/</link>
		<comments>http://dawnerd.com/post/16_optimizing-dynamic-content-with-memcached/#comments</comments>
		<pubDate>Sat, 14 Jun 2008 06:41:11 +0000</pubDate>
		<dc:creator>Troy Whiteley</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[memcached]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[optimization]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://dawnerd.com/?p=16</guid>
		<description><![CDATA[I have posted before on how to use Memcached to reduce database load, but I failed to give a sound example. Hopefully this will rectify that. Please read this post to catch up if you haven&#8217;t already. otherwise I will &#8230; <a href="http://dawnerd.com/post/16_optimizing-dynamic-content-with-memcached/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have posted before on how to use <a href="http://www.danga.com/memcached/">Memcached</a> to reduce database load, but I failed to give a sound example. Hopefully this will rectify that. Please <a href="http://dawnerd.com/php/2008/05/07/using-memcached-to-reduce-database-load/">read this post</a> to catch up if you haven&#8217;t already. otherwise I will assume you have experience with Memcached.<span id="more-16"></span></p>
<p>In this scenario, you have a custom built blog application that has a section with the latest posts. Instead of constantly pulling this text from the database or saving the output to text files, which can be slow, saving the test into memory may be the best solution.</p>
<p>Take the following code:</p>
<pre>
<code>
$sql = "SELECT * FROM posts ORDER BY date LIMIT 5";
$query = mysql_query($sql);
if(mysql_num_rows($query)
{
     while($row=mysql_fetch_array($query))
     {
          echo "
<h2>".$row['title']."</h2>

";
     }
}
</code>
</pre>
<p>Lets make that faster.</p>
<pre>
<code>
$memcache = new Memcache;
$memcache->connect('memcache_host', 11211);
if(!$memcache->get('recent_posts'))
{
     $sql = "SELECT * FROM posts ORDER BY date LIMIT 5";
     $query = mysql_query($sql);
     $post_array = array();
     if(mysql_num_rows($query)
     {
          while($row=mysql_fetch_array($query))
          {
               $post_array[] = $row;
          }
     }
    //recent expires in one hour
    $memcache->set('recent_posts',$post_Array, 0, 3600);
}

$recent_posts = $memcache->get('recent_posts');
for($i=0;$i<count($recent_posts);$i++)
{
     echo "
<h2>".$recent_posts[$i]['title']."</h2>

";
}
</code>
</pre>
<p>You won&#8217;t notice a large increase if your site is small, but if you have a busy site and you have a bunch of spare ram, you might as well put it to use. In the future I will show you some more examples of real-world usage of <a href="http://www.danga.com/memcached/">Memcached</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://dawnerd.com/post/16_optimizing-dynamic-content-with-memcached/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Simple Solution To Minify Data From Different Locations</title>
		<link>http://dawnerd.com/post/13_simple-solution-to-minify-data-from-different-locations/</link>
		<comments>http://dawnerd.com/post/13_simple-solution-to-minify-data-from-different-locations/#comments</comments>
		<pubDate>Wed, 04 Jun 2008 18:32:38 +0000</pubDate>
		<dc:creator>Troy Whiteley</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[data collection]]></category>
		<category><![CDATA[database]]></category>

		<guid isPermaLink="false">http://dawnerd.com/?p=13</guid>
		<description><![CDATA[Lets say you use a forum software and a blogging software as the backend of your website. Lets also say that you want to create profiles for your members, but neither the forum or the blog software have the support &#8230; <a href="http://dawnerd.com/post/13_simple-solution-to-minify-data-from-different-locations/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Lets say you use a forum software and a blogging software as the backend of your website. Lets also say that you want to create profiles for your members, but neither the forum or the blog software have the support you in, and in addition you need info from both the blog and the forum. <span id="more-13"></span></p>
<p>Instead of having two different arrays of data to show a user&#8217;s information, you can combine both arrays together with <code>array_merge()</code>. This is one of my favorite php functions as it really saves you hassles.</p>
<p>This:</p>
<pre>
<code markup="none">
echo $forum_array['name']." - ".$blog_array['blogpost_count'];
</code>
</pre>
<p>Can become:</p>
<pre>
<code markup="none">
echo $user['name']." - ".$user['blogpost_count'];
</code>
</pre>
<p>Not only is it already shorter, but there is less to have to remember. All the data is right there. And to do that all you would need to do is:</p>
<pre>
<code markup="none">
$user = array_merge($forum_array,$blog_array);
</code>
</pre>
<p>Of course <code>array_merge()</code> can be used for other things as well, such as combining POST and GET data into a single array (which hopefully you would run an XSS check on it all).</p>
]]></content:encoded>
			<wfw:commentRss>http://dawnerd.com/post/13_simple-solution-to-minify-data-from-different-locations/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Ajax Username Validation with The Most Popular JS Frameworks</title>
		<link>http://dawnerd.com/post/12_ajax-username-validation-with-the-most-popular-js-frameworks/</link>
		<comments>http://dawnerd.com/post/12_ajax-username-validation-with-the-most-popular-js-frameworks/#comments</comments>
		<pubDate>Fri, 23 May 2008 21:59:02 +0000</pubDate>
		<dc:creator>Troy Whiteley</dc:creator>
				<category><![CDATA[HTML]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[prototype]]></category>
		<category><![CDATA[user interface]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://dawnerd.com/?p=12</guid>
		<description><![CDATA[It seems like every site these days uses some form of Ajax to validate form fields. One thing I cannot stand is websites that do not use Ajax to check usernames (or other data) as you type. Because a lot &#8230; <a href="http://dawnerd.com/post/12_ajax-username-validation-with-the-most-popular-js-frameworks/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>It seems like every site these days uses some form of Ajax to validate form fields. One thing I cannot stand is websites that do not use Ajax to check usernames (or other data) as you type. Because a lot of sites are lacking this one feature, I thought it would be nice to throw together a few examples of how to do it correctly with the most popular of JS frameworks. <span id="more-12"></span></p>
<p>You can view the source of the examples to see how they are done.</p>
<p><strong><a href="http://labs.dawnerd.com/ajaxusercheck_prototype/">Ajax Username Validation with Prototype</a></strong><br />
<strong><a href="http://labs.dawnerd.com/ajaxusercheck_jquery/">Ajax Username Validation with jQuery</a></strong></p>
<p><em>note: more examples will come in time. I am currently reading the mootools, dojo, and mochikit.</em></p>
<p>The only PHP code you will need is as follows:</p>
<pre>
<code markup="none">
include("../db.php");
$name = ereg_replace("[^A-Za-z0-9-]", "",mysql_real_escape_string(strip_tags(trim($_GET['name']))));
if(empty($name)) die();

$sql = "SELECT `username` FROM `common_usernames` WHERE `username` = '$name'";
$query = mysql_query($sql,$db);

if(!mysql_num_rows($query))
{
	die('<span style="font-weight:bold;color:green;font-size:12px;">'.$name.' is available!</span>');
}
else
{
	die('<span style="font-weight:bold;color:red;font-size:12px;">'.$name.' is taken!</span>');
}
</code>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://dawnerd.com/post/12_ajax-username-validation-with-the-most-popular-js-frameworks/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Emulate PHP&#8217;s Rand() Function in Javascript</title>
		<link>http://dawnerd.com/post/10_emulate-phps-rand-function-in-javascript/</link>
		<comments>http://dawnerd.com/post/10_emulate-phps-rand-function-in-javascript/#comments</comments>
		<pubDate>Tue, 20 May 2008 20:04:08 +0000</pubDate>
		<dc:creator>Troy Whiteley</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[random number]]></category>

		<guid isPermaLink="false">http://dawnerd.com/?p=10</guid>
		<description><![CDATA[Javascript&#8217;s random number generator is lacking a lot of power. To create a number between say 0 and 10, you can do this: number = Math.round(Math.random()*10); Of course you can modify this slightly to fit your needs, but this should &#8230; <a href="http://dawnerd.com/post/10_emulate-phps-rand-function-in-javascript/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Javascript&#8217;s random number generator is lacking a lot of power. To create a number between say 0 and 10, you can do this:</p>
<pre>
<code markup="none">
number = Math.round(Math.random()*10);
</code>
</pre>
<p>Of course you can modify this slightly to fit your needs, but this should be the basics needed.</p>
<p><strong>Edit:</strong> As pointed out, the code I supplied is not very random. If you need true random numbers, the mt_rand function supplied by the good guys at <a href="http://phpjs.org/functions/mt_rand:476">phpjs.org</a> is a great solution.</p>
<pre>
<code markup="none">
function mt_rand( min, max ) {
    // Returns a random number from Mersenne Twister
    //
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/mt_rand
    // +   original by: Onno Marsman
    // *     example 1: mt_rand(1, 1);
    // *     returns 1: 1
    var argc = arguments.length;
    if (argc == 0) {
        min = 0;
        max = 2147483647;
    } else if (argc == 1) {
        throw new Error('Warning: mt_rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
</code>
</pre>
<p>I would suggest using the above when you need to generate random numbers. You should also check out the rest of <a href="http://phpjs.org/">phpjs</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://dawnerd.com/post/10_emulate-phps-rand-function-in-javascript/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Quickly Creating SEO Friendly Links</title>
		<link>http://dawnerd.com/post/7_quickly-creating-seo-friendly-links/</link>
		<comments>http://dawnerd.com/post/7_quickly-creating-seo-friendly-links/#comments</comments>
		<pubDate>Fri, 09 May 2008 07:37:12 +0000</pubDate>
		<dc:creator>Troy Whiteley</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[seo]]></category>

		<guid isPermaLink="false">http://dawnerd.com/?p=7</guid>
		<description><![CDATA[Over the years I have seen many different ways programmers have used mod_rewrite to make clean urls. However, I have not seen the correct way much. All you need in your .htaccess file is this: RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} &#8230; <a href="http://dawnerd.com/post/7_quickly-creating-seo-friendly-links/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Over the years I have seen many different ways programmers have used mod_rewrite to make clean urls. However, I have not seen the correct way much. All you need in your .htaccess file is this: <span id="more-7"></span></p>
<pre>
<code markup="none">
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]
</code>
</pre>
<p>that will allow you to have all the /section/production/2/view/large sections you want without creating additional rewrite conditions. In your index.php script, you can access all of the uri data by simply doing this:</p>
<pre>
<code markup="none">
$vars = explode("/",$_SERVER['REQUEST_URI']);

foreach($vars as $value)
{
     echo $value." | ";
}
</code>
</pre>
<p>That will output all of the sections in the uri. Say you want to get a product number and the uri is:</p>
<pre>
<code>
/products/12345/
</code>
</pre>
<p>Grab the product number by getting the second key in the <code>$vars</code> array.</p>
<p>This concept is used in some major open source projects such as <a href="http://wordpress.org">WordPress</a> and <a href="http://codeigniter.com">CodeIgniter</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://dawnerd.com/post/7_quickly-creating-seo-friendly-links/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Using Memcached to Reduce Database Load</title>
		<link>http://dawnerd.com/post/6_using-memcached-to-reduce-database-load/</link>
		<comments>http://dawnerd.com/post/6_using-memcached-to-reduce-database-load/#comments</comments>
		<pubDate>Thu, 08 May 2008 05:00:00 +0000</pubDate>
		<dc:creator>Troy Whiteley</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[memcache]]></category>
		<category><![CDATA[memcached]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[optimization]]></category>
		<category><![CDATA[server loads]]></category>

		<guid isPermaLink="false">http://dawnerd.com/?p=6</guid>
		<description><![CDATA[If you host your site on a shared server environment, then this information will not be useful for you (unless the shared server had memcached installed, which would be awesome). If you run a large website, you probably should be &#8230; <a href="http://dawnerd.com/post/6_using-memcached-to-reduce-database-load/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If you host your site on a shared server environment, then this information will not be useful for you (unless the shared server had memcached installed, which would be awesome). <span id="more-6"></span></p>
<p>If you run a large website, you probably should be offsetting your database load. One popular solution is to cache database queries to files on the server&#8217;s hardrive. This is not the best way if you are looking for near instant data read times. Memcached stores data into ram, making reading and writing the data very quick.</p>
<p>A simple scenario: You increment the &#8216;views&#8217; field for a news post. All growing traffic causes a ton of updates which result in locking. Your site becomes slow. Memcached to the rescue!</p>
<pre>
<code markup="none">
$memcache = new Memcache;
$memcache->connect('memcache_host', 11211);
if(!$memcache->get('postxyz_123_views'))
{
    //sql to grab number of views

    //number expires in one hour
    $memcache->set('postxyz_123_views',$view_count, 0, 3600);
}
//increment the views
$memcache->increment('postxyz_123_views');

$view_count = $memcache->get('postxyz_123_views');
</code>
</pre>
<p>All you need to do then is run a cron job every hour and have it dump the view counts to the database.</p>
<p>That is basically all there is to using memcached. It is very simple. If you feel adventurous, check out the <a href="http://us.php.net/manual/en/ref.memcache.php">php documentation</a> for some more advanced features.</p>
]]></content:encoded>
			<wfw:commentRss>http://dawnerd.com/post/6_using-memcached-to-reduce-database-load/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Basic Traffic Shaping in PHP</title>
		<link>http://dawnerd.com/post/5_basic-traffic-shaping-in-php/</link>
		<comments>http://dawnerd.com/post/5_basic-traffic-shaping-in-php/#comments</comments>
		<pubDate>Wed, 07 May 2008 08:18:57 +0000</pubDate>
		<dc:creator>Troy Whiteley</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[download]]></category>
		<category><![CDATA[traffic shaping]]></category>

		<guid isPermaLink="false">http://dawnerd.com/?p=5</guid>
		<description><![CDATA[I ran into this problem today where we needed a PHP based solution to limit file download speeds. There are probably better ways to do this, so it might be wise to consider your possibilities before continuing. It is amazingly &#8230; <a href="http://dawnerd.com/post/5_basic-traffic-shaping-in-php/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I ran into this problem today where we needed a PHP based solution to limit file download speeds. There are probably better ways to do this, so it might be wise to consider your possibilities before continuing. <span id="more-5"></span></p>
<p>It is amazingly simple to limit download speeds with php using no more than a half-handful of built in functions.</p>
<p>To get started, define the download path, filename, and download speed.</p>
<pre>
<code markup="none">
$file_path = "/path/to/file/demosong.mp3";
$file_name = "Cool_Song.mp3";
//download speed is in kb/s
$download_rate = 50;
</code>
</pre>
<p><em>note: you can easily change the download rate on a per-mimetype basis. ex:</em></p>
<pre>
<code markup="none">
if(strstr($file_name,'.mp3'))
{
$download_rate = 30;
}
else
{
$download_rate = 150;
}
</code>
</pre>
<p>Now, check that the file exists and then send some header information.</p>
<pre>
<code markup="none">
if(file_exists($file_path) &#038;&#038; is_file($file_path))
{
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($file_path));
header('Content-Disposition: filename='.$file_name);
flush();
</code>
</pre>
<p><em>note: it is a good idea to leave the <code>flush()</code> in there.</em></p>
<p>All we have to do now is read the file in chunks. PHP will sleep every second and output the <code>$download_rate</code> to the browser.</p>
<pre>
<code markup="none">
$file = fopen($file_path, "r");
while(!feof($file)) {
print fread($file, round($download_rate * 1024));
flush();
sleep(1);
}
fclose($file);
}
else
{
die('Error: The file '.$file_name.' does not exist!');
}
</code>
</pre>
<p>That sums it up. Below is the file code.</p>
<pre>
<code markup="none">
$file_path = "/path/to/file/demosong.mp3";
$file_name = "Cool_Song.mp3";
//download speed is in kb/s
$download_rate = 50;
if(strstr($file_name,'.mp3'))
{
$download_rate = 30;
}
else
{
$download_rate = 150;
}
if(file_exists($file_path) &amp;&amp; is_file($file_path))
{
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($file_path));
header('Content-Disposition: filename='.$file_name);
flush();
$file = fopen($file_path, "r");
while(!feof($file)) {
print fread($file, round($download_rate * 1024));
flush();
sleep(1);
}
fclose($file);
}
else
{
die('Error: The file '.$file_name.' does not exist!');
}
</code>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://dawnerd.com/post/5_basic-traffic-shaping-in-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
