<?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>edrackham &#187; PHP</title>
	<atom:link href="http://edrackham.com/category/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://edrackham.com</link>
	<description>PHP, MySQL, JavaScript and Other Web Tutorials!</description>
	<lastBuildDate>Thu, 04 Aug 2011 08:30:57 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Top 10 PHP Tips, Functions and Techniques You Need to Know</title>
		<link>http://edrackham.com/php/top-10-php-tips-functions-techniques-you-need-to-know/</link>
		<comments>http://edrackham.com/php/top-10-php-tips-functions-techniques-you-need-to-know/#comments</comments>
		<pubDate>Tue, 19 Oct 2010 21:08:54 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://edrackham.com/?p=141</guid>
		<description><![CDATA[This is a rundown of my top 10 PHP functions and techniques that I use on a daily basis (pretty-much) and thought I&#8217;d share them with you. Hopefully there&#8217;s some gems in there that you have never heard of (or used), that will change the way you code. #10 &#8211; print_r() print_r() is probably my [...]]]></description>
			<content:encoded><![CDATA[<p>This is a rundown of my top 10 PHP functions and techniques that I use on a daily basis (pretty-much) and thought I&#8217;d share them with you. Hopefully there&#8217;s some gems in there that you have never heard of (or used), that will change the way you code.<span id="more-141"></span><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h2>#10 &#8211; print_r()</h2>
<p><strong>print_r()</strong> is probably my most used function. This allows you to recursively print an array, multi-dimensional array or even an object. It&#8217;s great for getting a useful visual representation of one of the aforementioned data types. Here&#8217;s a quick example:</p>
<pre name="code" class="php">
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
</pre>
<p>Will print:</p>
<pre>
Array
(
    [a] => apple
    [b] => banana
     => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>
<p>I find this immensely useful for debugging arrays, so I think you&#8217;ll find this one of those top tips you keep coming back to. You can pass a second boolean parameter if you just need to return the result of print_r to a variable. This is useful for sending debug data in emails and things like that.</p>
<h2>#9 &#8211; Variable variables (double-dollar $$)</h2>
<p>This is a good little tip &#8211; Imagine you had a variable called <strong>$fruit</strong>, declared like the following:</p>
<pre name="code" class="php">
$fruit = "apple";
</pre>
<p>Now what if we wanted to use the <em>value</em> of the variable <strong>$fruit</strong> to create a new variable, which is named as the value &#8211; we&#8217;d simply use:</p>
<pre name="code" class="php">
$$fruit = "juicy";
</pre>
<p>This has now created two variables:</p>
<pre name="code" class="php">
$fruit = "apple";
$apple = "juicy";
</pre>
<p>What this has done, is shown us how to create a variable variable. The basic thing to note with variable variables (double dollar / $$) is that we can create a variable which is named as per the value of another variable.</p>
<h2>#8 &#8211; Ternary Operators</h2>
<p>Ternary operators are a cleaner way of doing an if &#8230; else statement. Look at the following example, and I&#8217;ll explain it below:</p>
<pre name="code" class="php">
echo ($myBoolean) ? 'True' : 'False';
</pre>
<p>We could write this as:</p>
<pre name="code" class="php">
if($myBoolean){
  echo 'True';
}else{
  echo 'False';
}
</pre>
<p>But as you can see, it&#8217;s much cleaner. What happens is we have a test case, then what happens if it&#8217;s true, then what happens if it&#8217;s false:</p>
<pre name="code" class="php">
(TESTCASE) ? TRUE_ACTION : FALSE_ACTION;
</pre>
<p>You can &#8220;chain&#8221; ternary operators, take a look at the one from the PHP documentation:</p>
<pre name="code" class="php">
echo (true?'true':false?'t':'f');
</pre>
<p>Which outputs &#8216;t&#8217;. It does this, because the statement is evaluated from left to right &#8211; so in the above example, we have true, which makes the first ternary operator <em>return</em> true, so the second part (after the second question mark) returns the true part &#8216;t&#8217;.</p>
<h2>#7 &#8211; glob()</h2>
<p>Glob is my preferred method for listing files within a directory (as opposed to readdir(), and other long-winded methods). It&#8217;s great for getting a list of images (for example) within a directory. To do this, you would use something like:</p>
<pre name="code" class="php">
$images = glob("/path/to/images/*.{jpg,gif,png}", GLOB_BRACE);
</pre>
<p>Which would return an array of images (with their path names). We&#8217;re using <strong>GLOB_BRACE</strong> here, which allows us to use a braced expression &#8211; {jpg,gif,png} &#8211; so glob will search for all files ending with either of those extensions. A much more simple glob example would be as follows:</p>
<pre name="code" class="php">
$phpFiles = glob("*.php");
</pre>
<p>Which would return an array of php files, and stick the array into the <strong>$phpFiles</strong> variable.</p>
<h2>#6 &#8211; json_encode()</h2>
<p>I use this function for two main things. Firstly, if I&#8217;m doing an AJAX call, I use this to return a JSON object back to the calling JavaScript as it&#8217;s a nice, clean way of accessing objectified data. Secondly, and much less commonly, I use this function over PHP&#8217;s serialize() function, to store an array of data, or even an object, in a database table.</p>
<p>You can simple pass any value (except a resource) to be encoded. I generally just use arrays, or objects. The example (which is more than suffice) I&#8217;ll us, is the one from the PHP documentation:</p>
<pre name="code" class="php">
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
</pre>
<p>Which gives us:</p>
<pre>
{"a":1,"b":2,"c":3,"d":4,"e":5}
</pre>
<p><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h2>#5 &#8211; ob_gzhandler()</h2>
<p>Thanks to using Google&#8217;s page speed analyzer &#8211; I now use ob_gzhandler() at the start of all of my pages. I usually include this in a header config file, so that it naturally gets included across the entire site. What this does is it checks to see if the requesting browser supports gz encoded data, and if it does, it will compress the entire page and push a much smaller file to the browser, therefore helping to speed up your pages. You simply just need to call the following, and it works automagically:</p>
<pre name="code" class="php">
ob_start("ob_gzhandler");
</pre>
<h2>#4 &#8211; mysql_real_escape_string()</h2>
<p>There&#8217;s a good chance that you might already know this one &#8211; but if you don&#8217;t, you really should. This function will ensure that any variables passed into your queries for execution against a MySQL database are safe. An example of how to use this would be:</p>
<pre name="code" class="php">
$query = 'SELECT * FROM customers WHERE name = "' . mysql_real_escape_string($name) . '"';
mysql_query($query);
</pre>
<p>Generally speaking, <strong>$name</strong> will be safe (i.e. not have any nasty SQL injections in) but if this was a user-submitted form, and the user was malicious &#8211; they might enter something like <strong>&#8221; OR 1=1&#8211;</strong> which <em>is</em> a MySQL injection string. Without using <strong>mysql_real_escape_string()</strong> &#8211; our query would look like:</p>
<pre>
SELECT * FROM customers WHERE name = "" OR 1=1--;
</pre>
<p>Which would get all results, as we&#8217;re using an OR clause that will always return true. The double dash just tells MySQL to ignore everything after it (same as a comment in PHP really). This could be potentially used to get all sorts of data from a database. So, use mysql_real_escape_string() and you can sleep at night, in the knowledge that some uber leet skript kiddie won&#8217;t be gaining access through your tables!</p>
<h2>#3 &#8211; Forcing File Downloads</h2>
<p>Sometimes, it&#8217;s much nicer to have your users download a file, rather than simply display it on the page. For example, let&#8217;s say we have an image gallery which allows users to purchase selected images. When they purchase, it would be nicer to provide them with a download dialog box, rather than display the image and expect them to right-click save-as. To do this, you&#8217;d simply use:</p>
<pre name="code" class="php">
header("Content-type: application/octet-stream");
header("Content-Length: " . filesize('image.jpg'));
header('Content-Disposition: attachment; filename="image.jpg"');
readfile('image.jpg');
</pre>
<p>Replace &#8216;image.jpg&#8217; with the file you wish to allow them to download. It&#8217;s important to note, here, that you should not send any other output to the browser &#8211; as this will mess the headers up. You can run extra PHP bits and bobs (such as logging how many times the image has been downloaded etc&#8230;). I generally put this code into it&#8217;s own file, named something like <strong>download.php</strong> and link to it from a gallery.</p>
<p><strong>Protip!</strong> You can force downloads of any type of file, not just images.</p>
<h2>#2 &#8211; Sorting a Multidimensional Array</h2>
<p>Sorting standard, or singular-dimensional arrays is simple business. If you have an array like so:</p>
<pre name="code" class="php">
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
</pre>
<p>You can use <strong>asort</strong> to sort by the values of the array:</p>
<pre name="code" class="php">
asort($fruits);
</pre>
<p>Which would give you a nicely sorted array like so:</p>
<pre>
c = apple
b = banana
d = lemon
a = orange
</pre>
<p>But what if we had a multi-dimensional array? Let&#8217;s take the following array for this example:</p>
<pre name="code" class="php">
$students[0]['name'] 	= 'Ed Rackham';
$students[0]['age'] 	= 25;

$students[1]['name'] 	= 'Joe Rackham';
$students[1]['age'] 	= 27;

$students[2]['name'] 	= 'Sarah Cockburn';
$students[2]['age'] 	= 25;

$students[3]['name'] 	= 'Luke Newnham';
$students[3]['age'] 	= 25;

$students[4]['name'] 	= 'Mart Dingley';
$students[4]['age'] 	= 28;

$students[5]['name'] 	= 'Skript Kiddie';
$students[5]['age'] 	= 16;
</pre>
<p>If we run a <strong>print_r()</strong> on our $students array, we will get the following:</p>
<pre>
Array
(
    [0] => Array
        (
            [name] => Ed Rackham
            [age] => 25
        )

    [1] => Array
        (
            [name] => Joe Rackham
            [age] => 27
        )

    [2] => Array
        (
            [name] => Sarah Cockburn
            [age] => 25
        )

    [3] => Array
        (
            [name] => Luke Newnham
            [age] => 25
        )

    [4] => Array
        (
            [name] => Mart Dingley
            [age] => 28
        )

    [5] => Array
        (
            [name] => Skript Kiddie
            [age] => 16
        )
)
</pre>
<p>But what if we wanted to sort the array based on the age of the student? Well, we&#8217;d simply use <strong>usort</strong> which allows us to sort an array by values using a custom sorting function &#8211; in this example our custom sorting function is called <strong>customSort</strong>. Firstly, we need to add our custom sorting function, which is really simple &#8211; it looks like the following:</p>
<pre name="code" class="php">
function customSort($a, $b){
	return strcmp($a['age'], $b['age']);
}
</pre>
<p>Which, as you can see returns the result of strcmp based on <strong>array[DIMENSION]</strong> by <strong>array[DIMENSION]</strong>. We want to sort by the &#8216;age&#8217; dimension, so we simply sort by this array dimension. We could use a variable here to make this custom sorting function a little more flexible.</p>
<p>Next, we need to add the <strong>usort()</strong> function after we have declared our array, so we can actually sort it:</p>
<pre name="code" class="php">
usort($students, 'customSort');
</pre>
<p>This takes two parameters, our array we want to sort, and the name of the custom sorting function that we want to use for the sorting. Once we have run this, we can do a <strong>print_r()</strong> on our array and we now get the following:</p>
<pre>
Array
(
    [0] => Array
        (
            [name] => Skript Kiddie
            [age] => 16
        )

    [1] => Array
        (
            [name] => Luke Newnham
            [age] => 25
        )

    [2] => Array
        (
            [name] => Sarah Cockburn
            [age] => 25
        )

    [3] => Array
        (
            [name] => Ed Rackham
            [age] => 25
        )

    [4] => Array
        (
            [name] => Joe Rackham
            [age] => 27
        )

    [5] => Array
        (
            [name] => Mart Dingley
            [age] => 28
        )
)
</pre>
<p>Awesome hey? There&#8217;s so many uses for this, and I&#8217;m sure &#8211; during your PHP careers &#8211; you&#8217;ll find many uses for this bad boy.</p>
<p><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h2>#1 &#8211; Require, Include and _once</h2>
<p>Finally, you probably already use one of the following as you code your PHP scripts:</p>
<ul>
<li>include()</li>
<li>require()</li>
<li>include_once()</li>
<li>require_once()</li>
</ul>
<p>But do you know the difference? The differences are important, so let me explain:</p>
<ul>
<li><strong>include()</strong> will attempt to include the file, but if it fails PHP will just produce a warning, and continue to execute the script (as best it can) regardless. This is safer if you nonchalantly include files regardless of whether they are actually needed / exist.</li>
<li><strong>require()</strong> will attempt to include the file, but fail with a fatal error should it have a problem when trying to get the file. I like this method, as the PHP will stop executing immediately and bug out if the file is not loaded correctly (for whatever reason).</li>
<li><strong>include_once() / require_once()</strong> you should really try to avoid using. The benefits of using the <strong>_once</strong> method is that you know, for sure, that you&#8217;re not including the same file twice. However &#8211; this is much much slower than just writing semantic code and not relying on the fact you might have included the file more than once.</li>
</ul>
<p>Basically, using <strong>require()</strong> is probably the best practise, as it is faster than the <strong>_once</strong> methods, and you should be writing clean, semantic, code these days that don&#8217;t rely on PHP fallbacks such as <strong>include()</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/php/top-10-php-tips-functions-techniques-you-need-to-know/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>AJAX Form Tutorial</title>
		<link>http://edrackham.com/php/ajax-form-tutorial/</link>
		<comments>http://edrackham.com/php/ajax-form-tutorial/#comments</comments>
		<pubDate>Tue, 12 Oct 2010 20:11:49 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[AJAX Form]]></category>

		<guid isPermaLink="false">http://edrackham.com/?p=149</guid>
		<description><![CDATA[This tutorial will show you how to create an AJAX form with PHP and jQuery. The AJAX form doesn&#8217;t look any different to an ordinary HTML form, with the exception of making sure that when we submit the form, it calls a javascript function rather than pushes the user to a page (causing a new [...]]]></description>
			<content:encoded><![CDATA[<p>This tutorial will show you how to create an AJAX form with PHP and jQuery. The AJAX form doesn&#8217;t look any different to an ordinary HTML form, with the exception of making sure that when we submit the form, it calls a javascript function rather than pushes the user to a page (causing a new page reload). I&#8217;ll also demonstrate how we can use &#8216;loading&#8217; animation for the AJAX form, whilst we wait for the server to respond.<span id="more-149"></span><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h2><a target="_blank" href="http://edrackham.com/tutorials/ajax-form-tutorial/">DEMO: HERE</a></h2>
<h2>The AJAX Form</h2>
<pre name="code" class="html">
&lt;form name=&quot;ajaxForm&quot; id=&quot;ajaxForm&quot; method=&quot;post&quot; action=&quot;&quot; onsubmit=&quot;postForm(); return false;&quot;&gt;
	&lt;label for=&quot;yourName&quot;&gt;Your Name&lt;/label&gt;
	&lt;input type=&quot;text&quot; name=&quot;yourName&quot; id=&quot;yourName&quot; /&gt;
	&lt;br /&gt;

	&lt;label for=&quot;yourAge&quot;&gt;Your Age&lt;/label&gt;
	&lt;input type=&quot;text&quot; name=&quot;yourAge&quot; id=&quot;yourAge&quot; /&gt;

	&lt;br /&gt;

	&lt;label for=&quot;submitForm&quot;&gt;&amp;nbsp;&lt;/label&gt;
	&lt;input type=&quot;submit&quot; id=&quot;submitForm&quot; value=&quot;Submit&quot; /&gt;

	&lt;input type=&quot;hidden&quot; name=&quot;formPosted&quot; value=&quot;true&quot; /&gt;
&lt;/form&gt;
</pre>
<p>We&#8217;re using a simple form for this tutorial, but feel free to add any number of form elements you wish. In this example, we have given the form an id of <strong>ajaxForm</strong>, we also have a field for <strong>yourName</strong> and a field for <strong>yourAge</strong>. As explained in my <a href="http://edrackham.com/php/php-login-script-tutorial/">User Login Script</a> tutorial, we also have a hidden field that I like to use to confirm that the page was actually submitted, and which form was the &#8220;sender&#8221;. The most important thing about this form, and to make it work using AJAX, is the following attribute within our opening form tag:</p>
<pre name="code" class="html">
onsubmit=&quot;postForm(); return false;&quot;
</pre>
<p>The <strong>onsubmit</strong> attribute allows us to execute some JavaScript (to eventually run our AJAX!) prior to actually sending the form using it&#8217;s default method (by sending the form data to the page via a complete page reload). We&#8217;re immediately calling <strong>return false;</strong> straight after, this actually prevents the form from sending the data the normal way.</p>
<p>If it helps to understand, here&#8217;s all we&#8217;ve done up to this point:</p>
<ul>
<li>Create a simple HTML form</li>
<li>Add the <strong>onsubmit</strong> attribute to the opening form tag</li>
<li>Made a call to a (currently non-existent) JavaScript function within the <strong>onsubmit</strong> attribute</li>
<li>Returned false after our call to the JavaScript function &#8211; to prevent the form from actually submitting</li>
</ul>
<h2>The AJAX Preloader</h2>
<p>Our form is all dealt with, so now let&#8217;s create a little div, which will show when our form is sending the data, and waiting for some response back. After your form, add the following:</p>
<pre name="code" class="html">
&lt;div id=&quot;loading&quot; style=&quot;display: none;&quot;&gt;
	&lt;img src=&quot;loader.gif&quot; style=&quot;vertical-align: middle;&quot; /&gt; Loading...
&lt;/div&gt;
</pre>
<p>This is a real simple little div, which is hidden by default (using the <strong>style=&#8221;display: none&#8221;</strong> attribute). We&#8217;ve given it an id of <strong>loading</strong>, which is important as we&#8217;ll need to use the jQuery to show / hide this div in a moment. Inside this div I have placed a preloading gif which I created using <a href="http://www.preloaders.net/">http://www.preloaders.net</a>, and a simple bit of text saying &#8216;Loading&#8230;&#8217;. You can put whatever you like within this div really, but I quite like the preloading animated gifs myself.</p>
<h2>The Actual AJAX Function</h2>
<p>Ok, so we&#8217;re diverting the actual onsubmit action of the form to a JavaScript function called <strong>postForm()</strong>. We&#8217;re using jQuery to handle this AJAX form as it&#8217;s a much easier method than manually writing a cross-browser XMLHttpRequest handler. I&#8217;m assuming you know how to include jQuery into your page, but if not &#8211; take a quick peek at my <a href="http://edrackham.com/javascript/how-to-create-a-textarea-character-counter-limiter-using-jquery/">Textarea Counter</a> tutorial, which explains my preferred method for including jQuery libraries.</p>
<p>Right, you have jQuery included? Good, let&#8217;s go and create the <strong>postForm()</strong> function now. It looks like the following:</p>
<pre name="code" class="javascript">
function postForm(){
	$('#loading').show('fast');
	$.post("index.php", $("#ajaxForm").serialize(),
	   function(data){
			$('#loading').hide('fast');
	     alert("Your name is: " + data.name + "\nYour age is: " + data.age);
	   }, "json");
}
</pre>
<p>The first thing we&#8217;re doing is showing the loading div (with our preloader). We do this by calling:</p>
<pre name="code" class="javascript">
$('#loading').show('fast');
</pre>
<p>This does a quick fade-in of our loading div, before we do anything else. This is a good idea, because we want to give the user immediate feedback that something it happening. We could also disable the submit button at this point &#8211; but that&#8217;s not covered in the scope of this tutorial.</p>
<p>Next comes our actual AJAX call which will submit our form. I&#8217;m using $.post() in this tutorial, but you can use $.get() and even $.getJSON().</p>
<ul>
<li>$.post() will simulate a form POST (as if we had our form method set to post)</li>
<li>$.get() will simulate a form GET request (as if we had our form method set to get)</li>
<li>$.getJSON will simulate a GET request as above, but expect the results to be well formatted JSON, and as such return it as JSON data</li>
</ul>
<p>A quick look at the jQuery docs for how the $.post() function should be formatted shows that we can use numerous methods, but for this tutorial we want to set <strong>four main things</strong>.</p>
<p>The page we&#8217;re submitting the form data to. As explained in my <a href="http://edrackham.com/php/php-login-script-tutorial/">User Login Script</a> tutorial, I like to submit the data to the same page, so this is going to be set to <strong>index.php</strong> (and we&#8217;ll get to how we handle the data in a moment!).</p>
<p>Next, we need to tell the AJAX call what data we&#8217;re going to be sending. As we&#8217;re using a well-formatted form (when using AJAX, you won&#8217;t always necessarily be using a form), we&#8217;re going to use a great jQuery function called serialize() which &#8211; in basic terms &#8211; tells our function that we&#8217;re sending all elements within the form that we&#8217;re serializing. We do this by calling <strong>$(&#8220;#ajaxForm&#8221;).serialize()</strong> (essentially, we&#8217;re serializing all the data within the <strong>ajaxForm</strong> &#8211; remember, this is the ID of the form we created earlier).</p>
<p>After that comes our &#8220;success&#8221; function. In other words, a function that gets automatically called once our AJAX call has had a response from the page that we&#8217;re sending the data to. This is taking an automatic parameter which I&#8217;ve called <strong>data</strong>. You can name this parameter anything you like (provided it&#8217;s not a <a href="https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words">reserved JavaScript word</a>), but generally speaking &#8211; <strong>data</strong> is a good enough keyword, as essentially what we&#8217;ll be receiving is <strong>data</strong>.</p>
<p>We&#8217;ll break down that mini-function in a moment.</p>
<p>The fourth and final parameter that we need (for this tutorial anyway) is the &#8220;what data type are you expecting back?&#8221; parameter. I&#8217;ve set this to <strong>json</strong> as I like working with it. What is JSON? Ah, it stands for JavaScript Object Notation. It is a relatively modern, and my preferred method, for handling data within JavaScript. If you&#8217;re used to PHP, think of JSON as a multi-dimensional array. It allows us to handle groups of data as one &#8220;object&#8221; (or variable if you prefer). We generally use dot notation to access it&#8217;s properties. I&#8217;m sure I&#8217;ll explain JSON in greater detail in the future &#8211; but for now here&#8217;s a <a href="http://en.wikipedia.org/wiki/JSON">more-than-generous explanation</a>.</p>
<p>Ok so our four parameters are set:</p>
<ul>
<li>Send Data To This Page</li>
<li>Send This Data To That Page</li>
<li>Run This Function When We Get a Response From That Page</li>
<li>I&#8217;m Expecting The Data To Be Returned Like This</li>
</ul>
<p>Ok so that&#8217;s our four main parameters set for our <strong>$.post()</strong> function. Before we check out the server-side handling of this AJAX call, let&#8217;s just take a quick peek at our success function (which is our third parameter in our AJAX call):</p>
<pre name="code" class="javascript">
function(data){
	$('#loading').hide('fast');
	alert("Your name is: " + data.name + "\nYour age is: " + data.age);
}
</pre>
<p>The first thing we&#8217;re doing is hiding the <strong>loading</strong> div (as our data has now loaded), and then we&#8217;re just doing a simple alert with the data we received. To populate the alert, we&#8217;re just using JSON to retrieve the data using data.<strong>VARIABLE</strong>. In this case, data.<strong>name</strong> and data.<strong>age</strong>.</p>
<p>How do we know we&#8217;re going to have <strong>name</strong> and <strong>age</strong> sent back as our <strong>data</strong> JavaScript Object? That all comes down to the final part &#8211; the server-side handling of our AJAX form, and I think you&#8217;ll be surprised to see just how simple it really is!</p>
<h2>Handling the AJAX Form, Server-Side</h2>
<p>At the very top of our page &#8211; where I like to handle my form posts (on the same page as the form, not on a different page), we have the following code:</p>
<pre name="code" class="php">
&lt;?php
if($_POST['formPosted'] == 'true'){
	$returnData = array(2);
	$returnData['name'] = $_POST['yourName'];
	$returnData['age']	= $_POST['yourAge'];
	echo json_encode($returnData);
	exit;
}
?&gt;
</pre>
<p>That&#8217;s it!</p>
<p>We know that we can handle the form variables using the <strong>$_POST</strong> super global, as we used the <strong>$.post()</strong> function via jQuery. We also know that we&#8217;re sending ALL form elements, because we used the serialize() method, again provided by jQuery. This means that we can access the <strong>yourName</strong> and <strong>yourAge</strong> form elements (note that we&#8217;re also checking that <strong>formPosted</strong> is true before running this block of code &#8211; this was our hidden variable in our form remember?).</p>
<p>We&#8217;re then simply (and very simply for the purposes of this tutorial), creating an array called <strong>$returnData</strong>, and adding the value of <strong>yourName</strong> to <strong>$returnData['name']</strong>, and <strong>yourAge</strong> to <strong>$returnData['age']</strong>. Notice something here? The PHP array we have just created now has two elements, <strong>name</strong> and <strong>age</strong>.</p>
<p>All we need to do now is to encode our array as JSON, and echo it out, which we do in one line:</p>
<pre name="code" class="php">
echo json_encode($returnData);
</pre>
<p>Then <strong>most importantly</strong>, we exit. We MUST exit here, otherwise the remainder of the page would continue to load, and also be sent back to our JavaScript function which is waiting for the data. ALWAYS exit once you have dealt with an AJAX call. The point is to provide the data requested and that&#8217;s it. If we sent it all back, it would malform the JSON we&#8217;re echoing out, and as such, break our functionality. Not to mention it&#8217;d also be completely pointless, as we&#8217;re loading the entire page again!</p>
<p>So there you have it! Any questions, comments or criticism &#8211; please post in the comments, and don&#8217;t forget that there&#8217;s a:</p>
<h2><a target="_blank" href="http://edrackham.com/tutorials/ajax-form-tutorial/">DEMO: HERE</a></h2>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/php/ajax-form-tutorial/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PHP Login Script Tutorial</title>
		<link>http://edrackham.com/php/php-login-script-tutorial/</link>
		<comments>http://edrackham.com/php/php-login-script-tutorial/#comments</comments>
		<pubDate>Wed, 06 Oct 2010 21:04:34 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Membership]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Sessions]]></category>
		<category><![CDATA[User Authentication]]></category>

		<guid isPermaLink="false">http://edrackham.com/?p=100</guid>
		<description><![CDATA[This PHP login script / tutorial will show you how you can have users register on your site, and log in to access secure areas. I have seen a few tutorials around the web which show how this can be done, but they all seem to lack in security. This user membership tutorial will show [...]]]></description>
			<content:encoded><![CDATA[<p>This PHP login script / tutorial will show you how you can have users register on your site, and log in to access secure areas. I have seen a few tutorials around the web which show how this can be done, but they all seem to lack in security. This user membership tutorial will show a better way of having users authenticated once logged in by using their session ID.<span id="more-100"></span><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h2><a href="http://edrackham.com/tutorials/user-membership-with-php-mysql/" target="_blank">DEMO: HERE</a></h2>
<h2>The Table</h2>
<p>Firstly, we need to create a table to store our users. I&#8217;m using phpMyAdmin to administer my database, so setting up the table is pretty easy for me. You can use the following SQL statement to create your `users` table, using whichever method you prefer:</p>
<pre name="code" class="php">
CREATE TABLE `users` (
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `email` VARCHAR( 255 ) NOT NULL ,
    `password` VARCHAR( 32 ) NOT NULL ,
    `session_id` VARCHAR( 32 ) NULL ,
    `date_registered` DATETIME NOT NULL ,
    UNIQUE (`email`)
) ENGINE = MYISAM ;
</pre>
<p>A few things to note here:</p>
<ul>
<li>We&#8217;re going to be hashing the passwords (using MD5), so we know that the password field will be exactly 32 characters in length</li>
<li>For extra security, we&#8217;re going to re-authenticate users across pages using their session ID, so we &#8211; again &#8211; need a field which is exactly 32 characters</li>
<li>We&#8217;re making the email field unique. This isn&#8217;t completely necessary, as we&#8217;ll be checking for duplicate email addresses within the register form, but it&#8217;s just an extra &#8220;lock on the door&#8221; so to speak. So if anything failed within the PHP code, the database would still fail on the insert.</li>
</ul>
<p>&nbsp;</p>
<p><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h2>The main config file</h2>
<p>It makes sense to have an include which will set up a few things for us on every page we want to secure. This file should have the <strong>session_start()</strong> function call in it &#8211; because without this, we wouldn&#8217;t be able to use sessions at all! We also need to establish a database connection, and finally, check for an authenticated user.</p>
<p>Create a new file called <strong>config.php</strong> and paste the following code into it:</p>
<pre name="code" class="php">
// Start the session (pretty important!)
session_start();

// Establish a link to the database
$dbLink = mysql_connect('YOUR HOSTNAME', 'YOUR USERNAME', 'YOUR PASSWORD');
if (!$dbLink) die('Can\'t establish a connection to the database: ' . mysql_error());

$dbSelected = mysql_select_db('YOUR DATABASE', $dbLink);
if (!$dbSelected) die ('We\'re connected, but can\'t use the table: ' . mysql_error());

// Run a quick check to see if we are an authenticated user or not
// First, we set a 'is the user logged in' flag to false by default.
$isUserLoggedIn = false;
$query 		= 'SELECT * FROM users WHERE session_id = "' . session_id() . '" LIMIT 1';
$userResult 	= mysql_query($query);
if(mysql_num_rows($userResult) == 1){
	$_SESSION['user'] = mysql_fetch_assoc($userResult);
	$isUserLoggedIn = true;
}else{
	if(basename($_SERVER['PHP_SELF']) != 'login.php'){
		header('Location: login.php');
		exit;
	}
}
</pre>
<p>Ok, so firstly we&#8217;re calling <strong>session_start()</strong>. This is an extremely important function to call if you want to use server-side session variables. This function should ALWAYS be called before any output has been sent to the browser &#8211; even newlines. It&#8217;s generally a good idea to just call session_start() at the very top of your code, on every page. Why are we using session variables anyway? Well, it&#8217;s much easier to handle arrays of data across pages if we do this. In this example, we will be storing the user&#8217;s details (such as name, email address etc&#8230;) within a session variable array, so we can access it on any number of secure pages we have.</p>
<p>Lines 5 to 9 are simply establishing a connection to our database. I&#8217;m not going to go into too much detail on how you use PHP to connect to a database, but you do need to replace the following four items within these lines:</p>
<ul>
<li><strong>YOUR HOSTNAME</strong> &#8211; This is generally <strong>localhost</strong>, but can be another named, or IP of a remote host where your database resides.</li>
<li><strong>YOUR USERNAME</strong> &#8211; Replace this with your username for accessing your database.</li>
<li><strong>YOUR PASSWORD</strong> &#8211; Replace this with your password for accessing your database.</li>
<li><strong>YOUR DATABASE</strong> &#8211; Replace this with the name of your database you want to access.</li>
</ul>
<p>&nbsp;</p>
<p><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h2>The Auto-Authentication</h2>
<p>Within the config.php file, I think it&#8217;d be a good idea to automatically authenticate the user. This means that every time a page is loaded (with our config.php file in the header) we&#8217;ll be doing a quick check to see if they&#8217;re authenticated, and if they are &#8211; we&#8217;ll set a boolean flag to indicate this, and a session based array full of their information.</p>
<p>Line 13 sets the boolean flag <strong>$isUserLoggedIn</strong> to false by default. Line 14 sets up a query to get any user who has the session id set to <strong>session_id()</strong>. <strong>session_id()</strong> is a PHP function which returns a 32 character length string with the user&#8217;s current session variable. This is a unique string that PHP will generate for every user on your site. This will timeout (change to a new session ID) based on the PHP ini setting <strong>session.gc_maxlifetime</strong>. Generally, you won&#8217;t need to change this timeout limit, but if you need to, you should be able to add the following to the top of the config file (just under session_start() should do fine):</p>
<pre name="code" class="php">
ini_set(’session.gc_maxlifetime’, 60*60);
</pre>
<p>Which will set the timeout to one hour &#8211; 60 seconds multiplied by 60. You can make this even bigger if you like, but it&#8217;s a good idea to keep your timeouts down to around 30mins, so if a registered &#8211; and logged in &#8211; user leaves their computer for over 30mins, someone else won&#8217;t be able to use the secure area (as the session would have timed out).</p>
<p>Line 15 simply executes the query, and stores the return result of the query in <strong>$userResult</strong>.</p>
<p>Line 16 checks to see if we have a result returned. If we do, it means that we have found a user in our users table, with a session ID which exactly matches the result of session_id(). Therefore, it&#8217;s safe to say that the user is an already-logged-in user, and as such, we can authenticate them.</p>
<p>We do this on lines 17 and 18 by setting a session variable array <strong>$_SESSION['user']</strong> to the array of data that we get back when we fetch the row of data, and then setting the <strong>$isUserLoggedIn</strong> flag to true.</p>
<p>The remaining lines in our config.php file are there so that we can handle what happens to a non-authenticated user. If no logged-in-user is found, we check to see what page we&#8217;re currently on. If we&#8217;re not on our login.php page, we redirect the user to our login.php page. We need to check that we&#8217;re not on the login page before doing the redirect, otherwise we&#8217;d end up putting the user in an infinite loop. For example, regardless of what page you&#8217;re on (including the login.php page), we&#8217;d ALWAYS be redirecting the user to the login.php page. Just under that we&#8217;re calling <strong>exit;</strong>. This should always be called after doing a <strong>header(&#8216;Location: &#8230;&#8217;);</strong> call, as the page <em>can</em> still continue to render after the header has been executed, causing all sorts of problems.</p>
<h2>The Login &#038; Register Page</h2>
<p>Yep &#8211; we&#8217;re clever, so we&#8217;re going to have the login and register functionality / forms on the same page!</p>
<p>Create a new file called <strong>login.php</strong> and copy the following code into it:</p>
<pre name="code" class="php">
&lt;?php
include_once('config.php');

// Reset errors and success messages
$errors = array();
$success = array();

// Login attempt
if(isset($_POST['loginSubmit']) &amp;&amp; $_POST['loginSubmit'] == 'true'){
	$loginEmail = trim($_POST['email']);
	$loginPassword 	= trim($_POST['password']);

	if (!eregi(&quot;^[_a-z0-9-] (.[_a-z0-9-] )*@[a-z0-9-] (.[a-z0-9-] )*(.[a-z]{2,3})$&quot;, $loginEmail))
		$errors['loginEmail'] = 'Your email address is invalid.';

	if(strlen($loginPassword) &lt; 6 || strlen($loginPassword) &gt; 12)
		$errors['loginPassword'] = 'Your password must be between 6-12 characters.';

	if(!$errors){
		$query 	= 'SELECT * FROM users WHERE email = &quot;' . mysql_real_escape_string($loginEmail) . '&quot; AND password = MD5(&quot;' . $loginPassword . '&quot;) LIMIT 1';
		$result = mysql_query($query);
		if(mysql_num_rows($result) == 1){
			$user = mysql_fetch_assoc($result);
			$query = 'UPDATE users SET session_id = &quot;' . session_id() . '&quot; WHERE id = ' . $user['id'] . ' LIMIT 1';
			mysql_query($query);
			header('Location: index.php');
			exit;
		}else{
			$errors['login'] = 'No user was found with the details provided.';
		}
	}
}

// Register attempt
if(isset($_POST['registerSubmit']) &amp;&amp; $_POST['registerSubmit'] == 'true'){
	$registerEmail = trim($_POST['email']);
	$registerPassword = trim($_POST['password']);
	$registerConfirmPassword 	= trim($_POST['confirmPassword']);

	if (!eregi(&quot;^[_a-z0-9-] (.[_a-z0-9-] )*@[a-z0-9-] (.[a-z0-9-] )*(.[a-z]{2,3})$&quot;, $registerEmail))
		$errors['registerEmail'] = 'Your email address is invalid.';

	if(strlen($registerPassword) &lt; 6 || strlen($registerPassword) &gt; 12)
		$errors['registerPassword'] = 'Your password must be between 6-12 characters.';

	if($registerPassword != $registerConfirmPassword)
		$errors['registerConfirmPassword'] = 'Your passwords did not match.';

	// Check to see if we have a user registered with this email address already
	$query = 'SELECT * FROM users WHERE email = &quot;' . mysql_real_escape_string($registerEmail) . '&quot; LIMIT 1';
	$result = mysql_query($query);
	if(mysql_num_rows($result) == 1)
		$errors['registerEmail'] = 'This email address already exists.';

	if(!$errors){
		$query = 'INSERT INTO users SET email = &quot;' . mysql_real_escape_string($registerEmail) . '&quot;,
																		password = MD5(&quot;' . mysql_real_escape_string($registerPassword) . '&quot;),
																		date_registered = &quot;' . date('Y-m-d H:i:s') . '&quot;';

		if(mysql_query($query)){
			$success['register'] = 'Thank you for registering. You can now log in on the left.';
		}else{
			$errors['register'] = 'There was a problem registering you. Please check your details and try again.';
		}
	}

}
?&gt;
&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;meta charset=&quot;utf-8&quot;/&gt;
  &lt;title&gt;Login to the secure area&lt;/title&gt;
  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width; initial-scale=1.0; maximum-scale=1.0;&quot;/&gt;
  &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;default.css&quot;/&gt;
&lt;/head&gt;

&lt;body&gt;
  &lt;header&gt;&lt;h1&gt;Login / Register Here&lt;/h1&gt;&lt;/header&gt;

	&lt;form class=&quot;box400&quot; name=&quot;loginForm&quot; action=&quot;&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;&quot; method=&quot;post&quot;&gt;
		&lt;h2&gt;Login&lt;/h2&gt;
		&lt;?php if($errors['login']) print '&lt;div class=&quot;invalid&quot;&gt;' . $errors['login'] . '&lt;/div&gt;'; ?&gt;

		&lt;label for=&quot;email&quot;&gt;Email Address&lt;/label&gt;
		&lt;input type=&quot;text&quot; name=&quot;email&quot; value=&quot;&lt;?php echo htmlspecialchars($loginEmail); ?&gt;&quot; /&gt;
		&lt;?php if($errors['loginEmail']) print '&lt;div class=&quot;invalid&quot;&gt;' . $errors['loginEmail'] . '&lt;/div&gt;'; ?&gt;

		&lt;label for=&quot;password&quot;&gt;Password &lt;span class=&quot;info&quot;&gt;6-12 chars&lt;/span&gt;&lt;/label&gt;
		&lt;input type=&quot;password&quot; name=&quot;password&quot; value=&quot;&quot; /&gt;
		&lt;?php if($errors['loginPassword']) print '&lt;div class=&quot;invalid&quot;&gt;' . $errors['loginPassword'] . '&lt;/div&gt;'; ?&gt;

		&lt;label for=&quot;loginSubmit&quot;&gt;&amp;nbsp;&lt;/label&gt;
		&lt;input type=&quot;hidden&quot; name=&quot;loginSubmit&quot; id=&quot;loginSubmit&quot; value=&quot;true&quot; /&gt;
		&lt;input type=&quot;submit&quot; value=&quot;Login&quot; /&gt;
	&lt;/form&gt;

	&lt;form class=&quot;box400&quot; name=&quot;registerForm&quot; action=&quot;&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;&quot; method=&quot;post&quot;&gt;
		&lt;h2&gt;Register&lt;/h2&gt;
		&lt;?php if($success['register']) print '&lt;div class=&quot;valid&quot;&gt;' . $success['register'] . '&lt;/div&gt;'; ?&gt;
		&lt;?php if($errors['register']) print '&lt;div class=&quot;invalid&quot;&gt;' . $errors['register'] . '&lt;/div&gt;'; ?&gt;

		&lt;label for=&quot;email&quot;&gt;Email Address&lt;/label&gt;
		&lt;input type=&quot;text&quot; name=&quot;email&quot; value=&quot;&lt;?php echo htmlspecialchars($registerEmail); ?&gt;&quot; /&gt;
		&lt;?php if($errors['registerEmail']) print '&lt;div class=&quot;invalid&quot;&gt;' . $errors['registerEmail'] . '&lt;/div&gt;'; ?&gt;

		&lt;label for=&quot;password&quot;&gt;Password&lt;/label&gt;
		&lt;input type=&quot;password&quot; name=&quot;password&quot; value=&quot;&quot; /&gt;
		&lt;?php if($errors['registerPassword']) print '&lt;div class=&quot;invalid&quot;&gt;' . $errors['registerPassword'] . '&lt;/div&gt;'; ?&gt;

		&lt;label for=&quot;confirmPassword&quot;&gt;Confirm Password&lt;/label&gt;
		&lt;input type=&quot;password&quot; name=&quot;confirmPassword&quot; value=&quot;&quot; /&gt;
		&lt;?php if($errors['registerConfirmPassword']) print '&lt;div class=&quot;invalid&quot;&gt;' . $errors['registerConfirmPassword'] . '&lt;/div&gt;'; ?&gt;

		&lt;label for=&quot;registerSubmit&quot;&gt;&amp;nbsp;&lt;/label&gt;
		&lt;input type=&quot;hidden&quot; name=&quot;registerSubmit&quot; id=&quot;registerSubmit&quot; value=&quot;true&quot; /&gt;
		&lt;input type=&quot;submit&quot; value=&quot;Register&quot; /&gt;
	&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>It&#8217;s not as scary as it looks. Lines 1 to 66 contain the main PHP functionality for the page, whereas the rest is simple HTML markup with a few little extras for validation (which, again, many other similar tutorials don&#8217;t cover!).</p>
<p>We start by including our config.php file which we&#8217;ve just created. We&#8217;re assuming that the file is in the same directory as this login.php file. This can be changed easily, but just remember to either update your paths to your config file, or set a globally accessible variable to build the paths dynamically.</p>
<p>Because we have included that config.php file, we can already assume the following:</p>
<ul>
<li>We have declared <strong>session_start()</strong>, so we don&#8217;t need to re-declare that at all.</li>
<li>We have a valid database connection</li>
<li>We have run a check for a valid, logged-in user</li>
</ul>
<p>&nbsp;</p>
<p>We&#8217;re then declaring two empty arrays to hold errors and success messages. This will be used for validating the form, and notifying the user that they have successfully registered.</p>
<p>Next, we have two main if statements. One for the login attempt, and one for the register attempt. Both of which are looking for a hidden form variable to be set, with a value of &#8216;true&#8217;. I do this, as it&#8217;s my preferred method for checking for a form post, but feel free to use whatever method of checking for a form submission you prefer. The way this setup works is that on a standard page load (i.e. without a form submission) neither of the if statements will return true, as no form data would have been sent to it &#8211; but if we submit one of the forms, it will post back to itself and be dealt with accordingly. I like this method, as it allows me to keep functionality specific to a certain page, contained within that page.<br />
<div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h3>The Login Attempt If Block</h3>
<p>We&#8217;re firstly cleaning the posted variables, by <strong>trim()</strong>-ing them. This removes whitespace from the left and right side of the variable. This also gets around people just posting empty form elements, or form elements which have only spaces in them.</p>
<p>This is also setting a variable that we&#8217;ll use further down the page when we get to the form. How many times have you filled out a form on the web, only to have it not validate and then be faced with the same form &#8211; but completely blank! We&#8217;re going to use the <strong>$loginEmail</strong> variable on the <strong>loginEmail</strong> form element as the value, so if they mistype something, at least they won&#8217;t have to write their email address again (provided they typed it right the first time). It&#8217;s more of a proof-of-concept thing, rather than a MUST-DO for this tutorial.</p>
<p>After those two lines comes the validation. We&#8217;re using a regular expression to validate the email address, and simply checking the string length of the password to ensure it falls between 6 and 12 characters. If either fail, the <strong>$error</strong> array will be populated with the appropriate error messages, which will be used further down the page when we get to the actual form.</p>
<p>Following that, we have another if statement checking to see if we <strong>don&#8217;t</strong> have any errors. If we don&#8217;t, we then look on the database for a user with the email address provided, and the password &#8211; which is MD5 hashed using the <strong>MD5()</strong> MySQL function. If we get a result (in other words, there is a user with the email address and password provided), we update that row for the user so that their session_id field in our database gets the value of the PHP provided session_id().</p>
<p>We then simply push them to our landing page for authenticated users &#8211; in this example, it&#8217;s index.php. As we&#8217;ll be including the config.php file across all secure pages, we know we don&#8217;t need to worry about anything else, because our config.php file does a user authentication check every page anyway <img src='http://edrackham.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<h3>The Register Attempt If Block</h3>
<p>Very similar to the login attempt if block, but within this, we have a <strong>confirmPassword</strong> form element that we need to make sure matches the password form element, and lines 50 to 53 are also checking that the email address doesn&#8217;t exist within the database. We don&#8217;t want two people registering under the same email address!</p>
<p>Provided we have no errors, we insert a new record for the user into our users table, setting the email address, password (using MD5), and date registered. If the query succeeds when we execute it (on line 60), we can set a success message which will be displayed below, otherwise we set an error message.</p>
<h3>The Forms</h3>
<p>I&#8217;m not going to go into too much detail regarding the markup of the actual HTML page, but I will say that it is using HTML5 (for those unfamiliar), and there is a stylesheet included to aid the layout of the forms / labels. Feel free to create your own, or take mine from the <a href="http://edrackham.com/tutorials/user-membership-with-php-mysql/">actual tutorial itself</a>.</p>
<p>The forms themselves (<strong>loginForm</strong> and <strong>registerForm</strong>) should be self explanatory, but you just need to note the following:</p>
<ul>
<li>Both forms have their action set to <strong>$_SERVER['PHP_SELF']</strong>. This makes sure that the form posts the submitted data to the same page (which will be dealt with accordingly as in our main PHP block at the top of the page.</li>
<li>Within the forms I am checking for the existence of error or success array variables, such as <strong>$errors['loginEmail']</strong>, and if they exist, I&#8217;m outputting the error message wrapped in a div with appropriate styling.</li>
<li>The login form has a hidden form element called <strong>loginSubmit</strong>, whereas the register form has a hidden form variable called <strong>registerSubmit</strong>. They are both set to &#8216;<strong>true</strong>&#8216;. This is so we can identify which form was submitted when we post the data to the page. <em>There are other ways of doing this, but I find this the cleanest for this tutorial.</em></li>
<li>The register form has an extra field called <strong>confirmPassword</strong>, which is used to check that the user has entered their password correctly when they register.</li>
</ul>
<p>And that is all we need for our login / register page.</p>
<h2>The Secure Page(s)</h2>
<p><em>Almost</em> finally, we need to create a secure page to demonstrate this authentication / user membership is working.</p>
<p>Create a new file called <strong>index.php</strong> and copy in the following code:</p>
<pre name="code" class="php">
&lt;?php
include_once('config.php');
?&gt;
&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;meta charset=&quot;utf-8&quot;/&gt;
  &lt;title&gt;Welcome to the secure area&lt;/title&gt;
  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width; initial-scale=1.0; maximum-scale=1.0;&quot;/&gt;
  &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;default.css&quot;/&gt;
&lt;/head&gt;

&lt;body&gt;
  &lt;header&gt;&lt;h1&gt;Secure Area&lt;/h1&gt;&lt;/header&gt;

	&lt;p&gt;This is one (of many potential) pages that reside in the secure area. All you need to remember to do is to include the &lt;strong&gt;config.php&lt;/strong&gt; file, which handles the user authentication every time.&lt;/p&gt;

	&lt;p&gt;Your user details are as follows:&lt;/p&gt;
	&lt;ul&gt;
		&lt;?php foreach($_SESSION['user'] as $key =&gt; $value){ ?&gt;
			&lt;li&gt;&lt;?php echo $key; ?&gt; &lt;strong&gt;&lt;?php echo $value; ?&gt;&lt;/strong&gt;&lt;/li&gt;
		&lt;?php } ?&gt;
	&lt;/ul&gt;

	&lt;footer&gt;
		&lt;a href=&quot;logout.php&quot;&gt;Logout&lt;/a&gt;
	&lt;/footer&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The magic here, is that we don&#8217;t need to to much at all! As you can see, we don&#8217;t need to do anything but include the <strong>config.php</strong> file. You can create as many secure pages as you like, but just remember to have the config file included at the top of your pages. This page will always ensure that your customers are logged in and authenticated at all times, and if they&#8217;re not &#8211; they&#8217;ll be pushed right back to the login.php page.</p>
<h2>Logging a User Out</h2>
<p>The final part of this tutorial is showing how we log a user out securely.</p>
<p>Create a new file called <strong>login.php</strong> and add the following code:</p>
<pre name="code" class="php">
include_once('config.php');
$query = 'UPDATE users SET session_id = NULL WHERE id = ' . $_SESSION['user']['id'] . ' LIMIT 1';
mysql_query($query);
unset($_SESSION['user']);
header('Location: login.php');
exit;
</pre>
<p>Very simple. We&#8217;re simply updating the users table to set the currently logged in user&#8217;s session ID (as stored in the database) to NULL, unsetting the $_SESSION['user'] variable, then pushing them to the login.php page.</p>
<p>This concludes my simple &#8211; but secure &#8211; user membership / authentication tutorial using PHP and MySQL. You should have learned how to securely authenticate a user, track their authentication across multiple pages, and securely log them out. If you have any questions at all, please post them in the comments and I&#8217;ll do my best to answer them for you.</p>
<p>Don&#8217;t forget, there is a&#8230;</p>
<h2><a href="http://edrackham.com/tutorials/user-membership-with-php-mysql/" target="_blank">DEMO: HERE</a></h2>
<p><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/php/php-login-script-tutorial/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>How to Convert PHP Multidimensional Array to Javascript Object (using jQuery)</title>
		<link>http://edrackham.com/php/how-to-convert-php-multidimensional-array-to-javascript-object-using-jquery/</link>
		<comments>http://edrackham.com/php/how-to-convert-php-multidimensional-array-to-javascript-object-using-jquery/#comments</comments>
		<pubDate>Wed, 29 Sep 2010 20:50:17 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Javascript Object]]></category>
		<category><![CDATA[Parsing JSON]]></category>
		<category><![CDATA[PHP Arrays]]></category>

		<guid isPermaLink="false">http://edrackham.com/?p=77</guid>
		<description><![CDATA[I was working on a project today, and I needed to convert a PHP based multidimensional array into a Javascript array, so that I could use it for a dynamic select dropdown (depending on the top level category chosen, the next level select dropdown would be populated with the child elements of the top level [...]]]></description>
			<content:encoded><![CDATA[<p>I was working on a project today, and I needed to convert a PHP based multidimensional array into a Javascript array, so that I could use it for a dynamic select dropdown (depending on the top level category chosen, the next level select dropdown would be populated with the child elements of the top level category options &#8211; if you follow me!).</p>
<p>Anyway, I soon realised that converting the PHP array into a Javascript <em><strong>array</strong></em> was a bad idea, as converting it to a Javascript <em><strong>object</strong></em> would be much much better.<br />
<span id="more-77"></span><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<p>To convert a PHP array (single dimensional, or multidimensional) you simply need to <strong>double</strong> JSON encode the array. This tutorial relies on jQuery to parse the JSON (using $.parseJSON()), but this isn&#8217;t at all necessary &#8211; there are other methods to parse JSON. Let&#8217;s use the following PHP array as our example:</p>
<pre name="code" class="php">
$aCoders = array();
$aCoders['Ed']['age'] = 25;
$aCoders['Ed']['languages'] = array('PHP', 'MySQL', 'JavaScript', 'Objective-C', 'HTML', 'CSS');
$aCoders['Sarah']['age'] = 25;
$aCoders['Sarah']['languages'] = array('HTML', 'CSS');
</pre>
<p>Now we want to use that object with JavaScript. Rather than firing off an AJAX request to get the results we want, seeing as the array is fairly small, we may as well render it in the browser when the page loads &#8211; to save on bandwidth and unnecessary requests to the server. To make this array become accessible in Javascript (using jQuery), use the following:</p>
<pre name="code" class="javascript">
var coders = $.parseJSON(&lt;?php print json_encode(json_encode($aCoders)); ?&gt;);
</pre>
<p>Yep &#8211; you need to <strong>double encode</strong> the array. This is the key that took me a while to figure out. It adds extra slashes each time you encode, therefore making it render-able in Javascript the second time you encode it.</p>
<p>You can now access your array data using methods similar to the following:</p>
<pre name="code" class="javascript">
for(var language in coders.Ed.languages){
  alert('Ed can code in ' + language);
}
</pre>
<p>Note that javascript objects use dot notation to access the data. If you have a numeric key within your PHP array, you must access it via Javascript using square brackets. For example:</p>
<pre name="code" class="javascript">
alert(object[5].name);
</pre>
<p>I hope this helps you to better understand how to translate PHP arrays into Javascript objects, and realise when it&#8217;s a good idea to use them, and when it&#8217;s still a good idea to just grab what you need by means of an AJAX request.</p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/php/how-to-convert-php-multidimensional-array-to-javascript-object-using-jquery/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>PHP Class Tutorial – Part 3 – What Are Class Constructors?</title>
		<link>http://edrackham.com/php/php-class-tutorial-part-3-what-are-class-constructors/</link>
		<comments>http://edrackham.com/php/php-class-tutorial-part-3-what-are-class-constructors/#comments</comments>
		<pubDate>Tue, 28 Sep 2010 20:39:05 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[beginner PHP classes tutorial]]></category>
		<category><![CDATA[Class Constructors]]></category>
		<category><![CDATA[classes]]></category>

		<guid isPermaLink="false">http://edrackham.com/?p=58</guid>
		<description><![CDATA[So just what are class constructors, and how can they be used within PHP classes / OOP programming? When a PHP class is first called, the class will automatically run the class constructor function, which can help automatically configure the class. This can be useful if you need to preset some instance variables, sessions or [...]]]></description>
			<content:encoded><![CDATA[<p>So just what are class constructors, and how can they be used within PHP classes / OOP programming? When a PHP class is first called, the class will automatically run the class constructor function, which can help automatically configure the class. This can be useful if you need to preset some instance variables, sessions or cookies &#8211; prior to using the class methods.<br />
<span id="more-58"></span><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h3>PHP Class Tutorial Chapters</h3>
<p><a href="http://edrackham.com/php/php-class-tutorial/" title="PHP Class Tutorial - Part 1">Part 1 &#8211; Jumping In With Two Feet</a><br />
<a href="http://edrackham.com/php/php-class-tutorial-part-2-what-is-this/" title="PHP Class Tutorial - Part 2">Part 2 – What is $this-></a><br />
<strong>Part 3 – What Are Class Constructors?</strong></p>
<h2>Starting Point</h2>
<p>Let&#8217;s follow on from the previous tutorials, so we are using the following code as our starting point for this tutorial. If you don&#8217;t want/need to read the previous tutorials, please use the following code as the example for this tutorial.</p>
<pre name="code" class="php">class Time {

  var $sTime;

  function GenerateCurrentTime(){
    $this->sTime = gmdate("d-m-Y H:i:s");
  }

  function ShowFutureDate($iAddDays=0){
    $this->sTime = gmdate("d-m-Y H:i:s", strtotime("+" . $iAddDays . " days"));
  }
}</pre>
<h2>Let&#8217;s __construct()</h2>
<p>Again, to keep things simple, I&#8217;ll show a simple implementation of how using class constructors in PHP can help to build more efficient classes. Let&#8217;s assume that we want to create a new instance of our Time class, but set a default date without having to run any class methods.</p>
<p>How would we do this? Well we have an instance variable <strong>$sTime</strong> that we could manipulate off the bat. If we add the following (and I usually add constructors to the top of the class file, just after the instance variables have been declared &#8211; for readability &#8211; nothing else):</p>
<pre name="code" class="php">
  function __construct(){
    $this->GenerateCurrentTime();
  }
</pre>
<p>(<strong>NOTE:</strong> We&#8217;re adding this just after the <strong>var $sTime;</strong> line). Then as soon as we declare a new Time class, using:</p>
<pre name="code" class="php">
$oTime = new Time();
</pre>
<p>The class method <strong>GenerateCurrentTime()</strong> would be executed immediately. This means that we can instantly get a meaningful result from our instance variable, <strong>$sTime</strong>. So if we were to run the following:</p>
<pre name="code" class="php">
$oTime = new Time();
echo $oTime->sTime;
</pre>
<p>We&#8217;d see the current time displayed on the page &#8211; without having to <em>manually</em> run any class methods. This example is basically a shorthand way of doing:</p>
<pre name="code" class="php">
$oTime = new Time();
$oTime->GenerateCurrentTime();
echo $oTime->sTime;
</pre>
<p>So you can see how we&#8217;re cutting corners already!<div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h2>Can You Pass Parameters to Class Constructors?</h2>
<p>You certainly can my friends! Let&#8217;s say we wanted to preset the date when we first declare the class. This might not seem that useful right now, but down the line we could use the <em><strong>preset date</strong></em> and perform certain calculations on it, such as getting the days between the preset date and the current date. For the purposes of this tutorial, I&#8217;ll demonstrate how we can set an optional preset date. If we don&#8217;t set a preset date &#8211; the date will be set to the current date. Following me? Good! <img src='http://edrackham.com/wp-includes/images/smilies/icon_razz.gif' alt=':-P' class='wp-smiley' /> &#8230;</p>
<p>Let&#8217;s modify our __constructor() class to the following:</p>
<pre name="code" class="php">
  function __construct($sPresetDate = false){
    if($sPresetDate){
      $this->sTime = $sPresetDate;
    }else{
      $this->GenerateCurrentTime();
    }
  }
</pre>
<p>Now, we can declare our class in one of two ways:</p>
<pre name="code" class="php">
$oTime = new Time(date('Y-m-d H:i:s'));
echo $oTime->sTime;
</pre>
<p>Or&#8230;</p>
<pre name="code" class="php">
$oTime = new Time();
echo $oTime->sTime;
</pre>
<p>Both would return the same date and time (if executed at the same time for you pedantic people!) but it demonstrates how you can pass parameters to class constructors.</p>
<h2>Complete Code</h2>
<p>Out complete, with the class constructor would now look like the following:</p>
<pre name="code" class="php">class Time {

  var $sTime;

  function __construct($sPresetDate = false){
    if($sPresetDate){
      $this->sTime = $sPresetDate;
    }else{
      $this->GenerateCurrentTime();
    }
  }

  function GenerateCurrentTime(){
    $this->sTime = gmdate("d-m-Y H:i:s");
  }

  function ShowFutureDate($iAddDays=0){
    $this->sTime = gmdate("d-m-Y H:i:s", strtotime("+" . $iAddDays . " days"));
  }
}</pre>
<p>Nice! It looks like our class is coming along well. We&#8217;ve now covered the basics, what $this-> means and what class constructors are.</p>
<h3>PHP Class Tutorial Chapters</h3>
<p><a href="http://edrackham.com/php/php-class-tutorial/" title="PHP Class Tutorial - Part 1">Part 1 &#8211; Jumping In With Two Feet</a><br />
<a href="http://edrackham.com/php/php-class-tutorial-part-2-what-is-this/" title="PHP Class Tutorial - Part 2">Part 2 – What is $this-></a><br />
<strong>Part 3 – What Are Class Constructors?</strong><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/php/php-class-tutorial-part-3-what-are-class-constructors/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>PHP Class Tutorial &#8211; Part 2 &#8211; What is $this-&gt;</title>
		<link>http://edrackham.com/php/php-class-tutorial-part-2-what-is-this/</link>
		<comments>http://edrackham.com/php/php-class-tutorial-part-2-what-is-this/#comments</comments>
		<pubDate>Wed, 18 Aug 2010 18:44:47 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[OOP]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[$this->]]></category>
		<category><![CDATA[Class]]></category>
		<category><![CDATA[instance variables]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://edrackham.com/php/php-class-tutorial-part-2-what-is-this/</guid>
		<description><![CDATA[Please make sure you&#8217;ve followed my first PHP Class Tutorial before starting this one, as it follows on using the previous example. This tutorial will explain what $this-> is all about, and how to further your PHP class knowledge! PHP Class Tutorial Chapters Part 1 &#8211; Jumping In With Two Feet Part 2 &#8211; What [...]]]></description>
			<content:encoded><![CDATA[<p>Please make sure you&#8217;ve followed my <a href="http://edrackham.com/php/php-class-tutorial/">first PHP Class Tutorial</a> before starting this one, as it follows on using the <a href="http://edrackham.com/php/php-class-tutorial/">previous example</a>. This tutorial will explain what $this-> is all about, and how to further your PHP class knowledge!</p>
<p><span id="more-28"></span></p>
<h3>PHP Class Tutorial Chapters</h3>
<p><a href="http://edrackham.com/php/php-class-tutorial/" title="PHP Class Tutorial - Part 1">Part 1 &#8211; Jumping In With Two Feet</a><br />
<strong>Part 2 &#8211; What does $this-> mean in a PHP class file?</strong><br />
<a href="http://edrackham.com/php/php-class-tutorial-part-3-what-are-class-constructors/" title="PHP Class Tutorial - Part 3">Part 3 &#8211; What Are Class Constructors?</a></p>
<h1>I&#8217;m ready to go, set me up!</h1>
<p>Our first example used the following &#8211; very simple &#8211; class file:</p>
<pre name="code" class="php">
class Time {
  function GenerateCurrentTime(){
    $sTime = gmdate("d-m-Y H:i:s");
    return $sTime;
  }
}
</pre>
<p>Now, let&#8217;s add in the ability for our class file to look <strong>X</strong> number of days into the future shall we? Add in a new function to the class file that looks like:</p>
<pre name="code" class="php">  function ShowFutureDate($iAddDays=0){
    $sTime = gmdate("d-m-Y H:i:s", strtotime("+" . $iAddDays . " days"));
    return $sTime;
  }</pre>
<p>Now, if we were to run</p>
<pre name="code" class="php"><?php
$sTime = $oTime->ShowFutureDate(5);
print 'The time in 5 days is: ' . $sTime;
?></pre>
<p>We&#8217;d see the date in 5 days time. But for the purposes of this tutorial, let&#8217;s change things slightly so that we can use $this-> and start to understand it!</p>
<p>Firstly, let&#8217;s declare a variable that we can use within any of the class functions. We accomplish this in the following way:</p>
<pre name="code" class="php">
class Time {

  var $sTime;

  function GenerateCurrentTime(){
    $sTime = gmdate("d-m-Y H:i:s");
    return $sTime;
  }

  function ShowFutureDate($iAddDays=0){
    $sTime = gmdate("d-m-Y H:i:s", strtotime("+" . $iAddDays . " days"));
    return $sTime;
  }
}
</pre>
<div style="float: left; margin-right: 10px;">
			<script type="text/javascript"><!--
			google_ad_client = "pub-4159646232668987";
			google_ad_slot = "7221243178";
			google_ad_width = 250;
			google_ad_height = 250;
			//-->
			</script><br />
			<script type="text/javascript"
			src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
			</script>
		</div>
<p>Notice how we added &#8216;var $sTime;&#8217; at the beginning of the class file? Do the same in your code.</p>
<p>Let&#8217;s start using this as a variable, available only to the scope of the class file. It&#8217;s good practice to declare your class variables (only accessible within the scope of the class file / functions) in the header. Why are you calling that bit of space between the opening curly brace and the first function the header I hear you all ask? It&#8217;s just what I call it, as do many other developers. It&#8217;s a nice bit of white-space where you can declare your class variables within the PHP class. </p>
<h1>Ok done that, so what is $this->?</h1>
<p>Right, we&#8217;re going to remove the references to <strong>$sTime</strong> in both of our functions we now have, and we&#8217;re going to replace it with <strong>$this->sTime</strong>. Our entire class file should now look like the following:</p>
<pre name="code" class="php">
class Time {

  var $sTime;

  function GenerateCurrentTime(){
    $this->sTime = gmdate("d-m-Y H:i:s");
    return $this->sTime;
  }

  function ShowFutureDate($iAddDays=0){
    $this->sTime = gmdate("d-m-Y H:i:s", strtotime("+" . $iAddDays . " days"));
    return $this->sTime;
  }
}
</pre>
<p>If you run the code, and execute the functions on a page where you have this class file included (not within this class file!) &#8211; you&#8217;ll see that we&#8217;re still returning the same shizzle as before. That&#8217;s fine. Good infact &#8211; it means you&#8217;re following along well! Let&#8217;s say that you now run the function:</p>
<pre name="code" class="php">$oTime->ShowFutureDate(5);</pre>
<p>We know that the class, <strong>$oTime</strong> has now set it&#8217;s class variable &#8211; <strong>$sTime</strong> &#8211; to the current date + 5 days. We can now use that variable ANYWHERE in our page without having to run that function again, and again. THAT my friends is the beauty of class variables. As long as you have executed that function, we can now use:</p>
<pre name="code" class="php">echo $oTime->sTime;</pre>
<p>Anywhere, and as many times in the page as we like. It makes for much faster code! If you think of <strong>$this-></strong> outside of the class as the actual class name &#8211; <strong>$oTime</strong>, then you will have no problem using <strong>$this-></strong> within your class files, to write much much more efficient code.</p>
<h1>Final PHP Class File Code</h1>
<p>I&#8217;s worth noting in this PHP class file tutorial, that we should really remove the <strong>return</strong> references in our code, as we don&#8217;t really need them anymore. Our final code should now look like this:</p>
<pre name="code" class="php">
class Time {

  var $sTime;

  function GenerateCurrentTime(){
    $this->sTime = gmdate("d-m-Y H:i:s");
  }

  function ShowFutureDate($iAddDays=0){
    $this->sTime = gmdate("d-m-Y H:i:s", strtotime("+" . $iAddDays . " days"));
  }
}
</pre>
<p>The next tutorial will talk about <strong>Class Constructors</strong>!</p>
<h3>PHP Class Tutorial Chapters</h3>
<p><a href="http://edrackham.com/php/php-class-tutorial/" title="PHP Class Tutorial - Part 1">Part 1 &#8211; Jumping In With Two Feet</a><br />
<strong>Part 2 &#8211; What does $this-> mean in a PHP class file?</strong><br />
<a href="http://edrackham.com/php/php-class-tutorial-part-3-what-are-class-constructors/" title="PHP Class Tutorial - Part 3">Part 3 &#8211; What Are Class Constructors?</a></p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/php/php-class-tutorial-part-2-what-is-this/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Simple PHP MySQL Class</title>
		<link>http://edrackham.com/php/simple-php-mysql-class/</link>
		<comments>http://edrackham.com/php/simple-php-mysql-class/#comments</comments>
		<pubDate>Tue, 17 Aug 2010 20:50:35 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Class]]></category>

		<guid isPermaLink="false">http://edrackham.com/uncategorized/simple-php-mysql-class/</guid>
		<description><![CDATA[That&#8217;s right! I have a simple MySQL class file that you can use in your PHP projects. I&#8217;ve been using it for years, and it&#8217;s never let me down! You can grab it on my Github: http://github.com/a1phanumeric/PHP-MySQL-Class. Setup The setup is simple: Simply include this class into your project like so: include_once('/path/to/class.MySQL.php'); Then make sure [...]]]></description>
			<content:encoded><![CDATA[<p>That&#8217;s right! I have a simple MySQL class file that you can use in your PHP projects. I&#8217;ve been using it for years, and it&#8217;s never let me down!</p>
<p>You can grab it on my Github: <a href="http://github.com/a1phanumeric/PHP-MySQL-Class">http://github.com/a1phanumeric/PHP-MySQL-Class</a>.</p>
<p><span id="more-32"></span></p>
<h2>Setup</h2>
<p>The setup is simple:</p>
<p>Simply include this class into your project like so:</p>
<pre name="code" class="php">include_once('/path/to/class.MySQL.php');</pre>
<p>Then make sure you have the following definitions set:</p>
<pre name="code" class="php">MYSQL_HOST
MYSQL_USER
MYSQL_PASS
MYSQL_NAME</pre>
<p>I usually include them in a globally included config file.</p>
<p><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<p>MYSQL_HOST = The hostname of the MySQL server (usually, but not always, &#8216;localhost&#8217;).</p>
<p>MYSQL_USER = Your username for the server / database</p>
<p>MYSQL_PASS = Your password for the server / database</p>
<p>MYSQL_NAME = The name of your database</p>
<h2>Usage</h2>
<p>To use this class, you&#8217;d first init the object like so:</p>
<pre name="code" class="php">$oMySQL = new MySQL();</pre>
<p>The class constructor will perform a connection to the database automatically. To execute statements simply use:</p>
<pre name="code" class="php">$oMySQL->ExecuteSQL($query);</pre>
<p>There&#8217;s plenty more to do with this class, such as get instantly arrayed results using:</p>
<pre name="code" class="php">$oMySQL->ArrayResults();</pre>
<p>Or:</p>
<pre name="code" class="php">$oMySQL->ArrayResultsWithKey();</pre>
<p>So have a play and let me know what you think &#8230;or fork me!</p>
<p>The code is all here:</p>
<p><a href="http://github.com/a1phanumeric/PHP-MySQL-Class">http://github.com/a1phanumeric/PHP-MySQL-Class</a></p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/php/simple-php-mysql-class/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>How to make URL Safe strings for mod_rewrite using PHP</title>
		<link>http://edrackham.com/php/how-to-make-url-safe-strings-for-mod_rewrite-using-php/</link>
		<comments>http://edrackham.com/php/how-to-make-url-safe-strings-for-mod_rewrite-using-php/#comments</comments>
		<pubDate>Sun, 11 Jul 2010 17:18:18 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Mod_Rewrite]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[mod rewrite]]></category>
		<category><![CDATA[one liner]]></category>
		<category><![CDATA[preg replace]]></category>
		<category><![CDATA[url safe]]></category>

		<guid isPermaLink="false">http://edrackham.com/uncategorized/how-to-make-url-safe-strings-for-mod_rewrite-using-php/</guid>
		<description><![CDATA[It&#8217;s relatively easy to make URL safe strings for use by mod_rewrite. Let&#8217;s use the example that you have a form that adds a new blog post to your site. When the user submits this form, you want to generate a URL safe string (based on the title of the blog post) for mod_rewrite to [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s relatively easy to make URL safe strings for use by mod_rewrite. Let&#8217;s use the example that you have a form that adds a new blog post to your site. When the user submits this form, you want to generate a URL safe string (based on the title of the blog post) for mod_rewrite to use. This little snippet will show you how this can be achieved in one line of code in PHP.<br />
<span id="more-31"></span></p>
<p>The following function shows just how easy it is to generate a URL safe string for mod_rewrite. I&#8217;ve even included a demo of this code below.</p>
<p><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h3>Try it out&#8230;</h3>
<p><iframe frameborder="0" src="http://edrackham.com/tutorials/making-mod-rewrite-strings-with-php/?iframe" height="80px" width="460px" scrolling="no">Your browser doesn&#8217;t support IFRAMES. You can see the URL safe generator <a href="http://edrackham.com/tutorials/making-mod-rewrite-strings-with-php/" title="Simple Online URL Safe Generator">here</a>.</iframe></p>
<pre name="code" class="php">function MakeURLSafeString($string){
    return trim(preg_replace('/[-]{2,}/', '-', preg_replace('/[^a-z0-9]+/', '-', strtolower($_POST['TheString']))), '-');
}</pre>
<p>That&#8217;s all there is to it! To break it down a little, you could have written it as per the following:</p>
<pre name="code" class="php">function MakeURLSafeString($string){
    $string = strtolower($string); // Makes everything lowercase (just looks tidier).
    $string = preg_replace('/[^a-z0-9]+/', '-', $string); // Replaces all non-alphanumeric characters with a hyphen.
    $string = preg_replace('/[-]{2,}/', '-', $string); // Replaces one or more occurrences of a hyphen, with a single one.
    $string = trim($string, '-'); // This ensures that our string doesn't start or end with a hyphen.
    return $string;
}</pre>
<p><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/php/how-to-make-url-safe-strings-for-mod_rewrite-using-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>PHP Date Picker</title>
		<link>http://edrackham.com/php/php-date-picker/</link>
		<comments>http://edrackham.com/php/php-date-picker/#comments</comments>
		<pubDate>Fri, 16 Jan 2009 13:38:18 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://edrackham.com/php/php-date-picker/</guid>
		<description><![CDATA[This is a simple to use script that can be called at anytime to insert a date picker into your form. Example Your browser does not support IFRAMES. Please view the date picker at http://edrackham.com/tutorials/php-date-picker/ Usage Just make a call to echo DatePicker(); wherever you want the date picker to show. If you want to [...]]]></description>
			<content:encoded><![CDATA[<p>This is a simple to use script that can be called at anytime to insert a date picker into your form.</p>
<h3>Example</h3>
<p><iframe id="php_date_picker" name="php_date_picker" width="460" scrolling="no" height="70" frameborder="0" src="http://edrackham.com/tutorials/php-date-picker/?iframe">Your browser does not support IFRAMES. Please view the date picker at http://edrackham.com/tutorials/php-date-picker/</iframe><br />
<span id="more-25"></span><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h3>Usage</h3>
<p>Just make a call to
<pre name="code" class="php">echo DatePicker();</pre>
<p> wherever you want the date picker to show. If you want to use it multiple times, just call it multiple times like
<pre name="code" class="php">echo DatePicker();
echo DatePicker(); </pre>
<p> but make sure you have the first line of the code un commented.</p>
<h3>The Code</h3>
<pre name="code" class="php">$iDatePickerCounter = '';		// Used for having multiple date pickers
								// comment it out if you are only going to
								// use ONE datepicker call on this page.
								// (It will make the form element names
								// nicer to work with).
$sYearName 			= 'Year';	// Base name for the Year form element
$sMonthName 		= 'Month';	// Base name for the Month form element
$sDayName 			= 'Day';	// Base name for the Day form element

$iFromYear			= 1985;		// Starting Year
$iToYear			= 2030;		// Ending Year

function DatePicker(){
	// Call up the global variables
	global $iDatePickerCounter,
		   $sYearName,
		   $sMonthName,
		   $sDayName,
		   $iFromYear,
		   $iToYear;

	// Set up some base variables
	$sPostFix = '';
	$sNL = "\r\n";

	if(isset($iDatePickerCounter)){
		$iDatePickerCounter++;
		$sPostFix = '_' . $iDatePickerCounter;
	}

	// Start the coding of the SELECT areas
	$sYearDropDown 	= '
<select name="' . $sYearName . $sPostFix . '" id="' . $sYearName . $sPostFix . '">' . $sNL;
	$sMonthDropDown = '
<select name="' . $sMonthName . $sPostFix . '" id="' . $sMonthName . $sPostFix . '">' . $sNL;
	$sDayDropDown 	= '
<select name="' . $sDayName . $sPostFix . '" id="' . $sDayName . $sPostFix . '">' . $sNL;

	// Year loop
	for($i = $iFromYear; $i <= $iToYear; $i++){
		$sYearDropDown .= "\t" . '
<option value="' . $i . '"';

		$sYearDropDown .= (isset($_REQUEST[$sYearName . $sPostFix])) ?
						  (($_REQUEST[$sYearName . $sPostFix] == $i) ? ' selected="selected"' : '') :
						  '';
		$sYearDropDown .= '>' . $i . '</option>

' . $sNL;
	}
	$sYearDropDown .= '</select>

' . $sNL . $sNL;

	// Month Loop
	$sDummyDate = '2008-01-01';
	for($i = 0; $i < 12; $i++){
		$sMonthDropDown .= "\t" .'
<option value="' .
						   date('m', strtotime('+' . $i . ' months', strtotime($sDummyDate))) . '"';

		$sMonthDropDown .= (isset($_REQUEST[$sMonthName . $sPostFix])) ?
						  (($_REQUEST[$sMonthName . $sPostFix] == date('m', strtotime('+' . $i . ' months', strtotime($sDummyDate)))) ?
						  ' selected="selected"' : '') : '';
		$sMonthDropDown .= '>' . date('M', strtotime('+' . $i . ' months', strtotime($sDummyDate))) . '</option>

' . $sNL;
	}
	$sMonthDropDown .= '</select>

' . $sNL . $sNL;

	// Day loop
	for($i = 1; $i <= 31; $i++){
		$sDayDropDown .= "\t" .'
<option value="' . $i . '"';
		$sDayDropDown .= (isset($_REQUEST[$sDayName . $sPostFix])) ?
						 (($_REQUEST[$sDayName . $sPostFix] == $i) ? ' selected="selected"' : '') :
						 '';
		$sDayDropDown .= '>' . $i . '</option>

' . $sNL;
	}
	$sDayDropDown .= '</select>

' . $sNL . $sNL;

	return $sYearDropDown . $sMonthDropDown . $sDayDropDown;
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/php/php-date-picker/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Get Random Row with MySQL</title>
		<link>http://edrackham.com/php/get-random-row-with-mysql/</link>
		<comments>http://edrackham.com/php/get-random-row-with-mysql/#comments</comments>
		<pubDate>Sat, 09 Feb 2008 00:51:31 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://edrackham.com/php/get-random-row-with-mysql/</guid>
		<description><![CDATA[UPDATE: Please see my newer atricle on how to retrieve a random row, faster, without RAND(). This post assumes you know how to create and use a connection to a MySQL database in PHP and have a table named &#8216;quotes&#8217; as shown below. In this post, I will aim to teach you how to use [...]]]></description>
			<content:encoded><![CDATA[<p><strong>UPDATE:</strong> Please see my newer atricle on <a href="http://edrackham.com/mysql/get-random-row-with-mysql-without-rand/" title="Blink, and you'll miss it!">how to retrieve a random row, faster, without RAND()</a>.</p>
<p><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<p>This post assumes you know how to create and use a connection to a MySQL database in PHP and have a table named &#8216;quotes&#8217; as shown below. In this post, I will aim to teach you how to use PHP to pull random quotes from a MYSQL table of quotes. This can be easily extended to pull a random banner as will be explained at the end of the post.</p>
<p>Let&#8217;s firstly assume we have a MySQL table similar to the following:</p>
<pre>+----+------------------------------------------------+
| id | quote                                          |
+----+------------------------------------------------+
| 1  | I know Karate... and many other Chinese words! |
+----+------------------------------------------------+
| 2  | w00t this is geeky                             |
+----+------------------------------------------------+
| 3  | You're CLINICALLY MENTAL!                      |
+----+------------------------------------------------+</pre>
<p><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<p>Now, in your PHP code, we need to:</p>
<ol>
<li>Build a suitable MySQL query to obtain a random result from the &#8216;quotes&#8217; table.</li>
<li>Store the result of the query to be used in the HTML somewhere.</li>
<li>Output the result in the HTML somewhere.</li>
</ol>
<p>So, for step one we&#8217;d use something like the following:</p>
<pre name="code" class="php">$sSQLQuery = "SELECT quote FROM quotes ORDER BY RAND() LIMIT 1";
$aResult = mysql_query($sSQLQuery);
$aRow = mysql_fetch_array($aResult, MYSQL_ASSOC);
$sQuoteOfTheDay = $aRow['quote'];</pre>
<p>There, the variable &#8216;$sQuoteOfTheDay&#8217; now has the value of our randomly pulled quote. Let&#8217;s just analyse each line of the code above to see what it does.</p>
<pre name="code" class="php">$sSQLQuery = "SELECT quote FROM quotes ORDER BY RAND() LIMIT 1";</pre>
<p>This line stores the MySQL query we&#8217;re going to use against the database. It says, in laymans terms, &#8220;Select just one random value of the quote field from the table named quotes&#8221;. All this line does though is store the query into the variable &#8216;$sSQLQuery&#8217;.</p>
<pre name="code" class="php">$aResult = mysql_query($sSQLQuery);</pre>
<p>This line runs the MySQL query, storing the result of running the query in the variable &#8216;$aResult&#8217;. It&#8217;s important that we store the result of the mysql_query in a variable, as the result of running a successful MySQL query using PHP&#8217;s function &#8216;mysql_query&#8217; doesn’t return a nicely formatted array that we can necessarily use.</p>
<pre name="code" class="php">$aRow = mysql_fetch_assoc($aResult);</pre>
<p>This is probably the hardest line for me to explain. Firstly, many of you may have seen a similar line like this used in a &#8216;while&#8217; loop. However, our MySQL query used the &#8216;LIMIT 1&#8242; string, so we know we’re only going to get ONE result, hence no need for a loop. The function &#8216;mysql_fetch_assoc&#8217; takes one parameter: the result of the successful &#8216;mysql_query&#8217; which as we know is &#8216;$aResult&#8217;. My biggest tip here is to use the &#8216;assoc&#8217; method wherever possible, as it creates the array in such a way that we can reference each element by the column name, not a number. This is particularly useful if you ever update the MySQL table to have more columns.</p>
<p>Anyway, this line basically says &#8216;Fill the variable &#8216;$aRow&#8217; with the CURRENT row of the returned query&#8217;. We know that the CURRENT row of the returned query is the ONLY row, hence (again) the lack of a loop. As the result of our query would return something like:</p>
<pre>+-----------------------------------------------+
| quote                                         |
+-----------------------------------------------+
| You're CLINICALLY MENTAL!                     |
+-----------------------------------------------+</pre>
<p><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<p>Our variable (or array) would literally look something like:</p>
<pre name="code" class="php">Array ( "quote" = "You're CLINICALLY MENTAL!" )</pre>
<p>Which leads us on to our last line:</p>
<pre name="code" class="php">$sQuoteOfTheDay = $aRow['quote'];</pre>
<p>Which just assigns the value of &#8216;$aRow['quote']&#8216; to the variable &#8216;$sQuoteOfTheDay&#8217;. In other words, &#8216;$sQuoteOfTheDay&#8217; now has the value of a random quote pulled from the database of quotes.</p>
<p>To use this in an HTML page, we would simply just use this (AFTER the above code has grabbed the random quote from the DB for us):</p>
<pre name="code" class="php">echo $sQuoteOfTheDay;</pre>
<p>Which will output the quote of the day somewhere in the HTML code.</p>
<p>As I said at the beginning, this can be extended easily to pull an image for a banner by simply changing the quotes table to store image paths such as &#8216;images/my_image.png&#8217; which can then be pulled in the same way, and then output similar to the following:</p>
<pre name="code" class="php"><img src="<?= $sImageOfTheDay; ?>" alt="My Image" /></pre>
<p>Obviously we changed the variable name here to $sImageOfTheDay just to keep things constant.</p>
<p>Hope this has helped someone!</p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/php/get-random-row-with-mysql/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

