<?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</title>
	<atom:link href="http://edrackham.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://edrackham.com</link>
	<description>PHP, MySQL, JavaScript and Other Web Tutorials!</description>
	<lastBuildDate>Tue, 21 Feb 2012 11:57:10 +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>CSV to PLIST converter</title>
		<link>http://edrackham.com/tools/csv-to-plist-converter/</link>
		<comments>http://edrackham.com/tools/csv-to-plist-converter/#comments</comments>
		<pubDate>Tue, 21 Feb 2012 11:49:34 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Objective-C / Xcode (iPhone)]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://edrackham.com/?p=208</guid>
		<description><![CDATA[I&#8217;ve knocked up a simple to use CSV to plist converter which is pretty useful for iOS / OSX development. You can grab the code here: csv2plist.py on GitHub Usage is a piece of cake, python csv2plist.py mycsv.csv outputs: mycsv.plist in the same directory as mycsv.csv python csv2plist.py mycsv.csv myplist.plist outputs: myplist.plist in the same [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve knocked up a simple to use CSV to plist converter which is pretty useful for iOS / OSX development. You can grab the code here:</p>
<p><a href="https://github.com/a1phanumeric/csv2plist.py">csv2plist.py on GitHub</a></p>
<p>Usage is a piece of cake,</p>
<p>python csv2plist.py mycsv.csv<br />
outputs: mycsv.plist in the same directory as mycsv.csv</p>
<p>python csv2plist.py mycsv.csv myplist.plist<br />
outputs: myplist.plist in the same directory as mycsv.csv</p>
<p>Any questions or comments are greatly appreciated as always!</p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/tools/csv-to-plist-converter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I&#8217;ve Made a Free iPhone App &#8230;Should I Let You See The Source?</title>
		<link>http://edrackham.com/iphone-ipad-ipod/ive-made-a-free-iphone-app-should-i-let-you-see-the-source/</link>
		<comments>http://edrackham.com/iphone-ipad-ipod/ive-made-a-free-iphone-app-should-i-let-you-see-the-source/#comments</comments>
		<pubDate>Thu, 19 May 2011 01:22:20 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[iPhone, iPad, Ipod]]></category>
		<category><![CDATA[Objective-C / Xcode (iPhone)]]></category>

		<guid isPermaLink="false">http://edrackham.com/?p=187</guid>
		<description><![CDATA[So, I&#8217;ve built an iPhone app &#8211; What Should I Make For Dinner Tonight?. Please download it and play with it. I&#8217;d LOVE to hear your feedback, and will happily code in any improvements we all agree would be beneficial. If you&#8217;re interested in the Objective-C source code then let me know and maybe I&#8217;ll [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://a5.mzstatic.com/us/r1000/051/Purple/26/cd/4f/mzm.tzzzhtwo.175x175-75.jpg" alt="What Should I Make For Dinner Tonight - Free iPhone App" style="float: left; margin-right: 10px" />So, I&#8217;ve built an iPhone app &#8211; <a href="http://itunes.apple.com/us/app/what-should-i-make-for-dinner/id432085816?mt=8&#038;ls=1">What Should I Make For Dinner Tonight</a>?.</p>
<p>Please <a href="http://itunes.apple.com/us/app/what-should-i-make-for-dinner/id432085816?mt=8&#038;ls=1">download it and play with it</a>. I&#8217;d LOVE to hear your feedback, and will happily code in any improvements we all agree would be beneficial. If you&#8217;re interested in the Objective-C source code then let me know and maybe I&#8217;ll release it!</p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/iphone-ipad-ipod/ive-made-a-free-iphone-app-should-i-let-you-see-the-source/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>How to Format NSDate in Objective-C Tutorial (iPhone / Cocoa)</title>
		<link>http://edrackham.com/objective-c-xcode-iphone/how-to-format-nsdate-in-objective-c-tutorial-iphone-cocoa/</link>
		<comments>http://edrackham.com/objective-c-xcode-iphone/how-to-format-nsdate-in-objective-c-tutorial-iphone-cocoa/#comments</comments>
		<pubDate>Fri, 25 Mar 2011 10:34:55 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Objective-C / Xcode (iPhone)]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[NSDate]]></category>
		<category><![CDATA[NSDateFormatter]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://edrackham.com/?p=183</guid>
		<description><![CDATA[How to format NSDate using NSDateFormatter (iPhone Xcode Tutorial) So, you&#8217;re making an iPhone (or iPad) app, and want to know how to format an NSDate in Cocoa? Formatting NSDate in Objective-C is actually not too difficult. Open up Xcode and let&#8217;s get&#8217;s cracking with some Objective-C goodness! For those who just smash up Xcode, [...]]]></description>
			<content:encoded><![CDATA[<p>How to format NSDate using NSDateFormatter (iPhone Xcode Tutorial)</p>
<p>So, you&#8217;re making an iPhone (or iPad) app, and want to know how to format an NSDate in Cocoa? Formatting NSDate in Objective-C is actually not too difficult. Open up Xcode and let&#8217;s get&#8217;s cracking with some Objective-C goodness!</p>
<p>For those who just smash up Xcode, and get cracking with their iPhone applications &#8211; I&#8217;m putting the full source code of this tutorial right here at the top:</p>
<pre class="brush: objc; title: ; notranslate">
NSDate *myDate = [NSDate date];
NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:@&quot;EEEE dd MMMM, yyyy&quot;];
self.someLabel.text = [df stringFromDate:myDate];
[df release];
</pre>
<p><span id="more-183"></span></p>
<p>Right, and now for those who want a bit more of an explanation of how to format an NSDate for your iPhone applications in Objective-C.</p>
<p>To begin, create a date variable:</p>
<pre class="brush: objc; title: ; notranslate">
NSDate *myDate = [NSDate date];
</pre>
<p>Nothing particularly difficult there &#8211; we now have the current date stored in myDate.</p>
<p>Now, Apple have made a nice class called NSDateFormatter that we can use to display our NSDate in our iPhone app in all kinds of wonderful ways… First we need to create a new NSDateFormatter:</p>
<pre class="brush: objc; title: ; notranslate">
NSDateFormatter *df = [NSDateFormatter new];
</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>Then we need to set a format on our NSDateFormatter, which will be used to dictate the way our NSDate is displayed on our iPhone. Similar (but not the same) to how PHP&#8217;s date() function works, we can use a date pattern as specified at Unicode.org: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns. </p>
<p>If you wanted to display the date like &#8220;Friday 25 March, 2011&#8243; you would use the following call to your NSDateformatter (in the above example, we declared this as &#8216;df&#8217;):</p>
<pre class="brush: objc; title: ; notranslate">
[df setDateFormat:@&quot;EEEE dd MMMM, yyyy&quot;];
</pre>
<p>Ok, so our NSDateFormatter is all set up, now how do we actually get this applied to our NSDate? Simple, we just use the following:</p>
<pre class="brush: objc; title: ; notranslate">
[df stringFromDate:myDate];
</pre>
<p>That&#8217;s basically it, but don&#8217;t forget to release your NSDateFormatter, as we used &#8216;new&#8217; earlier (same as alloc, init):</p>
<pre class="brush: objc; title: ; notranslate">
[df release];
</pre>
<p>stringFromDate returns a NSString, so you can either assign this to a variable, or apply it directly to a UILabel, UITextField etc&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/objective-c-xcode-iphone/how-to-format-nsdate-in-objective-c-tutorial-iphone-cocoa/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<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>3</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 Create a Textarea Character Counter / Limiter Using jQuery</title>
		<link>http://edrackham.com/javascript/how-to-create-a-textarea-character-counter-limiter-using-jquery/</link>
		<comments>http://edrackham.com/javascript/how-to-create-a-textarea-character-counter-limiter-using-jquery/#comments</comments>
		<pubDate>Mon, 04 Oct 2010 20:07:52 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Character Counter]]></category>
		<category><![CDATA[Code Snippet]]></category>
		<category><![CDATA[Forms]]></category>
		<category><![CDATA[Textarea]]></category>

		<guid isPermaLink="false">http://edrackham.com/?p=83</guid>
		<description><![CDATA[Need to limit the number of characters that are allowed to be entered into a textarea? I&#8217;ve crafted a little snippet that you can drop into your projects to achieve just that! It also provides a counter to the user, showing how many characters are remaining as they type. Your browser doesn&#8217;t support IFRAMES. You [...]]]></description>
			<content:encoded><![CDATA[<p>Need to limit the number of characters that are allowed to be entered into a textarea? I&#8217;ve crafted a little snippet that you can drop into your projects to achieve just that! It also provides a counter to the user, showing how many characters are remaining as they type.</p>
<p><iframe frameborder="0" src="http://edrackham.com/tutorials/textarea-character-counter-using-jquery/?iframe" height="80px" width="460px" scrolling="no">Your browser doesn&#8217;t support IFRAMES. You can see the textarea character counter <a href="http://edrackham.com/tutorials/textarea-character-counter-using-jquery/" title="Textarea Character Counter">here</a>.</iframe></p>
<p>This could be extended pretty easily, so that it works on multiple textareas, or even as a jQuery plugin.<span id="more-83"></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>Show Me the Code</h2>
<p>If you don&#8217;t need to read the breakdown of this tutorial, you can simply just copy the code below and read no further!</p>
<h3>The Javascript</h3>
<pre name="code" class="javascript">
&lt;script type="text/javascript" src="http://www.google.com/jsapi"&gt;&lt;/script&gt;

&lt;script type="text/javascript" language="javascript"&gt;
google.load("jquery", "1.4.2");

var characterLimit = 150;

google.setOnLoadCallback(function(){

	$('#remainingCharacters').html(characterLimit);

	$('#myTextarea').bind('keyup', function(){
		var charactersUsed = $(this).val().length;

		if(charactersUsed > characterLimit){
			charactersUsed = characterLimit;
			$(this).val($(this).val().substr(0, characterLimit));
			$(this).scrollTop($(this)[0].scrollHeight);
		}

		var charactersRemaining = characterLimit - charactersUsed;

		$('#remainingCharacters').html(charactersRemaining);
	});
});
&lt;/script&gt;
</pre>
<h3>The HTML</h3>
<pre name="code" class="html">
<textarea id="myTextarea"></textarea>

<span id="remainingCharacters"></span> characters remaining.
</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>So, How Does It All Work?</h2>
<p>Let&#8217;s start with the HTML markup. It&#8217;s pretty simple, we&#8217;re just creating a textarea, with an ID of <strong>myTextarea</strong>. We also have a paragraph below that, which has an empty span with an ID of <strong>remainingCharacters</strong>. This is where the remaining characters will be displayed to the user as they type.</p>
<h2>Google JSAPI</h2>
<p>The Javascript is a little more involved. Let&#8217;s go line-by-line:</p>
<pre name="code" class="javascript">
&lt;script type="text/javascript" src="http://www.google.com/jsapi"&gt;&lt;/script&gt;
</pre>
<p>I&#8217;ve recently started using the <a href="http://code.google.com/apis/libraries/">Google JSAPI</a> to link to my most-used Javascript libraries. For those who don&#8217;t know what the Google JSAPI is &#8211; <a href="http://code.google.com/apis/libraries/">have a read here</a>. I prefer to load jQuery this way for a number of reasons:</p>
<ul>
<li>It&#8217;s always hosted in the same place &#8211; so no having to traverse your own paths to find where your JS libraries are located</li>
<li>It saves bandwidth</li>
<li>It seems to load much faster</li>
<li>It&#8217;s very easy to bolt on other libraries you may need</li>
</ul>
<pre name="code" class="javascript">
&lt;script type="text/javascript" language="javascript"&gt;
google.load("jquery", "1.4.2");
</pre>
<p>Here, we&#8217;re starting our main Javascript block, and &#8211; using the Google JSAPI &#8211; we&#8217;re loading the jquery library, version 1.4.2.</p>
<h2>Variable Limit</h2>
<pre name="code" class="javascript">
var characterLimit = 150;
</pre>
<p>Real simple here &#8211; we&#8217;re setting a global variable to the value of our limit for the textarea. Feel free to change this value to whatever you wish.</p>
<h2>What? No $(document).ready()?</h2>
<pre name="code" class="javascript">
google.setOnLoadCallback(function(){
</pre>
<p>Nope. When you use the Google JSAPI, you should really use <strong>google.setOnLoadCallback()</strong>. This is due to the way we&#8217;re loading the jQuery. $(document).ready() may actually provide a false-positive, and execute before the jQuery has been fully loaded &#8211; therefore we should use the google on load callback &#8211; which fires once all the libraries we have requested have been included.</p>
<h2>Set the Starting Figure</h2>
<pre name="code" class="javascript">
$('#remainingCharacters').html(characterLimit);
</pre>
<p>As our <strong>remainingCharacters</strong> span in our HTML markup is empty, we need to set the value when the page loads. We could hard-code the value of the remaining characters, but this would mean that we&#8217;d have to update two places if we wanted to change the limit, not just one (the one place we need to update the character limit is on the <strong>var characterLimit = 150;</strong> line).<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>
<h2>Binding It All Up</h2>
<pre name="code" class="javascript">
$('#myTextarea').bind('keyup', function(){
	var charactersUsed = $(this).val().length;

	if(charactersUsed &gt; characterLimit){
		charactersUsed = characterLimit;
		$(this).val($(this).val().substr(0, characterLimit));
		$(this).scrollTop($(this)[0].scrollHeight);
	}

	var charactersRemaining = characterLimit - charactersUsed;

	$('#remainingCharacters').html(charactersRemaining);
});
</pre>
<p>The final bit, this <strong>bind</strong> is where all the magic happens. Firstly we&#8217;re binding a function to the &#8216;keyup&#8217; event on the element named <strong>myTextarea</strong>.</p>
<p>Inside this function we need to know how many characters have been used. We do this by calling the following:</p>
<pre name="code" class="javascript">
var charactersUsed = $(this).val().length;
</pre>
<p>Notice how we can use <strong>$(this)</strong> to reference the <strong>myTextarea</strong> element. This is a nice little bit of shorthand that comes in handy &#8211; often!</p>
<pre name="code" class="javascript">
if(charactersUsed &gt; characterLimit){
	charactersUsed = characterLimit;
	$(this).val($(this).val().substr(0, characterLimit));
	$(this).scrollTop($(this)[0].scrollHeight);
}
</pre>
<p>We then have this if statement which checks to see if the number of characters used is greater than our preset character limit. If it is greater, we know that the user has gone over their limit, and we need to do something about that. We need to trim any extra characters past our limit, and reset the focus to the bottom of the textarea. We need to set the focus to the bottom again, because when you update the text within a textarea, the focus jumps back to the top!</p>
<h2>Letting the User See How Many Characters Remain</h2>
<pre name="code" class="javascript">
var charactersRemaining = characterLimit - charactersUsed;

$('#remainingCharacters').html(charactersRemaining);
</pre>
<p>Fairly self explanatory here &#8211; we do a quick calculation to determine how many characters remain, and then update the <strong>remainingCharacters</strong> span, so the user can see how much more they can type.</p>
<p>Remember, this gets updated every time they key is released from within the textarea.</p>
<p>That concludes this tutorial! I hope it&#8217;s helped in some way. I may even release this as a simple jQuery plugin that can be used on any number of textareas.</p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/javascript/how-to-create-a-textarea-character-counter-limiter-using-jquery/feed/</wfw:commentRss>
		<slash:comments>7</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>12</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>24</slash:comments>
		</item>
		<item>
		<title>All Beginner Tutorials</title>
		<link>http://edrackham.com/tools/all-beginner-tutorials/</link>
		<comments>http://edrackham.com/tools/all-beginner-tutorials/#comments</comments>
		<pubDate>Sun, 12 Sep 2010 17:45:58 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Tools]]></category>
		<category><![CDATA[All Beginner Tutorials]]></category>

		<guid isPermaLink="false">http://edrackham.com/featured/all-beginner-tutorials/</guid>
		<description><![CDATA[So &#8211; I&#8217;ve just started off this new site &#8211; All Beginner Tutorials. It&#8217;s aimed at becoming a repository for many beginner-focused tutorials. Please take the time to check it out, and even add a tutorial or two!]]></description>
			<content:encoded><![CDATA[<p>So &#8211; I&#8217;ve just started off this new site &#8211; <a href="http://all-beginner-tutorials.com">All Beginner Tutorials</a>. It&#8217;s aimed at becoming a repository for many beginner-focused tutorials. Please take the time to check it out, and even <a href="http://all-beginner-tutorials.com/submit-a-tutorial/">add a tutorial or two</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/tools/all-beginner-tutorials/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

