<?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/"
	>

<channel>
	<title>The PHP Blog</title>
	<atom:link href="http://thephpblog.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://thephpblog.com</link>
	<description>Just another WordPress weblog</description>
	<pubDate>Wed, 21 Jan 2009 16:20:34 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>We&#8217;ve got a sister!</title>
		<link>http://thephpblog.com/read/weve-got-a-sister/</link>
		<comments>http://thephpblog.com/read/weve-got-a-sister/#comments</comments>
		<pubDate>Wed, 21 Jan 2009 16:20:34 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
		
		<category><![CDATA[Basics]]></category>

		<guid isPermaLink="false">http://thephpblog.com/?p=85</guid>
		<description><![CDATA[The PHP Blog was the first of its kind from our wonderful team, but today we have an addition to the family with the launch of <a href="http://theiphonesdkblog.com/" title="The iPhone SDK Blog">the iPhone SDK blog</a>!

The iPhone SDK Blog will bring you regular tutorials on many aspects of developing applications for the iPhone, be sure to check them out and add them to your bookmarks! :)]]></description>
			<content:encoded><![CDATA[The PHP Blog was the first of its kind from our wonderful team, but today we have an addition to the family with the launch of <a href="http://theiphonesdkblog.com/" title="The iPhone SDK Blog">the iPhone SDK blog</a>!

The iPhone SDK Blog will bring you regular tutorials on many aspects of developing applications for the iPhone, be sure to check them out and add them to your bookmarks! :)]]></content:encoded>
			<wfw:commentRss>http://thephpblog.com/read/weve-got-a-sister/feed/</wfw:commentRss>
		</item>
		<item>
		<title>More Advanced Arrays</title>
		<link>http://thephpblog.com/read/more-advanced-arrays/</link>
		<comments>http://thephpblog.com/read/more-advanced-arrays/#comments</comments>
		<pubDate>Wed, 14 Jan 2009 10:49:48 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
		
		<category><![CDATA[Basics]]></category>

		<category><![CDATA[advanced]]></category>

		<category><![CDATA[array]]></category>

		<category><![CDATA[arrays]]></category>

		<category><![CDATA[variables]]></category>

		<guid isPermaLink="false">http://thephpblog.com/?p=75</guid>
		<description><![CDATA[This post is a part two of the first post on the <a href="thephpblog.com/read/bare-basics-arrays/" title="Part One">basics of arrays</a>. Today we'll look at some useful functions built for using with arrays that come as standard with PHP and some more advanced techniques.]]></description>
			<content:encoded><![CDATA[<h2>Quick Recap</h2>
<p>Ok so hopefully you read <a title="Part One" href="http://thephpblog.com/read/bare-basics-arrays/">this tutorial first</a> so that you have a basic understanding of the different types of array and what we can store in them.</p>
<h2>Built-in Array Functions</h2>
<p>Rather than mess around coding our own functions, which so many new developers do without even looking to see if it&#8217;s already been done, PHP comes with quite a lot of built-in functions to do different things with arrays. We&#8217;re not going to look at them, just the most useful ones, but if you want to see the complete list then <a href="http://uk3.php.net/array">click here</a>.</p>
<h3>Basic Functions</h3>
<p>The most basic function to do with arrays is simply <em>array()</em> itself which simply creates a new array, PHP is a forgiving language and therefore we don&#8217;t need actually need to declare an array, but if adhering to good practice then we use this function like this;</p>
<pre name="code" class="php">&lt;?php

$my_new_array = array();

?&gt;</pre>
<p>This function can also be used to create a standard number-indexed array or an associative array using some parameters, here&#8217;s another example;</p>
<pre name="code" class="php">&lt;?php

// example one - number index (0-4)
$my_pets = array('dog', 'cat', 'frog', 'fish', 'lizard');
echo $my_pets[0]; // will print 'dog' without the quotes

// example two - associative
$fruits = array('banana'=&gt;'yellow', 'pear'=&gt;'green', 'kiwi'=&gt;'green');
echo $fruits['kiwi']; // will print 'green' without the quotes
?&gt;</pre>
<p>It&#8217;s simple to create arrays with many values on one line using the <em>array()</em> function and can come in handy at times. There are other ways for building arrays though, for example it&#8217;s possible to build a multi-dimensional array out of two standard arrays using <em>array_combine()</em>. We all know that a multi-dimensional array needs two things; a key and a value, so all we need is two arrays - one for keys and one for values;</p>
<pre name="code" class="php">&lt;?php

$key_array = array('the', 'php', blog');
$value_array = array('guitar', 'spork', 'raptor');

$new_array = array_combine($key_array, $value_array);
echo $new_array['blog']; // will print 'raptor' without the quotes

?&gt;</pre>
<p>As we can see, &#8216;the&#8217;, &#8216;php&#8217; and &#8216;blog&#8217; have become keys whilst &#8216;guitar&#8217;, &#8217;spork&#8217; and &#8216;raptor&#8217; (the first three things I saw looking around my room (don&#8217;t ask).</p>
<h3>For Debugging</h3>
<p>A great function for when you&#8217;re debugging your web application, blog or whatever in between is <em>print_r()</em>. If we use <em>print($some_array)</em> then all we&#8217;ll get is PHP printing the word &#8216;Array&#8217; or similar. If we use <em>print_r($some_array)</em> then we get something a bit more interesting and useful for when we just can&#8217;t figure out what&#8217;s wrong with our code but we suspect it&#8217;s an array, it looks like this;</p>
<pre name="code" class="php">&lt;?php

$my_array = array('knife', 'fork', 'spoon');
print_r($my_array);

?&gt;</pre>
<p>This code will give us an output that looks like this;</p>
<pre class="html">Array
(
	[0] =&gt; knife
	[1] =&gt; fork
	[2] =&gt; spoon
)</pre>
<p>Now we can see the entire contents of our array, this works for any type of array.</p>
<p>Our next useful function we&#8217;re going to look at is <em>array_key_exists()</em>. If you haven&#8217;t already guessed what it does, it searches through a multi-dimensional array to see if a key exists, like this;</p>
<pre name="code" class="php">&lt;?php

$fruits = array('banana'=&gt;'yellow', 'pear'=&gt;'green', 'kiwi'=&gt;'green');

if ( array_key_exists('kiwi', $fruits) )
{
	echo 'Found a kiwi';
}

?&gt;</pre>
<p>The above code would print &#8216;Found a kiwi&#8217; because there is a key called &#8216;kiwi&#8217; in the array $fruits.</p>
<p>Next we have a function with use in some situations, maybe a random quote generator, or maybe an employer deciding who to fire today; <em>array_rand()</em>. There is no example for this function, it takes two parameters, the first one specifies the array, the second is optional and specifies how many random elements to return (default 1).</p>
<p>For searching through an array, we have the appropriately named <em>array_search()</em>, this function will search an array (second parameter) and if a value exists that matches the search then it&#8217;ll return the key. The parameters are; search value, array to search, strict. They are all self explanatory apart from strict, strict is false by default but if changed to true it will be a literal serach, meaning that &#8216;5&#8242; as a string and the number 5 without quotes are different things. This function is a bit more tricky, here&#8217;s an example (without strict);</p>
<pre name="code" class="php">&lt;?php

$fruits = array('banana'=&gt;'yellow', 'pear'=&gt;'green', 'kiwi'=&gt;'green');
echo array_search('yellow', $fruits); // will print 'banana' without the quotes

?&gt;</pre>
<p>Similar to <em>array_search()</em> is a, for some reason more popular, function called <em>in_array()</em>. This function is simplistic, the first parameter is what we&#8217;re searching for and the second parameter is the array we&#8217;re searching, this function returns true or false.</p>
<h2>Nested Arrays</h2>
<p>Now we&#8217;re wrapping up the useful functions and we&#8217;re going to briefly look at something equally useful, nested arrays. Previously we&#8217;ve looked at single-dimensional arrays, multi-dimensional arrays and now we&#8217;re going to look at nested, nested arrays are basically a multi-dimensional array where some of the values are arrays themselves. Incase you&#8217;re confused by how many times I&#8217;ve said &#8216;dimensional&#8217;, here&#8217;s an example;</p>
<pre name="code" class="php">&lt;?php

$nested = array('a' =&gt; 'the', 'b' =&gt; 'php', c =&gt; array('1', '2', '3'));
print_r($nested);

?&gt;</pre>
<p>Would give us an output a little like this;</p>
<pre class="html">Array
(
    [a] =&gt; the
    [b] =&gt; php
    [c] =&gt; Array
        (
            [0] =&gt; 1
            [1] =&gt; 2
            [2] =&gt; 3
        )

)</pre>
<p>As you can imagine, nested arrays can be very useful especially for storing stuff like user data, geographic information or anything in between.</p>
<h2>Conclusion</h2>
<p>We&#8217;ve had a quite a long tutorial with some useful functions, or maybe it just feels like that because it takes longer to write than to read. But we&#8217;ve touched on some more advanced techniques we can use with arrays, if you&#8217;re interested in reading even more into this subject then <a href="http://uk3.php.net/array">click here</a> for a complete list!</p>
<p>Hope you enjoyed this tutorial, if you have any comments or questions then leave a comment.</p>
]]></content:encoded>
			<wfw:commentRss>http://thephpblog.com/read/more-advanced-arrays/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Bare Basics - Arrays</title>
		<link>http://thephpblog.com/read/bare-basics-arrays/</link>
		<comments>http://thephpblog.com/read/bare-basics-arrays/#comments</comments>
		<pubDate>Fri, 09 Jan 2009 14:46:03 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
		
		<category><![CDATA[Basics]]></category>

		<guid isPermaLink="false">http://thephpblog.com/?p=71</guid>
		<description><![CDATA[One thing you can’t escape in your PHP journey is arrays, at one point or another they’ll crop up in your simple script, your project or anything in between. Arrays are relatively to simple to use, but can be a bit daunting for people new to programming or just PHP.

Today we’ll look at arrays from a simple array, to a key and value array, finally we’ll have a look at expanding on arrays with a multi-dimensional array.]]></description>
			<content:encoded><![CDATA[<h2>What is an array?</h2>
<p>The concept of arrays are simple. If you create a variable to store a value, it does exactly that, stores a single value. Whether it&#8217;s an integer, string or anything in between. An array is basically a variable that can hold multiple values. Arrays have many uses, but that&#8217;s a little beyond what we&#8217;re looking at in this tutorial, we&#8217;re just trying to get to grips with them for now. Let&#8217;s look at the basic syntax for an array;</p>
<pre name="code" class="php">
&lt;?php

$my_array[0] = 'Red';
$my_array[1] = 'Green';
$my_array[2] = 'Blue';

?>
</pre>
<p>
Here we&#8217;ve created an array that holds three different values, Red, Green and Blue respectively. These values can be referenced by their number, 0-2. An <b>important note</b> is that arrays are typically started from 0, so in our array which holds values 0-2, there are three values. Forgetting to count the 0 as a number in programming is often called a fencepost error (or off-by-one error). The values are accessed in the same way they are set;</p>
<pre name="code" class="php">
&lt;?php

// echo's 'Red and Blue' (without quotes)
echo $my_array[0] . ' and ' . $my_array[2];

?>
</pre>
<p>
Using arrays in this way can have many uses, but let&#8217;s say for arguments sake (so we have something to learn) that we want to store the hex values for the colours (or &#8216;colors&#8217; for those who choose to butcher the english language!), why not? Let&#8217;s have a look at two solutions, one is the bad solution using variables that you so often see in newbie projects, one is the better solution using arrays;</p>
<pre name="code" class="php">
&lt;?php

// messy, messy, messy!
$colour_one_name = 'Red';
$colour_one_hex = '#ff0000';
$colour_two_name = 'Green';
$colour_two_hex = '#00ff00';
$colour_three_name = 'Blue';
$colour_three_hex = '#0000ff';

// the better approach
$colours['red'] = '#ff0000';
$colours['green'] = '#00ff00';
$colours['blue'] = '#0000ff'; 

?>
</pre>
<p>
As you can see, the array approach is much tidier and saves a lot of lines of code in comparison to the variable approach. Ok now we&#8217;ve learnt the basics of an array, it can hold a number and a value or a key and a value. Well what if we wanted to store something like employee details (how cliche), we&#8217;ll need a sort of&#8230; array-within-an-array scenario?&#8230;</p>
<h2>Multi-Dimensional Arrays</h2>
<p>Ooooh, doesn&#8217;t it sound scary? Have no fear, multi-dimensional arrays, or associative arrays, may have a big name but they&#8217;re actually very simple (and even more useful!). So let&#8217;s go back to that previous situation of employee records, of course with what we&#8217;ve learnt so far we could come up with something that could work&#8230;</p>
<pre name="code" class="php">
&lt;?php

$employee_one['name'] = 'Dan Walker';
$employee_one['email'] = 'dan[at]thephpblog[dot]com';
$employee_one['gender'] = 'm';
$employee_one['salary'] = 99999999; // one day....

$employee_two['name'] = 'Joe Bloggs';
$employee_two['email'] = 'joe[at]bloggs[dot]com;
$employee_two['gender'] = 'm';
$employee_two['salary'] = 20000; // one day....

?>
</pre>
<p>
The above works, we&#8217;ve created two arrays, one for each employee, and filled it with data using the key and value method we learned about earlier. That&#8217;s great, but what if we wanted to create a loop that displayed all our employee names or something? Well then we&#8217;d be pretty screwed because they have different names and we&#8217;d have to recode everything every time we added a new employee! Not good! But what if we could put a key and value array <b>inside</b> a standard incremental array. Now you&#8217;re thinking!</p>
<pre name="code" class="php">
&lt;?php

$employees[0]['name'] = 'Dan Walker';
$employees[0]['email'] = 'dan[at]thephpblog[dot]com';
$employees[0]['gender'] = 'm';
$employees[0]['salary'] = 99999999;

$employees[1]['name'] = 'Joe Bloggs';
$employees[1]['email'] = 'joe[at]bloggs[dot]com';
$employees[1]['gender'] = 'm';
$employees[1]['salary'] = 20000;

?>
</pre>
<p>
<b>Note: </b>Notice that the salary values do not have quotes round them, that&#8217;s because they&#8217;re integers - arrays can hold different types of data just as a variable can.<br />
Now that my friend is looking a lot cleaner. The logic is simple, <i>$employees[0]</i> now contains another array, as does <i>$employees[1]</i>. Because these arrays are nested within another array, this is where we get the name multi-dimensional array from (as if you hadn&#8217;t already guessed that).</p>
<p>Because we&#8217;ve done it this way we can now cycle through loops to do stuff, let&#8217;s say we want to list all our employee names, this is how we&#8217;d do it.</p>
<pre name="code" class="php">
&lt;?php

$employees[0]['name'] = 'Dan Walker';
$employees[0]['email'] = 'dan[at]thephpblog[dot]com';
$employees[0]['gender'] = 'm';
$employees[0]['salary'] = 99999999;

$employees[1]['name'] = 'Joe Bloggs';
$employees[1]['email'] = 'joe[at]bloggs[dot]com';
$employees[1]['gender'] = 'm';
$employees[1]['salary'] = 20000;

for ($i=0; $i&lt;count($employees); $i++)
{
	echo $employees[$i]['name'] . '&lt;br />';
}

?>
</pre>
<p>
Would list the two employee names on different lines. You see if we use <i>count($employees)</i> then it counts how many values are in the top layer of our array, the first brackets. There are 2 values in this array and so the loop loops twice. It&#8217;s important to remember we start the loop from 0 because our array starts from 0.</p>
<h2>Conclusion</h2>
<p>Of course this has just been the basics of arrays, if you&#8217;re interested in how we could use an array like our employees one, why not take a look at my <a href="#" title="PHP MySQL Class">PHP MySQL class</a> which stores its results in a multi-dimensional array.</p>
<p>Thanks for reading, questions and comments welcome =]</p>
]]></content:encoded>
			<wfw:commentRss>http://thephpblog.com/read/bare-basics-arrays/feed/</wfw:commentRss>
		</item>
		<item>
		<title>We&#8217;ve moved host, no more downtime!</title>
		<link>http://thephpblog.com/read/weve-moved-host-no-more-downtime/</link>
		<comments>http://thephpblog.com/read/weve-moved-host-no-more-downtime/#comments</comments>
		<pubDate>Sun, 04 Jan 2009 15:42:43 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
		
		<category><![CDATA[Site News]]></category>

		<guid isPermaLink="false">http://thephpblog.com/?p=67</guid>
		<description><![CDATA[The PHP Blog has moved host from Crissic to <a href="http://secure.hostgator.com/cgi-bin/affiliates/clickthru.cgi?id=Demonix">HostGator</a> and hopefully the downtime we've been experiencing lately is no more!<br /><br />
We'd like to apologize about the recent down time, our previous host Crissic decided to go down for days at a time with no explanation, when the site finally came back online we took a backup and moved host instantly.]]></description>
			<content:encoded><![CDATA[<h2>Bad Timing</h2>
<p>When you&#8217;re trying to get a site off the ground like a tutorial site and your hits are steadily increasing the worst thing that could happen is an unexpected period of downtime with no explanation, especially when that downtime is about 5 days long.</p>
<p>Recently we&#8217;ve experienced a lot of downtime thanks to our previous host, Crissic. Although it is not the job of this blog to compare and evaluate hosts, we&#8217;d heavily recommend not using Crissic and definitely using <a href="http://secure.hostgator.com/cgi-bin/affiliates/clickthru.cgi?id=Demonix">HostGator</a> due to the quick support, cheap plans and ease of setup.</p>
<p>Again we apologize for all the recent downtime but hopefully this has come to an end!<br />
The PHP Blog team</p>
]]></content:encoded>
			<wfw:commentRss>http://thephpblog.com/read/weve-moved-host-no-more-downtime/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Getting to Grips With Functions</title>
		<link>http://thephpblog.com/read/getting-to-grips-with-functions/</link>
		<comments>http://thephpblog.com/read/getting-to-grips-with-functions/#comments</comments>
		<pubDate>Thu, 04 Dec 2008 11:38:54 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
		
		<category><![CDATA[Basics]]></category>

		<guid isPermaLink="false">http://thephpblog.com/?p=63</guid>
		<description><![CDATA[More often than not, new developers tend to repeat a lot of code in their websites and web apps instead of recycling them. Functions give you the freedom to alter code all throughout your website or web app in one place, both convenient and it helps avoid errors!<br />
<br />
We'll look at why functions should be used, where they should be used, how they should be used and some special techniques you should be using.]]></description>
			<content:encoded><![CDATA[<h2>An overview of functions</h2>
<p>Using functions in your code should be 2nd nature in medium to large scale projects. In basic terms, a function is a block of code with a name, and a majority will take parameters/arguments and return a value(s). If you&#8217;ve done PHP before (if you&#8217;re reading this I&#8217;m guessing you have) you no doubt will have encountered functions without knowing it - here&#8217;s some you&#8217;ve probably ran into; <i>echo()</i>, <i>require_once()</i>, <i>include_once()</i>, <i>die()</i>. All of these functions are already built in to PHP and unlike other languages you don&#8217;t need to do anything before you can use them.</p>
<h3>Basic syntax</h3>
<p>There&#8217;s two pieces of code you need to know when using and creating functions, the code to create them and the code to call them. Let&#8217;s take a look at both.</p>
<pre name="code" class="php">
function myFunction(/* parameters here*/)
{
	// code goes here

	// return a value (optional)
	return true;
}
</pre>
<p>This code would create a (useless) function called myFunction(), to call it in our code we&#8217;d do something like this;</p>
<pre name="code" class="php">
myFunction(/*parameters here*/);
</pre>
<p>
Obviously without the commented /*parameters here*/. As you can see, by storing a chunk of code in one location and referencing it rather than rewriting it over and over again, if we have a problem with the code we only have to edit one location rather than several. Also if we want to update the code or anything in between, we can again do it from one location. Of course, nothing makes sense without a real world example, so lets say that we have an application that needs to check if a number is even, here&#8217;s a simple way of how we&#8217;d go about that;<br />
</p>
<pre name="code" class="php">
function is_even($number)
{
	if ($number % 2 == 0 )
	{
		return true;
	} else {
		return false;
	}
}

$myNumber = 1491823;

if ( is_even($myNumer) )
{
	echo $myNumber . ' is even!';
} else {
	echo $myNumber . ' is odd!';
}
</pre>
<p>
Granted the above function won&#8217;t be the most useful one you&#8217;ll keep under your belt but the theory is there. Let&#8217;s go through it bit by bit and see what&#8217;s happening. First of all we&#8217;re creating a function called <i>is even</i> which takes one parameter called <i>$number</i>. A parameter is something you can pass into a function, it can be a number, string, variable and so on. Next up for those of you who don&#8217;t know what the % is, it shows the remainder, obviously dividing an even number in 2 will have no remainder which is how we find out what the number is. The rest of the code is self explanatory, we can use it just like any other function.</p>
<p>But hang on, let&#8217;s roll back a bit and take another look at the variables we&#8217;re using. Now something to keep in mind is that outside of the function {} we can not edit any of the variables inside, vice versa - we can not edit variables not inside the function {} from inside the function {} - not the best way to word it, so let&#8217;s move on and look at an important factor of functions&#8230;</p>
<h2>Variable scope</h2>
<p>Variable scope is quite a large subject and we only want to know what we need, so we won&#8217;t go too far in depth but I heavily recommend looking it up and doing some further reading, it can cause a lot of problems if you&#8217;re not knowledged in the area.</p>
<p>Every variable is born with its own scope, a scope is the area in which it can be used in any way. Look at this example;</p>
<pre name="code" class="php">
function set_something()
{
	$something = 'hello world';
}

echo $something;
</pre>
<p>This would echo nothing as <i>$something</i> is <b>local</b> to the function. Variables defined inside functions are local to that function and can not be used by the main body of code as standard. However, the scope of variables can be expanded. The following two examples will work.<br />
</p>
<pre name="code" class="php">
$myVar = 1;

function example()
{
	global $myVar;

	$myVar = $myVar + 10;
	return $myVar;
}

echo example(); // would echo 11
</pre>
<p></p>
<pre name="code" class="php">
$myVar = 1;

function example()
{
	$GLOBALS['myVar'] = $GLOBALS['myVar'] + 10;
}

echo $myVar; // would echo 11
</pre>
<p>
That&#8217;s right kids, the way functions can access variables outside their local scope is to either declare the variable as global as in example #1 or to use the superglobal - $GLOBALS. So long as the function knows to look for a variable in the global scope, we&#8217;re in business. </p>
<p>Whilst we&#8217;re on the subject of scope let&#8217;s quickly brush on to static scope variables and their use within functions. We know that normal variables in a function have local scope, to use variables outside the function we use the global scope, but when a function ends and returns the control to the main code again it will forget any local variables it used, what if we wanted to remember them?</p>
<p>Introducing the <i>static</i> varaible. Static variables are identical to local scope variables with the exception they will only be initialized once and will be remembered in the function. Let&#8217;s say you want a function to keep count of something, for our example let&#8217;s say we want to keep count of how many times we query a database, it&#8217;d need to look a little something like this;</p>
<pre name="code" class="php">
$myVar = 1;

function query_count()
{
	// only initalized once
	static $count = 0;

	$count++;

	echo $count;
}

// some query here
query_count();
// some query here
query_count();
// some query here
query_count();
</pre>
<p>
The above would echo 123. The <i>static $count = 0;</i> is the code that <b>initializes</b> the variable and is only executed once and ignored then on. Also for those who are wondering what the <i>++</i> means, it incremements the variable calling it by 1.</p>
<h3>The one-line return</h3>
<p>The return command doesn&#8217;t just return true, false or a variable, it can be used for pretty much anything.</p>
<pre name="code" class="php">
function some_function()
{
	$some_var = $var_a + $var_b;
	return $some_var
}
</pre>
<p>
Can be expressed as</p>
<pre name="code" class="php">
function some_function()
{
	return $var_a + $var_b;
}
</pre>
<p>
Just a small tip that saves time, lines of code and variables. The return function can do anything, even call other functions!</p>
<h2>Conclusion</h2>
<p>Well I hope you&#8217;ve got to grips with basic functionality of functions (pun?), be sure to keep a look out for part 2 where we&#8217;ll look at more in depth and advanced functions and varaibles. Any questions or suggestions let me know just below (poet?!)</p>
]]></content:encoded>
			<wfw:commentRss>http://thephpblog.com/read/getting-to-grips-with-functions/feed/</wfw:commentRss>
		</item>
		<item>
		<title>The ins and outs of SQL injection</title>
		<link>http://thephpblog.com/read/the-ins-and-outs-of-sql-injection/</link>
		<comments>http://thephpblog.com/read/the-ins-and-outs-of-sql-injection/#comments</comments>
		<pubDate>Thu, 27 Nov 2008 10:57:46 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
		
		<category><![CDATA[Databases]]></category>

		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://thephpblog.com/?p=42</guid>
		<description><![CDATA[SQL injection is one of the biggest and most overlooked flaws on the web today, with the advent of millions of hosting companies that offer you your own database and scripting language to play with, anyone can setup their own community, blog or anything in between. Developers who are unskilled tend to leave a lot of flaws in their code, room for SQL injection is one of the most dangerous.

In this tutorial we'll look at how attackers use SQL injection for the purpose of damage or unauthorized access and how to protect you and your site against it.]]></description>
			<content:encoded><![CDATA[<h2>What is SQL injection?</h2>
<p>SQL injection is an extremely overlooked problem, especially with how easy it is for Joe Bloggs and John Smith to setup their own website and do with it what they wish. SQL injection is the equivalent of letting any old user manipulate your database, be it for malicious purposes or not.This dangerous flaw is easy to prevent, however it is easier to overlook. Every time your website or application commits an SQL query with input that is given to it from the user, it is a possibility for SQL injection if you are not safeguarded properly. Today we&#8217;re going to learn how the SQL injection is done and how to prevent it in easy to swallow chunks, here we go&#8230;</p>
<h2>Right, so how do you do it?</h2>
<p>It&#8217;s much simpler than it sounds, SQL injection is simply changing the query from what it was intended to do with it what you wish, let&#8217;s skip the boring footwork and jump in head first. In order to &#8216;do&#8217; SQL injection you need a vulnerable website or application, of course to demonstrate prevention and so on we need to use a language, surprise surprise the language we&#8217;ll be using today is PHP coupled with it&#8217;s wonderful brethren, MySQL. Consider this, you have a page called profile.php that when accessed properly will pull information about a certain user from your wonderfully crafted database. Let&#8217;s say the query looks like this;</p>
<pre name="code" class="php">mysql_query("SELECT 	first_name,
						last_name
						FROM users
						WHERE user_id = '$_GET['id']'");</pre>
<p>Seemingly harmless, when executed properly this query will pull two fields from a table called users. In order to <span style="text-decoration: line-through;">wreak havoc</span> inject SQL into this query we need to perform our own query, let&#8217;s say for example; DROP TABLE users, seems only right. Obviously if we visited profile.php?id=123 then the query would look a little like this;</p>
<pre name="code" class="php">mysql_query("SELECT 	first_name,
						last_name
						FROM users
						WHERE user_id = '123'");</pre>
<p>Simple enough, this query will fetch the first name and last name of a user who has an ID of 123. Obviously not the best designed query as it&#8217;d be better to limit the amount of results etc but that is beyond the scope of this tutorial. Now let&#8217;s say we change profile.php?id=123 to profile.php?id=DROP TABLE users. The query that is executed now looks something like this;</p>
<pre name="code" class="php">mysql_query("SELECT 	first_name,
						last_name
						FROM users
						WHERE user_id = 'DROP TABLE users'");</pre>
<p>Pretty useless. All this query is doing is what&#8217;s intended of it and searching for a record where the user_id is set to DROP TABLE users. To actually make our command execute, we need to &#8216;escape&#8217; the friendly SQL query and insert our own query, I&#8217;d like to introduce the single quote ( &#8216; ). When you search for a string using SQL, in order to prevent the string from interfering with the query, it is wrapped in a set of single quotes. If we use a single quote in our query it suddenly becomes a little more interesting. Let&#8217;s try &#8216;DROP TABLE users.</p>
<pre name="code" class="php">mysql_query("SELECT 	first_name,
						last_name
						FROM users
						WHERE user_id = ''DROP TABLE users'");</pre>
<p>What we have done is made it so that the string to search for is simply blank, by using a single quote we have closed the string and we are now inside the actual query, exciting isn&#8217;t it? If you were to execute the above query all you&#8217;d receive back would be an error (although this varies depending on the PHP configuration). &#8216;Great&#8217; I hear you saying, but one of the golden rules when trying to exploit something is learning to love error messages. One of the quickest ways to find out whether a site can be exploited is to slap a single quote in a few of the $_GET variables and see if you receive an error message. If you do then it&#8217;s likely there&#8217;s a gaping hole for you to <span style="text-decoration: line-through;">destroy</span> report to the local administrator. Of course this isn&#8217;t always true, depending on many factors and should only be used as a quick first resort to check for vulnerability.</p>
<p>So we have an error message, awesome, we can manipulate the SQL query! Now the reason the above query didn&#8217;t work is because it is read as a single command to execute, we&#8217;re executing a SELECT command to select records from a database, shoving a DROP TABLE command in half way through isn&#8217;t going to be expected and therefore it&#8217;s going to cause a problem. The way we get round this is to close the SELECT command in order to inject our own SQL. The way to properly end a command in SQL is the same as with most languages, with a semi-colon, so all we need to do is end the previous command and then begin our own. One thing we need to remember is that the query we&#8217;re ending mustn&#8217;t cause an error because if it does then the error will stop the query and our command won&#8217;t be reached. Let&#8217;s inject.</p>
<pre name="code" class="php">mysql_query("SELECT 	first_name,
						last_name
						FROM users
						WHERE user_id = ''; DROP TABLE users'");</pre>
<p>We inserted &#8216;; DROP TABLE users. What we did was inserted an apostrophe to close the string followed by a semi-colon to end the query that&#8217;s searching for the user, as far as anyone is concerned the first command in this query is valid, the second one however is not. Why? Because after our command there is a single apostrophe lingering from the first command where we injected. Uh oh. Our command won&#8217;t be executed because there&#8217;s an error in it now. Another hurdle that can be jumped, essentially we need to ignore everything after what we&#8217;ve injected, we don&#8217;t care about it. In order to ignore the rest we have to use an SQL comment signified by two hyphens (&#8211;). Once two hyphens are read, the rest of the query is simply ignored and what we have is a successful command, before we comment out the rest of the query however, we need to end our command with the semi-colon. All in all our query now looks like this.</p>
<pre name="code" class="php">mysql_query("SELECT 	first_name,
						last_name
						FROM users
						WHERE user_id = ''; DROP TABLE users;--'");</pre>
<p>Voila, you&#8217;ve just upset a database administrator somewhere, congratulations. Now one thing we should touch on is getting around basic PHP/MySQL authorization with SQL injection.</p>
<h3>Correct login OR 1=1?</h3>
<p>Some (very) weak PHP login scripts that use a MySQL database use the actual query to check authorization rather than querying the database and then doing some playing with the results. Here&#8217;s an example of an extremely weak query;</p>
<pre name="code" class="php">myqsl_query("SELECT 	user_id
						FROM users
						WHERE username = '".$username."' AND password = '".$password."'");</pre>
<p>Now the reason people might use this query for authorization is that when the username and password specified are found in the database the above query will return TRUE, well actually it&#8217;ll return the user_id but for our example we&#8217;ll just assume that the PHP code just checks for any returned value. If the user isn&#8217;t found, the query will evaluate theoretically to FALSE. With this information in mind we already know that in order to get round this authorization, what we need is the query to return true - we can do this with some more SQL injection.</p>
<p>Assuming that the above query is used in the PHP code, we need to inject something that will make the query return true (or a value) no matter what credentials we supply. Well first we need to break into this query, there are two possibilities here; username and password, we&#8217;re going to use username. Now we know where we&#8217;re going to break into the query we need to make it return true, what will always return true?&#8230; 1=1. We need to tell MySQL to evaluate 1=1 rather than the username and password, to do that we&#8217;re going to use a little boolean algebra and use OR. Let&#8217;s see what this looks like with the username field injected;</p>
<pre name="code" class="php">myqsl_query("SELECT 	user_id
						FROM users
						WHERE username = '' OR 1=1;--' AND password = '".$password."'");</pre>
<p>By inserting a single quote, we escape from the username comparison and we&#8217;re now in the SQL query as we&#8217;ve previously learned. The next thing we do is insert an OR clause, this checks to see if the username is blank OR 1=1 and of course we then need to end this command and comment out the rest. Voila.</p>
<p>Now it&#8217;s all well and good being able to conduct SQL injection, but now it&#8217;s time to move on to the more important matter&#8230;</p>
<h2>Countering SQL injection</h2>
<p>It&#8217;s important to understand how the attackers will attempt to use SQL injection to attack your website in order to understand where the threats/weaknesses lie so we can use this knowledge to secure these flaws. You might be expecting paragraph upon paragraph of information on countering this threat but in reality you can protect yourself against it easily.</p>
<p>As with all input that PHP uses, it should be sanitized to ensure it can not interfere where it shouldn&#8217;t. The obvious method for protection is to simply remove all single quotes from a string or simply display an error if they are used, but this can cause problems when you apply it to a website that needs to display single quotes such as a review website or forum where you need to use words like can&#8217;t and don&#8217;t etc.</p>
<p>Note: It&#8217;s important to remember that the great thing about PHP is people can solve things in their own way, everyone has their own preferred method for countering SQL injection and this just happens to be the way I&#8217;ve chosen to convey to you.</p>
<h3>Escaping characters</h3>
<p>In order to use certain characters safely in a query, we need to escape them. This means prepending then evil character with a backslash, so &#8216; becomes \&#8217; and for extra safety, \ becomes \\. Now finding all the evil characters and putting backslashes in front of them might seem a bit of a chore, but PHP has a few handy functions that can help us. One of the most common is the addslashes() and stripslashes() functions. It is as simple as it sounds, addslashes() will add slashes before your evil characters and stripslashes() will take them away. Simple as that. Here&#8217;s a quick example;</p>
<pre name="code" class="php">$evil_name = "dan' OR 1=1;--";
$password = "abc123"
mysql_query("SELECT 	*
			FROM users
			WHERE username='".addslashes($evil_name)."' AND password='".addslashes($password)."'");</pre>
<p>This query should now be safe to run as the quotes in the original name have been escaped, the username now looks like this: dan\&#8217; OR 1=1&#8242;&#8211; which is not harmful to our query. Although there are many methods in which to prevent SQL injection, we&#8217;re just going to look at one more function provided by PHP and that&#8217;s mysql_real_escape_string(). This function has a little sister called mysql_escape_string(), the difference is that mysql_real_escape_string() takes into account the current character set used in the connection to the database. Using the same method as above, the query would look like this;</p>
<pre name="code" class="php">$evil_name = "dan' OR 1=1;--";
$password = "abc123"
mysql_query("SELECT 	*
			FROM users
			WHERE username='".mysql_real_escape_string($evil_name)."' AND mysql_real_escape_string ='".addslashes($password)."'");</pre>
<p>Another safe query successfully executed on the database.</p>
<h3>Conclusion</h3>
<p>We&#8217;ve learnt today that SQL injection is a major threat if not dealt with correctly and dealing with it isn&#8217;t at all hard and is only overlooked by developers who are either not knowledgable in this area or those who are just plain lazy. There are exceptions (human error) when skilled developers forget to apply SQL injection countering and this is why still today flaws exist on millions of sites (as a small example i found one in the United Nations website which was exploited a few months later by turkish hackers).</p>
<p>Remember that all input from users can&#8217;t be trusted, and you have to treat everything you use as another possibility for a bad guy to find their way in, don&#8217;t get caught out. I hope you enjoyed this tutorial, the first tutorial on this blog, any questions etc are welcome using the comments form below, or by sending me an email at [dan] [at-symbol] thephpblog[dot]com</p>
]]></content:encoded>
			<wfw:commentRss>http://thephpblog.com/read/the-ins-and-outs-of-sql-injection/feed/</wfw:commentRss>
		</item>
		<item>
		<title>The PHP Blog is launched!</title>
		<link>http://thephpblog.com/read/the-php-blog-is-launched/</link>
		<comments>http://thephpblog.com/read/the-php-blog-is-launched/#comments</comments>
		<pubDate>Sat, 22 Nov 2008 10:52:54 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
		
		<category><![CDATA[Site News]]></category>

		<guid isPermaLink="false">http://thephpblog.com/?p=36</guid>
		<description><![CDATA[Welcome all, to the opening of The PHP Blog. We've got a lot in store for you and we hope you enjoy all of our tutorials to come! We're a blog dedicated to teaching web development to the masses, you can also request tutorials to your own liking! ]]></description>
			<content:encoded><![CDATA[<h2>What can I expect here?</h2>
<p>Basically we&#8217;re aiming to cover all aspects of PHP coding that the common developer will run in to, we&#8217;ll also aim to teach you new techniques and styles to improve your codes efficiency, style and overall effectiveness.</p>
<h2>Stay tuned!</h2>
<p>With the launch of The PHP Blog we&#8217;ll aim to deliver 1-2 tutorials a week and as time progresses we&#8217;ll aim to expand our staff force and bring you more weekly updates, thanks for reading and we hope you stay tuned <img src='http://thephpblog.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://thephpblog.com/read/the-php-blog-is-launched/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
