<?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>GeekScribes &#187; Programming</title>
	<atom:link href="http://www.geekscribes.net/blog/category/tech-posts/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.geekscribes.net/blog</link>
	<description>Bringing geekiness to the world</description>
	<lastBuildDate>Tue, 07 Feb 2012 15:21:59 +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>Fundamentals of Programming: Part 3 &#8211; Style, Indentation and Comments</title>
		<link>http://www.geekscribes.net/blog/2012/02/07/fundamentals-of-programming-part-3-style-indentation-and-comments/</link>
		<comments>http://www.geekscribes.net/blog/2012/02/07/fundamentals-of-programming-part-3-style-indentation-and-comments/#comments</comments>
		<pubDate>Tue, 07 Feb 2012 15:16:08 +0000</pubDate>
		<dc:creator>InF</dc:creator>
				<category><![CDATA[Fundamentals]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tech Posts]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.geekscribes.net/blog/?p=1729</guid>
		<description><![CDATA[Welcome to Part 3 of the multi-post series on Fundamentals of Programming. Last time, I just touched upon one very important point regarding style in programming: indentation. In this series, we&#8217;ll see a bit more about styles in programming. You can think of those as the &#8220;formatting&#8221; used in programming. We&#8217;ll end with the importance [...]<p>This article comes from <a href="http://www.geekscribes.net/blog">GeekScribes</a><br/><br/><a href="http://www.geekscribes.net/blog/2012/02/07/fundamentals-of-programming-part-3-style-indentation-and-comments/">Fundamentals of Programming: Part 3 &#8211; Style, Indentation and Comments</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Welcome to Part 3 of the multi-post series on Fundamentals of Programming. Last time, I just touched upon one very important point regarding style in programming: indentation. In this series, we&#8217;ll see a bit more about styles in programming. You can think of those as the &#8220;formatting&#8221; used in programming. We&#8217;ll end with the importance of conventions, comments and consistency in programming. I hope you will enjoy this part and learn something.</p>
<p><span id="more-1729"></span></p>
<h2>Editors and IDEs help!</h2>
<p>Last time, we saw about indentation. Basically, indentation is making specific lines of code offset a bit so that you know at a glance where they belong. There are two ways of making indentation while programming: one is to use tabs (i.e. the tab key) and one is using multiple-spaces e.g. (press the space key 4 times).</p>
<p>Which one you use depends on you. As long as you stick to the style you choose, you should be alright. Now, if you&#8217;re writing code for other people e.g. open-source projects or a company, they may enforce a style on you i.e. you should only use space for e.g. because upstream, some other people have troubles with tabs. At this stage, you shouldn&#8217;t worry too much about those. In any case, you can have your Integrated Development Environment (IDE) do the substitution for you for e.g. replace a single press of the Tab key by 4 spaces.</p>
<p>You still remember what an IDE is, right? It&#8217;s that program that makes the task of writing other programs easier. Like a word processor for writing programs.</p>
<p>It&#8217;s a good idea to use an IDE when writing programs. Which IDE you will use largely depends on which language you are writing in, so we won&#8217;t go into the various IDEs that exist. If you write in many languages, or don&#8217;t want the hassle of having to install and learn an IDE, you could use so-called &#8220;Programmer Notepads&#8221;.</p>
<p>I did say you&#8217;re fine using Windows&#8217; Notepad program. Actually you are. Only, it is not specially meant for writing programs. It&#8217;s just a generic text editor.</p>
<p>These are text editors that have IDE-like functions especially code highlighting, syntax checking, code completion and indentation guidelines for e.g. There are many of those out there, so I&#8217;ve listed the 5 most common ones so you have something to start. Just choose one and start typing! The number of features provided will vary from just syntax highlighting to fairly complex things like versioning through plugins. So just get one of those 5 and you should have an easier task at writing code:</p>
<ol>
<li><a  title="Notepad++ Homepage" href="http://notepad-plus-plus.org/" target="_blank">Notepad++</a></li>
<li><a  title="PSPad Homepage" href="http://www.pspad.com/" target="_blank">PSPad</a></li>
<li><a  title="Programmer's Notepad" href="http://www.pnotepad.org/" target="_blank">Programmer&#8217;s Notepad</a></li>
<li><a  title="Crimson Editor Homepage" href="http://www.crimsoneditor.com/" target="_blank">Crimson Editor</a></li>
<li><a  title="Notepad2 Homepage" href="http://www.flos-freeware.ch/notepad2.html" target="_blank">Notepad2</a></li>
</ol>
<p>On Linux and other Unix variants, you will have the all-powerful Vim and Emacs, as well as GUI variants such as Kate and GEdit. Am just listing those here for reference, but if you&#8217;re already on Linux, you should probably already have found those. They probably come ready installed with your OS anyway so just find where they are and start using them. <img src='http://www.geekscribes.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Which editor you choose doesn&#8217;t really matter as long as it does what you want, and it makes things simple. If your editor makes a simple task more complex, you should either consider using another editor or see whether you&#8217;re doing stuff right in the first place! Editors vary in terms of features: some people like editors that does everything from highlighting brackets to sending satellites in space on their own. Others just want a place to type and if it provides pretty colors, fine! See what you want in an editor and choose appropriately.</p>
<p>At first, it&#8217;s good to try a lot of them to see which one you like. But after a while, try to choose one and learn how it works. You don&#8217;t want to keep switching editors mid-project and having to re-learn where the various options e.g. search and replace are found. I.e. find one and love it.</p>
<p>When you&#8217;re using one of these editors, the task of checking indentation, finding where brackets and braces open and close etc are handled automatically. That&#8217;s one less thing to worry about. But you still need to ensure your indentation is correct. Let&#8217;s see how pseudo code would look in one of these editors: Notepad++.</p>
<p style="text-align: center;"><img class="size-full wp-image-1731 aligncenter" title="Notepad++ Style" src="http://www.geekscribes.net/blog/wp-content/uploads/2012/02/fp_npp.png" alt="" width="449" height="150" /></p>
<p>And here&#8217;s how it looks in plain old Notepad:</p>
<p style="text-align: center;"><img class="size-full wp-image-1732 aligncenter" title="Notepad Style" src="http://www.geekscribes.net/blog/wp-content/uploads/2012/02/fp_notepad.png" alt="" width="416" height="262" /></p>
<p>You can see a few things are different from the Notepad++ image. First, the &#8220;reserved&#8221; or keywords are highlighted in a different color: blue. Second, brackets are highlighted so you can easily identify where pairs of brackets start and end (they are bolded here). Quoted text is in a different color, so if you accidentally missed a quote, you&#8217;d see everything in grey and you know something is off. See the faint dotted lines below &#8220;If&#8221;? They represent indentation guides. That is, they show where the &#8220;If&#8221; is going to end and what code falls under the control of the If. Similarly, if I had different levels of indentation, I&#8217;d see additional lines.  Finally, you can see line numbers. If you&#8217;re writing code and a friend says there&#8217;s a problem on line 13028, you don&#8217;t have to start counting but can go directly to it! Notepad cannot do this for you.</p>
<p>All these little things really help when you are writing large programs with thousands of lines. You can immediately see where a block starts or ends without having to do a ton of scrolling.</p>
<p>I think you&#8217;ve got the point now. Use an editor or an IDE. It makes life easier!</p>
<p>&nbsp;</p>
<h2>Comments</h2>
<p>What are comments? It&#8217;s as the name says, things you write in the code to make it clearer when reading it. They&#8217;re like small notes you write in the code itself to describe bits of code that might be difficult to understand at first glance.</p>
<p>Why would you want to type additional things and make things more tiring? Well, comments help. A lot! A LOT! They may not make sense now, but think about reading the same code, but 2 years later. Will you remember then, what that obscure piece of code does? Probably not. If you have put comments there, then yes, you&#8217;ll know immediately.</p>
<p>First, don&#8217;t write stupid comments. After you start programming, it&#8217;s no use commenting every single line of code. That is both senseless and wasting time. Things like (a+b) are obvious to any programmer. What you should be commenting is when you have codes that do special tasks. For e.g.</p>
<p>Does this make sense?</p>
<p style="text-align: center;"><img class="size-full wp-image-1733 aligncenter" title="Fahrenheit Conversion" src="http://www.geekscribes.net/blog/wp-content/uploads/2012/02/fp_fahrenheit.png" alt="" width="268" height="44" /></p>
<p>Does it now?</p>
<p style="text-align: center;"><img class="wp-image-1743 aligncenter" title="Celcius to Fahrenheit Commented" src="http://www.geekscribes.net/blog/wp-content/uploads/2012/02/fp_fahrenheit_comments1.png" alt="" width="381" height="59" /></p>
<p>Now you know the importance of comments.</p>
<p>Comments are identified by different symbols in different languages so make sure to use the right symbol, but here is a quick rundown of the most common symbols used to identify comments in code.</p>
<p>&nbsp;</p>
<p>Now you how what comments are, i.e. descriptions about code, written in the code itself and identified using special symbols, I advise you to use plenty of these where you think the code is not very clear or easy to understand. You&#8217;ll learn what to comment as you start writing more and more code. It then becomes second-nature and you&#8217;ll wish every programmer out there commented their code appropriately.</p>
<p style="text-align: center;"><img class="size-full wp-image-1738 aligncenter" title="Comment Styles" src="http://www.geekscribes.net/blog/wp-content/uploads/2012/02/fp_comments_style1.png" alt="" width="381" height="246" /></p>
<h2>Consistency</h2>
<p>Consistency refers to writing code in the same style, every time. This is not always possible as sometimes different projects impose different styles. But whatever style you will choose, stick to it. I.e. be consistent.</p>
<p>For e.g. I like plenty of white space in my code. I find it makes stuff easier to read. The second one is how I&#8217;d write this code. The first one could be written by another person who likes compactness and minimalism. Both do the same thing. If it makes sense to them, fine.</p>
<p style="text-align: center;"><img class="size-full wp-image-1736 aligncenter" title="Consistency in Code" src="http://www.geekscribes.net/blog/wp-content/uploads/2012/02/fp_consistency.png" alt="" width="356" height="147" /></p>
<p>But now, if I start arbitrarily switching between the various styles, for e.g. I use different numbers of white-spaces or different styles of opening and closing brackets, it makes things tough for others.</p>
<p>We&#8217;ll see more styles of coding in the other parts, especially after we start &#8220;Conditions&#8221;. It then becomes important that you write in one consistent way instead of as-you-please. Just keep this point in mind at the moment: choose your style and stick to it. Don&#8217;t change mid-way because you think brackets are prettier on their own line. You&#8217;ll make many other people angry!</p>
<p>That&#8217;s it for this rather short part. I hope you found it interesting. As usual, ask your questions using the comments box below and I welcome comments from other programmers if they think I could have written things better or provided more details. See you in the next part!</p>
<h3>In the same series:</h3><ul class="eg-series-posts" ><li class="eg-series-posts-item current"><span class="eg-series-post-title">Fundamentals of Programming: Part 3 - Style, Indentation and Comments</span> <span class="eg-series-post-this">(This post)</span></li><li class="eg-series-posts-item "><span class="eg-series-post-title"><a  href="http://www.geekscribes.net/blog/2012/02/05/fundamentals-of-programming-part-2-pseudo-code-and-batch-jobs/" title="Fundamentals of Programming: Part 2 - Pseudo Code and Batch Jobs">Fundamentals of Programming: Part 2 - Pseudo Code and Batch Jobs</a></span> </li><li class="eg-series-posts-item "><span class="eg-series-post-title"><a  href="http://www.geekscribes.net/blog/2012/02/04/fundamentals-of-programming-part-1-introduction/" title="Fundamentals of Programming: Part 1 - Introduction">Fundamentals of Programming: Part 1 - Introduction</a></span> </li></ul>
<p>This article comes from <a  href="http://www.geekscribes.net/blog">GeekScribes</a><br/><br/><a  href="http://www.geekscribes.net/blog/2012/02/07/fundamentals-of-programming-part-3-style-indentation-and-comments/">Fundamentals of Programming: Part 3 &#8211; Style, Indentation and Comments</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.geekscribes.net/blog/2012/02/07/fundamentals-of-programming-part-3-style-indentation-and-comments/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fundamentals of Programming: Part 2 &#8211; Pseudo Code and Batch Jobs</title>
		<link>http://www.geekscribes.net/blog/2012/02/05/fundamentals-of-programming-part-2-pseudo-code-and-batch-jobs/</link>
		<comments>http://www.geekscribes.net/blog/2012/02/05/fundamentals-of-programming-part-2-pseudo-code-and-batch-jobs/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 20:45:15 +0000</pubDate>
		<dc:creator>InF</dc:creator>
				<category><![CDATA[Fundamentals]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tech Posts]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.geekscribes.net/blog/?p=1718</guid>
		<description><![CDATA[Hello, welcome to Part 2 of the series. In this section, we&#8217;ll start with some actual code writing. &#8220;Code&#8221; is a short term to refer to &#8220;programming lines&#8221; i.e. instructions. So when someone is &#8220;coding&#8221;, they&#8217;re actually &#8220;writing programs&#8221;. I&#8217;ll use that word for short. We&#8217;ll start with writing some instructions in pseudo-code. What is [...]<p>This article comes from <a href="http://www.geekscribes.net/blog">GeekScribes</a><br/><br/><a href="http://www.geekscribes.net/blog/2012/02/05/fundamentals-of-programming-part-2-pseudo-code-and-batch-jobs/">Fundamentals of Programming: Part 2 &#8211; Pseudo Code and Batch Jobs</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Hello, welcome to Part 2 of the series. In this section, we&#8217;ll start with some actual code writing. &#8220;Code&#8221; is a short term to refer to &#8220;programming lines&#8221; i.e. instructions. So when someone is &#8220;coding&#8221;, they&#8217;re actually &#8220;writing programs&#8221;. I&#8217;ll use that word for short.</p>
<p>We&#8217;ll start with writing some instructions in pseudo-code. What is pseudo-code? Does it mean pseudo-programming? Yes, sort of.</p>
<p>You want to make sure you understand how to write and understand pseudo-code because that&#8217;s what I&#8217;ll be using through the rest of this series. They&#8217;re easy, English-like statement so don&#8217;t worry too much.</p>
<p><span id="more-1718"></span></p>
<h2>Pseudo Code</h2>
<p>Pseudo-code refers to instructions written in a structured language. That is, there are specific words to represent specific things. Like commands for e.g. You&#8217;ll understand what I mean soon. The good thing about pseudo code is that it is programming language-independent. You can write instructions in pseudo-code then hand your sheet to any programmer and he or she will be able to write a program based on that. Why? Because pseudo-code represents instructions in an independent way. The programmer will then be able to translate those in the language of his/her choice with appropriate syntax.</p>
<p>In short, pseudo-code are step-by-step instructions to solve problems, written in a &#8220;strict&#8221; way that can then be used as guideline when writing a program.</p>
<p>Algorithms are usually step-by-step instructions to solve a problem. You could say that pseudo-code is  a way to write algorithms. For e.g., some algorithm in mathematics can say, you need to square this, differentiate that. In pseudo-code, you&#8217;re just writing the things to do in a structured way. So for the purpose of this article, I&#8217;d say they mean the same things. Just step-by-step instructions.</p>
<p>How do programs begin? They start in the mind of a programmer as a series of steps that must be completed to solve a problem. Programmers think in terms of pseudo-code, and then use those to write programming language codes. Sometimes they write these instructions on paper or a whiteboard to make it easier for them, but for simple things, they just do it mentally. It becomes simple enough with some practice.</p>
<p>To get you started, let&#8217;s assume you&#8217;re telling a friend how to draw a simple house. You need to tell them instructions. What would you be telling him/her? Write down your commands.</p>
<p>If I were to do that, I&#8217;d probably write those lines:</p>
<pre style="padding-left: 30px;">Draw a square, each line being 10 cm. (walls)
At the top of the square, draw a triangle, touching the square. (roof)
Inside the square, draw two smaller squares near the top. (windows)
Near the bottom of the square, in the middle, draw a small rectangle. (Doors)</pre>
<p>Hopefully, that should give you a decent-looking house drawn like a 5-year old. Congratulations, you just wrote some pseudo-code!</p>
<p>Let&#8217;s see another example. We want to have the computer ask the user for two numbers, add those two numbers and then show the result to the user. Simple enough, huh?</p>
<p>This example has 3 sections: an input section (asking the user), a processing section (add numbers) and an output section (show the result). Those 3 steps are the basic things that happen in programs. These 3 things occur in almost all programs, although they may not be very apparent in all programs.</p>
<p>So let&#8217;s see how we can write pseudo codes for this problem:</p>
<pre style="padding-left: 30px;">Input 2 numbers, a and b.
Result = a + b.
Output result.</pre>
<p>Simple, yes? This is pseudo-code for addition of two numbers. If you look carefully, you will see I used &#8220;a&#8221; and &#8220;b&#8221;. These are called variables and we&#8217;ll see about those in the next part. Basically, these act as two generic numbers so whatever 2 numbers the user will tell the computer, they will be represented as a and b.</p>
<p>This is a simple set of instructions and a number of things could go wrong in that. It&#8217;s also fairly limited in terms of functions. What if you want something else than addition? What about multiplication? Can&#8217;t do. Actually, we can. We will do this in the lesson about conditions. What about adding more than two numbers? Can&#8217;t do. Oh yes we can, but in loops lesson! <img src='http://www.geekscribes.net/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Normally pseudo-code has a fairly strict syntax so that code written by different people. If a person writes &#8220;Input 2 numbers&#8221; and another &#8220;Enter 2 numbers&#8221;, it&#8217;s still ok. But if a 3rd writes &#8220;Shout 2 numbers&#8221;&#8230; then no. Thus, pseudo-code uses a restricted number of words in English, normally words which you will normally find in other programming languages. For e.g. &#8220;input&#8221;, &#8220;output&#8221;, &#8220;if&#8221;, &#8220;else&#8221; etc. You&#8217;ll learn about those words as we go along.</p>
<p>&nbsp;</p>
<h2>Batch Jobs</h2>
<p>Sometimes, programs don&#8217;t ask the user for any inputs. They just take their inputs from some file or from some other place. Batch jobs, or batch programs, are those programs that run without the user having to supply any data during running. Data, as in numbers, text or other information. They run, do their processing and could do some outputs, although not all of them do.</p>
<p>Let&#8217;s see about two examples of batch jobs. First example will read a series of numbers from a file and add them all together. If you don&#8217;t understand some parts, don&#8217;t worry too much. I&#8217;ll cover them in next parts. So, here it is:</p>
<pre style="padding-left: 30px;">Open numbers file.

While there are more numbers to read in file</pre>
<pre style="padding-left: 60px;">Add number just read to Total.</pre>
<pre style="padding-left: 30px;">End</pre>
<pre style="padding-left: 30px;">Output Total.</pre>
<pre style="padding-left: 30px;">Close File</pre>
<p>Here, we didn&#8217;t ask the user for inputs. We just get numbers from a file and add them all to a total count then show that to the user. The &#8220;inputs&#8221; are actually read automatically so the program can run fast, i.e. doesn&#8217;t have to wait for the user to supply numbers one by one. Thus we had to tell the computer to open the needed &#8220;numbers&#8221; file, read off it and finally close it when it&#8217;s done.</p>
<p>Note one thing: the &#8220;Add number just read to Total&#8221; is a bit off-sided as compared to the rest. This is called &#8220;indentation&#8221; and it makes reading code blocks easier. At a glance, we can know that this line falls under the control of the &#8220;While block&#8221;.</p>
<p>Which do you prefer in terms of clarity:</p>
<pre style="padding-left: 30px;">While there are more numbers to read in file
Add number just read to Total.
End</pre>
<p>Or:</p>
<pre style="padding-left: 30px;">While there are more numbers to read in file</pre>
<pre style="padding-left: 60px;">Add number just read to Total.</pre>
<pre style="padding-left: 30px;">End</pre>
<p>Guess I already know the answer.</p>
<p>Code blocks are important in programming since they normally do different things as the program is running. So seeing what code is running under the control of which blocks is very important and I encourage you to properly indent your code when you are writing inside blocks. You will learn what this particular block of code does if you read the &#8220;Loops&#8221; part of this series.</p>
<p>Let&#8217;s see another example. This time, no inputs, no outputs. Just processing. The &#8220;output&#8221; is actually writing to a file. We&#8217;ll do the same thing as above: read numbers in a file and find their total. But we&#8217;ll then write this number in another file.</p>
<pre style="padding-left: 30px;">Open numbers file</pre>
<pre style="padding-left: 30px;">While there are more numbers to read in file</pre>
<pre style="padding-left: 60px;">Add number just read to Total</pre>
<pre style="padding-left: 30px;">End</pre>
<pre style="padding-left: 30px;">Open results file</pre>
<pre style="padding-left: 30px;">Write Total to results file</pre>
<pre style="padding-left: 30px;">Close results file</pre>
<pre style="padding-left: 30px;">Close numbers file</pre>
<p>This time, we don&#8217;t show the user anything. We just read from one file and write to another. Basically, if this program was ran, the user would just see the program start and exit, and nothing else happen. They will have to open the results file to see something had happened.</p>
<p>That&#8217;s it for this part. I hope you enjoyed it and learnt something interesting. If you have questions, just ask in the comments below. Again, I ask programmers out there to please provide suggestions and comments. Thank you for reading and see you in Part 3.</p>
<h3>In the same series:</h3><ul class="eg-series-posts" ><li class="eg-series-posts-item "><span class="eg-series-post-title"><a  href="http://www.geekscribes.net/blog/2012/02/07/fundamentals-of-programming-part-3-style-indentation-and-comments/" title="Fundamentals of Programming: Part 3 - Style, Indentation and Comments">Fundamentals of Programming: Part 3 - Style, Indentation and Comments</a></span> </li><li class="eg-series-posts-item current"><span class="eg-series-post-title">Fundamentals of Programming: Part 2 - Pseudo Code and Batch Jobs</span> <span class="eg-series-post-this">(This post)</span></li><li class="eg-series-posts-item "><span class="eg-series-post-title"><a  href="http://www.geekscribes.net/blog/2012/02/04/fundamentals-of-programming-part-1-introduction/" title="Fundamentals of Programming: Part 1 - Introduction">Fundamentals of Programming: Part 1 - Introduction</a></span> </li></ul>
<p>This article comes from <a  href="http://www.geekscribes.net/blog">GeekScribes</a><br/><br/><a  href="http://www.geekscribes.net/blog/2012/02/05/fundamentals-of-programming-part-2-pseudo-code-and-batch-jobs/">Fundamentals of Programming: Part 2 &#8211; Pseudo Code and Batch Jobs</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.geekscribes.net/blog/2012/02/05/fundamentals-of-programming-part-2-pseudo-code-and-batch-jobs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fundamentals of Programming: Part 1 &#8211; Introduction</title>
		<link>http://www.geekscribes.net/blog/2012/02/04/fundamentals-of-programming-part-1-introduction/</link>
		<comments>http://www.geekscribes.net/blog/2012/02/04/fundamentals-of-programming-part-1-introduction/#comments</comments>
		<pubDate>Fri, 03 Feb 2012 21:02:40 +0000</pubDate>
		<dc:creator>InF</dc:creator>
				<category><![CDATA[Fundamentals]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tech Posts]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.geekscribes.net/blog/?p=1706</guid>
		<description><![CDATA[Hello there! Welcome to my Fundamentals of Programming series of post. In this series, I will teach you about the basics of programming, i.e. the building blocks and what makes a program tick. I will NOT teach you Java, C++, PHP, Python or whatever pretty language you can think of. Instead, I&#8217;ll keep it language-independent [...]<p>This article comes from <a href="http://www.geekscribes.net/blog">GeekScribes</a><br/><br/><a href="http://www.geekscribes.net/blog/2012/02/04/fundamentals-of-programming-part-1-introduction/">Fundamentals of Programming: Part 1 &#8211; Introduction</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Hello there! Welcome to my Fundamentals of Programming series of post. In this series, I will teach you about the basics of programming, i.e. the building blocks and what makes a program tick. I will <span style="font-size: medium;"><strong>NOT</strong></span> teach you Java, C++, PHP, Python or whatever pretty language you can think of. Instead, I&#8217;ll keep it language-independent so that even a complete beginner to programming will be able to follow.</p>
<p><span id="more-1706"></span></p>
<p>I don&#8217;t know how many parts there will be and I don&#8217;t know if I&#8217;ll have time to write about everything I can think of at the moment.</p>
<p>Here is what I intend to cover. I may add other things afterwards:</p>
<ol>
<li>What is programming? Questions and IDEs</li>
<li>Algorithms, Pseudo Code, Batch Jobs</li>
<li>Style, Indentation and Comments</li>
<li>Variables and Arrays</li>
<li>Data Types</li>
<li>Conditions</li>
<li>Loops</li>
<li>Errors and Bugs</li>
<li>Functions</li>
<li>Classes</li>
<li>Libraries and Plugins</li>
<li>Syntax and Programming Languages</li>
<li>In Real Life</li>
</ol>
<p>So please stick around and I hope you will enjoy reading my series of posts. Of course, your comments, questions and suggestions are welcome. I&#8217;d really like if my programmer friends, contacts and anonymous readers out there would provide some inputs in these posts to help beginners.</p>
<p>Without further delays, let&#8217;s start.</p>
<h2>What is programming?</h2>
<p>That.</p>
<p style="text-align: center;"><img class="size-full wp-image-1708" title="Java Codes" src="http://www.geekscribes.net/blog/wp-content/uploads/2012/02/fd_java.jpg" alt="" width="516" height="322" /></p>
<p style="text-align: left;">Ugh! What are all those brackets?! What are those awful colors! Public WHAT?! My brain is melting!</p>
<p>Keep calm! Breath in. Breath out. Are you alright? Fine. Don&#8217;t worry about this at the moment. You&#8217;ll understand more as we go along so just be patient. At least, be positive! It&#8217;s in English!</p>
<p>Programming is basically giving instructions to a computer so that knows how to accomplish some task. Why would you need that? Well, everything you do on your computer, you&#8217;re doing it through programs. You&#8217;re currently viewing this page through a program that allows you to view webpages. You are using a program that gives you an environment to run other programs. Everything is a program. You are in the Matrix. Haha.</p>
<p>Well yes, programs are everywhere. And guess what? Each of these programs were written in some programming language. That thing you just saw above? That was a programming language. That&#8217;s what is used to make programs. That is, the &#8220;Firefox&#8221; or &#8220;Internet Explorer&#8221; or &#8220;Safari&#8221; or &#8220;Chrome&#8221; etc you are using to view this page at the moment? It was written in a language that resembles that one above.</p>
<p>Programming is writing programs in some language. There you have it.</p>
<p>&nbsp;</p>
<h2>Why do we need programming?</h2>
<p>Simple! To make your computer understand what to do or what you want it to do. There&#8217;s a difference in that and we&#8217;ll see about it a bit later.</p>
<p>Computers are generally dumb machines of metal, silicon, plastic and lots of tiny little stuff that beep, light up and do other wonderful things. But they don&#8217;t really understand English. They only work with 2 numbers: zeroes and ones.</p>
<p>Programming is you telling it instructions, but you have to tell the instructions in some language the computer understands. If you think you have to write in zeroes and ones, you&#8217;d be correct but not completely.</p>
<p>Programming in zeroes and ones was done at the very start. It was hard as hell because, well, do you think something like 01001100 is meaningful to a human? Nope.</p>
<p>Some person thought it would be a good idea to translate some of those codes into meaningful words and have the computer translate this language into its zeroes and ones.</p>
<p>That person hence created a program that converts English words like &#8220;if&#8221; into computer-meaningful things like 01001100. Nowadays, you write English and your computer figures the rest out for you after you click a few buttons here and there. Then you see your shiny new program running and you&#8217;re happy.</p>
<p>This translation process, if you wish to know, is called &#8220;compilation&#8221;. There&#8217;s also &#8220;interpretation&#8221;. Both are basically translations, but compilation is done all-at-once while interpretation is done as-you-go.</p>
<p>&nbsp;</p>
<h2>How many languages are there?</h2>
<p>Too many. Estimate? <a  title="List of Programming Languages on Wikipedia" href="http://en.wikipedia.org/wiki/List_of_programming_languages" target="_blank">Above 4500</a>. Be scared.</p>
<p>&nbsp;</p>
<h2>Waaait what?! How can I learn all that?!</h2>
<p>You&#8217;re not supposed to. You&#8217;ll probably be fine learning one of them and you can write nice little programs. But why do we need so many languages? That&#8217;s because languages are created for specific tasks. For e.g. PHP is used to create dynamic web sites. That is, the web pages react to things you do, instead of being just boring, static, non-changing pages.</p>
<p>Other languages are for other things for e.g. C++ is used when there&#8217;s need for high speed of execution i.e. the program should run fast.</p>
<p>&nbsp;</p>
<h2>So how do I get started?</h2>
<p>Well, you could read books on some language you want to learn. But if you don&#8217;t understand programming itself, it&#8217;s pretty much pointless to do that. Did you learn English by reading Shakespeare? OMG FOR REAL?!</p>
<p>Nah you probably started by learning letters. And made a mess on walls everywhere. Then you learnt words. Swear words I bet. Then you created sentences. Then you wrote your first paragraph etc etc until at the end, you can finally understand English pretty well.</p>
<p>Programming is like that too. You have to start from the start. What is the start? Letters.</p>
<p>Not really. Programming languages are mostly in English. Mostly. There are some truly weird things out there. But yes, mostly English. So you already have a head start. What you need to learn are the words actually. And that&#8217;s what this series of posts will try to teach you about.</p>
<p>You&#8217;re not expected to be able to write codes at the end of the series. That will probably be for another series some time later. But at the end, I hope you&#8217;ll be able to read a program and able to think about how to write your own program.</p>
<p>I&#8217;ll make sure to use plenty of examples while writing so you get to know how programmers think when they are confronted with a solution.</p>
<p>&nbsp;</p>
<h2>Is there any special equipment I need?</h2>
<p>Not really. All you need is a working, powered-on computer, keyboard, mouse, screen and an Internet connection. Since you&#8217;re here reading this, you&#8217;re all fine.</p>
<p>Ironically, you&#8217;ll be using programs to write programs. Interesting huh? First programs were actually &#8220;written&#8221; using punch cards so these were not really programs. Then after a whole lot of troubles and annoyances, we arrived at the languages we use today. Be happy you don&#8217;t have to program in binary. Zeroes and Ones, if you didn&#8217;t know what binary (2 numbers) means.</p>
<p>Programmers do use a number of tools to facilitate their task. You can use &#8220;Notepad&#8221;, that simple text-writing program in Windows that nobody likes. Love it, it&#8217;s a nice program. If you&#8217;re  using Mac or Linux or some other operating system, just find a text editor and use it.</p>
<p>When you become more familiar and get more powerful (HAR!), you&#8217;ll want to use more capable tools. We call these &#8220;Integrated Development Environments&#8221; (IDEs). Fancy term for &#8220;big program that allows me to write big programs&#8221;. It&#8217;s still a sort of Notepad. Just one on steroids.</p>
<p>You don&#8217;t need to bother about any of these for the moment, although you may want to check out Notepad since it makes writing the basic codes I&#8217;ll show you WAY easier.</p>
<p>&nbsp;</p>
<p>Alright, that&#8217;s it for part 1, the Introduction. In the next part, we&#8217;ll move on to how programs are born. See you! If you have questions and comments, use the form below.</p>
<p>&nbsp;</p>
<h3>In the same series:</h3><ul class="eg-series-posts" ><li class="eg-series-posts-item "><span class="eg-series-post-title"><a  href="http://www.geekscribes.net/blog/2012/02/07/fundamentals-of-programming-part-3-style-indentation-and-comments/" title="Fundamentals of Programming: Part 3 - Style, Indentation and Comments">Fundamentals of Programming: Part 3 - Style, Indentation and Comments</a></span> </li><li class="eg-series-posts-item "><span class="eg-series-post-title"><a  href="http://www.geekscribes.net/blog/2012/02/05/fundamentals-of-programming-part-2-pseudo-code-and-batch-jobs/" title="Fundamentals of Programming: Part 2 - Pseudo Code and Batch Jobs">Fundamentals of Programming: Part 2 - Pseudo Code and Batch Jobs</a></span> </li><li class="eg-series-posts-item current"><span class="eg-series-post-title">Fundamentals of Programming: Part 1 - Introduction</span> <span class="eg-series-post-this">(This post)</span></li></ul>
<p>&nbsp;</p>
<p>Sources:</p>
<p><a  title="ECLIPSE IDE Java Demonstration - NCEAS" href="http://www.nceas.ucsb.edu/files/scicomp/EclipsePres/EclipseJava.html" target="_blank">Picture</a></p>
<p>This article comes from <a  href="http://www.geekscribes.net/blog">GeekScribes</a><br/><br/><a  href="http://www.geekscribes.net/blog/2012/02/04/fundamentals-of-programming-part-1-introduction/">Fundamentals of Programming: Part 1 &#8211; Introduction</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.geekscribes.net/blog/2012/02/04/fundamentals-of-programming-part-1-introduction/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Lessons 9: Session and Cookies</title>
		<link>http://www.geekscribes.net/blog/2010/03/19/php-lessons-9-session-and-cookies/</link>
		<comments>http://www.geekscribes.net/blog/2010/03/19/php-lessons-9-session-and-cookies/#comments</comments>
		<pubDate>Fri, 19 Mar 2010 09:34:20 +0000</pubDate>
		<dc:creator>Guest-GS</dc:creator>
				<category><![CDATA[PHP Lessons]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[How To]]></category>
		<category><![CDATA[Lessons]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.geekscribes.net/blog/?p=780</guid>
		<description><![CDATA[Hello there, back with some PHP lessons. It&#8217;s been quite a while. Got loads of projects to deal with at work and wasn&#8217;t feeling like typing codes at home. This lesson will deal about session ($_SESSION) and cookies ($_COOKIES)&#8230;(This kind of cookie has nothing to do with cookies our grand-mother used to cook for us [...]<p>This article comes from <a href="http://www.geekscribes.net/blog">GeekScribes</a><br/><br/><a href="http://www.geekscribes.net/blog/2010/03/19/php-lessons-9-session-and-cookies/">PHP Lessons 9: Session and Cookies</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Hello there, back with some PHP lessons. It&#8217;s been quite a while. Got loads of projects to deal with at work and wasn&#8217;t feeling like typing codes at home.</p>
<p>This lesson will deal about session ($_SESSION) and cookies ($_COOKIES)&#8230;(This kind of cookie has nothing to do with cookies our grand-mother used to cook for us <img src='http://www.geekscribes.net/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  )</p>
<p><span id="more-780"></span></p>
<p><strong>SESSIONS:</strong></p>
<p><strong>What are session and how can they be useful?</strong></p>
<p>Sessions in PHP are meant to keep track and store data for a particular user while they browse our site or pages. For example, with a login system, when the user logs in, PHP must have a way to keep track of the user&#8217;s status and with this kind of info, we can allow registered user to access private areas and so on. We can also store other data like what time they logged on, and show messages like: &#8220;You&#8217;ve been here for X minutes&#8221;.</p>
<p>When you start a SESSION, a random Session Id is stored in a COOKIE and the default name is PHPSESSID. Yes, even if it&#8217;s a SESSION, the value is also stored in a COOKIE an placed on your computer. The advantage of SESSION is, even if the user has cookies disable on his browser, SESSION will still keep track of user info, because, SESSION not only adds PHPSESSID to a cookie, but all values you assign to a SESSION, are also stored in a file on your server.</p>
<p><strong>How do we start a SESSION?</strong></p>
<p>The answer is simple, you just have to add this line on code on top of your page, before any html or php code whatsoever. It HAS to be at the very top, else you can get error messages.</p>
<pre>&lt;?php
    session_start();

    //other stuff below
?&gt;
</pre>
<p>Author&#8217;s note : Sometimes, when declaring session_start(), you might get a fancy notice which will drive you crazy. I will tell you about it later in this chapter.</p>
<p>Let&#8217;s try something with SESSION. We will declare a SESSION, assign a value to it, and retrieve the value. Code&#8217;s below:</p>
<pre>&lt;?php
     session_start(); 

     $_SESSION['view'] = 1; // assign value to session
     echo "Pageviews = ". $_SESSION['view']; //retrieving the value
?&gt;
</pre>
<p>Let&#8217;s analyze this,</p>
<p>1) We declared our session on top of everything.<br />
2) we assigned the value of 1 to the SESSION array at position &#8220;view&#8221;: $_SESSION['view']. We hence called the SESSION, &#8220;view&#8221;. Yep, $_SESSION is just an array!<br />
3) We echo out the value of the SESSION.</p>
<p>If you run this code, it will print 1. Cool huh?</p>
<p>With this, we can determine how many times a page has been viewed. The code below:</p>
<pre>&lt;?php
    session_start();  //declare session

    if(isset($_SESSION['view']))
       $_SESSION['view'] = $_SESSION['view']  + 1;

    else
       $_SESSION['view'] = 1;

   echo 'You viewed this page '. $_SESSION['view'].' times.';
?&gt;   
</pre>
<p>This one looks a bit different, we added a condition to check the value of our SESSION.</p>
<p>First, if the session is already set (isset()), We just add 1 to it. According to our condition here, if it&#8217;s there, lets just increment it, else we default the value to one.</p>
<p>If you try this code, keeps refreshing your page, and you will see the numbers increasing in value as you refresh.</p>
<p>As you already noticed by now, $_SESSION is also an Array.</p>
<pre>&lt;?php
   session_start();

   $_SESSION['firstname']   = 'John'; // Assign value to session called firstname. (Hello again, Mr. John!)
   $_SESSION['lastname']    = 'Dingo';
   $_SESSION['age']         = '18';
   $_SESSION['location']    = 'Mauritius';
   $_SESSION['sex']         = 'Male';

   echo '&lt;pre&gt;';
      print_r($_SESSION);
   echo '&lt;/pre&gt;';
?&gt;</pre>
<p>Try the code above, it will print an array of the $_SESSION we declare, and yes, it will echo ALL the session we declare, including the view $_SESSION from before. But now, why is it echoing out a $_SESSION that we didn&#8217;t declare in the script above? Well, remember, SESSION are being stored on a file on your server. The $_SESSION called &#8220;view&#8221; is still in there and we are looking at a complete Array of all SESSIONS that has been set.</p>
<p>How do we get rid of this view SESSION then?</p>
<p>In order to achieve this, we have to unset the session view. The name says it all because the built-in function we are going to use is called : unset();</p>
<p>Try the code below:</p>
<pre>&lt;?php
   session_start();

   $_SESSION['firstname']  = 'John'; // You again, Mr. John?
   $_SESSION['lastname']   = 'Dingo'; //
   $_SESSION['age']        = '18';
   $_SESSION['location']   = 'Mauritius';
   $_SESSION['sex']        = 'Male';

   unset($_SESSION['view']); //gets rid of the view 

   echo '&lt;pre&gt;';
      print_r($_SESSION);
   echo '&lt;/pre&gt;';
?&gt;
</pre>
<p>Refresh your page and TADA! the $_SESSION called view is gone. Now, since $_SESSION is an array. We can use the foreach() loop as well as the for() loop to deal with Multidimensional Arrays. <img src='http://www.geekscribes.net/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Let&#8217;s experiment. Code below:</p>
<pre>&lt;?php
    session_start();

    $_SESSION['msg'] = array(); //We assign our message session as an empty array;

    $_SESSION['msg']['msg_one'] = 'Hello this is message one.';
    $_SESSION['msg']['msg_two'] = 'Hello this is message two.';
    $_SESSION['msg']['msg_three'] = 'Hello this is message three.';

    echo $_SESSION['msg']; // This will only output Array to our browser. So we don't see any values

    echo '&lt;hr /&gt;';

    if(is_array($_SESSION['msg'])){
       foreach($_SESSION['msg'] as $myMsg){
          echo $myMsg.'&lt;br /&gt;';
       }        
    }

?&gt;
</pre>
<p>As you can see here, when we  echo $_SESSION['msg'];, it only outputs Array to our browser. We need to access the data in this array. Remember the foreach loop? It comes in handy there, we are iterating over the Array and outputting it&#8217;s value. The results will look like this:</p>
<pre>Hello this is message one.</pre>
<pre>Hello this is message two.</pre>
<pre>Hello this is message three.
</pre>
<p>You will notice a new little function called is_array(). This is a built-in function that checks if the argument being pass in an array. This function returns true or false, in our case, it will return true since $_SESSION['msg'] was set as an array to begin with.</p>
<p>Sometimes, these built-in functions comes in handy especially when you&#8217;re dealing with dynamically generated data.</p>
<p>You can start a session, but you can also destroy a session. Yes, you can. How?</p>
<p>Just by adding session_destroy() in your script.</p>
<p>Note that, when you close all your browsers, the session is automatically destroyed or cleared if you prefer. But some browsers like Mozilla Firefox sometimes asks you if you would like to save data before closing, if you choose yes, then I believe all the SESSIONS are preserved.</p>
<p>Earlier, i told about session_start() generating an ugly PHP Notice. This is true. Even if it&#8217;s a built-in function. How come? Well, let me explain something. In your PHP Configuration (php.ini file), there a line which says:</p>
<pre>session.auto_start = 0 or session.auto_start = 1
</pre>
<p>What this means is, when &#8216;session.auto_start = 1&#8242;, PHP has the power to start a session for you automatically, without you having to put session_start() at top of your script and if it is 0, then you will have to add session_start() at top of your script. PHP starting a session automatically for me. Cool huh? Not so quick pals, this can cause some serious damage later. Follow on.</p>
<p>Let&#8217;s assume the server your using right now, has session.auto_start set to 1. With this, you might say, ok, PHP is doing it for me, so I won&#8217;t bother adding session_start() in my script. But, what if you move your site on another server, and this another server PHP configuration has session.auto_start set to 0? That means your scripts won&#8217;t work and you will get some ugly error messages and yes YOU will have to go in your scripts and add session_start() everywhere where your scripts are using session.</p>
<p>Now, since we are good programmers, we must find a way to make our scripts cross-server. Bypassing this problem is actually quite easy. When a session is declared, a session_id is being generated. Remember, I told you that at the beginning of the lesson? In PHP, you can check if a session_id exist. We use the session_id() built-in function. With this, we can make a condition to bypass our problem. Code below:</p>
<pre>&lt;?php
   if(!session_id()) { session_start(); }

   $_SESSION['msg'] = array(); //We assign our message session as an empty array;

   $_SESSION['msg']['msg_one'] = 'Hello this is message one.';
   $_SESSION['msg']['msg_two'] = 'Hello this is message two.';
   $_SESSION['msg']['msg_three'] = 'Hello this is message three.';

   echo $_SESSION['msg']; // This will only output Array to our browser. So we don't see any values

   echo '&lt;hr /&gt;';

   if(is_array($_SESSION['msg'])){
      foreach($_SESSION['msg'] as $myMsg){
         echo $myMsg.'&lt;br /&gt;';
?&gt;
</pre>
<p>Have a look at the very first line in the code above. The condition says, if there&#8217;s no session_id, then we use the session_start. This will get rid of the pain <img src='http://www.geekscribes.net/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . I strongly advise that you use this method when starting a session. Believe me, it will save you some time later.</p>
<p>That&#8217;s it for $_SESSION. Moving on with $_COOKIES.</p>
<p><strong>Cookies</strong></p>
<p>Unlike the cookies we used to eat, this one is a bit tricky and less tasty, and the syntax is different from SESSION. We don&#8217;t start a cookie, we SET a cookie. I believe you all know what browser Cookies are. It&#8217;s a way to store data on the users computer in small files.</p>
<p>When a website places a cookie on your PC, it&#8217;s to determine wether you have been on this site recently. Usually when you login on a website, there&#8217;s a checkbox which says &#8220;Remember Me&#8221;, if you check it, the script will place a cookie on you computer, after two days, when you go to that same site, the script will check if a cookie exist, if it is, you won&#8217;t have to login again, you&#8217;re already logged in. Cool huh .. The syntax for COOKIE is below:</p>
<pre>setcookie(name, value, expire, path, domain, secure); 

name     = the name of the cookie
value    = the value of the cookie
expire   = the amount of time the cookie will remain alive
path     = which path on your server you want the cookie to be accessible
domain   = the domain that the cookie is available
secure   = Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client.
</pre>
<p>Below is an example of how to work with cookie:</p>
<pre>&lt;?php

    if(isset($_COOKIE['username'])){
       echo "You were there recently ".$_COOKIE['username']." Nice to have you back pal";
    }
    else{
       echo "Hi, you're new here. What is you name?";
       setcookie('username','John',time()+3600,'/');
    }

?&gt;</pre>
<p>In the code above, we first make a condition to see if a $_COOKIE name &#8216;username&#8217; was set. If it was, then it means the user was here recently. Else, it&#8217;s his first time, so we show him a message stating that his new, and then, we set a cookie using the setcookie function.</p>
<p>We named our cookie username, we gave it a value of John ( In this example, the value can be anything ), then we set the expire time, in our case, the cookie will expire in 1 hour (in seconds, 1 hour = 3600 seconds). The last parameter is the path; I want this cookie to be accessible everywhere on my server. After expiry, it means the cookie is no longer valid. If the user returned after say, 5 hours, he&#8217;ll get the message destined to new users. This is useful when you have checkboxes like &#8220;Remember me for a day&#8221;. Set the expiry of the cookie to one day, and you&#8217;re done.</p>
<p>You will notice that I omitted the domain and secure parameter, it is optional.</p>
<p>If you run the code, you will get: <strong>Hi, you&#8217;re new here. What is you name?</strong>&#8230; and a cookie will be set.</p>
<p>But if you refresh it again, you will get: <strong>You were here recently John. Nice to have you back pal!</strong>, since our condition saw a cookie named &#8220;check&#8221;.</p>
<p>Remember, John is the value of our cookie, that&#8217;s why we get his name in th first if statement.</p>
<p>To get an entire $_COOKIE Array, just run the code below:</p>
<pre>&lt;?php

   echo '&lt;pre&gt;';
   print_r($_COOKIE);
   echo '&lt;/pre&gt;';

?&gt;
</pre>
<p>You might get a big Array along with a bunch of values, depending on how many sites has a cookie on your PC <img src='http://www.geekscribes.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Now that we know how to set a cookie, but how do I delete the cookie? Interesting question. Unlike SESSION, a cookie cannot be delete using the unset() function, neither exist a built-in function call destroy_cookie(). You can&#8217;t go on deleting files on the user&#8217;s machine, can you?</p>
<p>To delete a cookie, you simply set the expire time in the past.:</p>
<p>Code below:</p>
<pre>&lt;?php

   if(isset($_COOKIE['username'])){
      setcookie('username','john',time()-3600,'/');
      echo 'Cookie has been deleted.';
   }

   echo '&lt;pre&gt;';
      print_r($_COOKIE);
   echo '&lt;/pre&gt;';
?&gt;
</pre>
<p>In our if statement, have a look at the setcookie function and analyze the parameters, something has changed. Notice the time()-3600 . Before we did time()+3600. But we wanted to erase it, so we defined the time 1 hour in the past. This will get rid of the cookie. Have a look at the Array, you will notice that John isn&#8217;t there anymore. He&#8217;s gone. Poor guy. He&#8217;ll be back, don&#8217;t worry.</p>
<p>Cool, we know how to set a cookie. But what about that time() function you keep talking about?</p>
<p>Well, PHP allows you to work with time. The function time() doesn&#8217;t actually return something like 19:50:23. Instead,it returns the current time as a UNIX TimeStamp (the number of seconds since January 1 1970 00:00:00 GMT). This is used as a reference time point to know much time elapsed. It&#8217;s the computer&#8217;s way of asking: &#8220;How long has it before you have eaten?&#8221;. So you figure out when you last ate, check what time it is now, and do a substraction and say, &#8220;5 mins ago&#8221;.If you echo time(), you will get something similar to this:</p>
<pre>1268422287</pre>
<p>Yes,a bunch of numbers. What the hell is that? That&#8217;s how a computer knows &#8220;Now&#8221;. 7 seconds ago would be:</p>
<pre>1268422280</pre>
<p>I want a good formatted time. Ok, to compensate for the delay of the PHP Lessons, I will show you some examples of how you can format a date and time using the number of seconds return by time(). The time() function, doesn&#8217;t take any parameters. In order to get a nice format of the date and time. We should use the date() function in addition with the time() function. Example below:</p>
<pre>&lt;?php
   echo 'Current time is : '. date('Y-m-d H:i:s',time()); // outputs Current time is : 2010-03-12 23:35:40
?&gt;
</pre>
<p>This code will give you the current time. Well, depending on your server, you might get a time 4 hours earlier than that. If that&#8217;s the case, to get the current time, you will need to offset your date() function. Example below:</p>
<pre>&lt;?php
   echo 'Current time is : '. date('Y-m-d H:i:s',time() + 14400);
?&gt;
</pre>
<p>You already noticed, we added 14400 with the time() function. Why 14400? Little maths below:</p>
<pre>1 minutes           = 60 seconds, So
1 hour              = 60 minutes, So to get the numbers of seconds in 1 hour, we do
1 hour in seconds   = 60 seconds * 60 minutes which = 3600

Now we know 3600 seconds equals 1 hour.
To get an offset of 4 hours, we multiply 3600 by 4. The result is 14400.
</pre>
<p>Next we add it to our time() function. Isn&#8217;t PHP great?</p>
<p>To get a list of available format of date and time, I strongly suggest you visit this link : http://php.net/manual/en/function.date.php.</p>
<p>While i&#8217;m at my little &#8216;compensating for the delay of lesson&#8217;, let&#8217;s go back in the past where we used to talk about user defined function.</p>
<p>This is a bonus for you.</p>
<p>When we create our own function, we can pass in arguments, as many as we want. What if one day, our function requires unlimited number of arguments? Supposed some numbers are being returned from a database, we want to make some maths or whatever with those numbers, and it so happens we are getting about 1000 rows of numbers. Are we going to write a function that takes 1000 arguments? If you have the time to type all that, then good luck. But instead of typing, let me show you how to create a function of your own, that can take unlimited amounts of args.</p>
<pre>&lt;?php
   function unlimitedArgs(){

      $arguments = func_get_args(); // returns an array of arguments passed to the function when calling it

      foreach($arguments as $args){
         return array_sum($args);
      }
   }

   $someArray = array(1,2,3,4,5);

   echo unlimitedArgs($someArray);

?&gt;
</pre>
<p>Let&#8217;s analyze, first, for a beginner, things looks weird, because we are creating a function that doesn&#8217;t take any arguments, and yet, when we call that function, we are passing an array as it&#8217;s arguments. Have a look at the function, we have this line:</p>
<pre>$arguments = func_get_args();
</pre>
<p>func_get_args() returns an array of any arguments passed to the function even if we didn&#8217;t supply it when created the function itself. This way, we can pass as many arguments as we want. In our example, our argument is an array containing numbers. Our function simply iterates over the array of arguments created by func_get_args, then we use the array_sum function to sum up all the values in the array. Our result is 15.</p>
<p>array_sum(Array) simply sum all the values in the given array.</p>
<p>Ok, I believe this is it for this lesson. If you didn&#8217;t understand the last part, comments are open for questions! <img src='http://www.geekscribes.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Nice reading.</p>
<h3 style="text-align: center;">This article was contributed by Tipa of <a  title="Mu-Anime: Tipa's Site" href="http://www.mu-anime.com/" target="_blank">Mu-Anime</a></h3>

<p>This article comes from <a  href="http://www.geekscribes.net/blog">GeekScribes</a><br/><br/><a  href="http://www.geekscribes.net/blog/2010/03/19/php-lessons-9-session-and-cookies/">PHP Lessons 9: Session and Cookies</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.geekscribes.net/blog/2010/03/19/php-lessons-9-session-and-cookies/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>PHP Lessons 8: Server Constants and HTML Forms</title>
		<link>http://www.geekscribes.net/blog/2009/12/10/php-lessons-8-server-constants-and-html-forms/</link>
		<comments>http://www.geekscribes.net/blog/2009/12/10/php-lessons-8-server-constants-and-html-forms/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 14:49:56 +0000</pubDate>
		<dc:creator>Guest-GS</dc:creator>
				<category><![CDATA[PHP Lessons]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[How To]]></category>
		<category><![CDATA[Lessons]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.geekscribes.net/blog/?p=760</guid>
		<description><![CDATA[Hello there, it&#8217;s been a while, I&#8217;ve been very busy with work and some personal project, so i had to delay the PHP courses, but anyway, I&#8217;m back and today we&#8217;ll have a look at Server Constants. Take a look at www.geekscribes.net, on the right side, we have a search form, when you type in [...]<p>This article comes from <a href="http://www.geekscribes.net/blog">GeekScribes</a><br/><br/><a href="http://www.geekscribes.net/blog/2009/12/10/php-lessons-8-server-constants-and-html-forms/">PHP Lessons 8: Server Constants and HTML Forms</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Hello there, it&#8217;s been a while, I&#8217;ve been very busy with work and some personal project, so i had to delay the PHP courses, but anyway, I&#8217;m back and today we&#8217;ll have a look at Server Constants.</p>
<p>Take a look at www.geekscribes.net, on the right side, we have a search form, when you type in a search keyword and press Enter, the page loads and it fetch every results according to what you typed. Ever wonder how it works? Don&#8217;t go any further, today I will show you bring a boring html form to life.</p>
<p>Before I start, if you missed the array tutorials, then please, go to the link below, and read the post, give it a try.. because you&#8217;ll need to understand how arrays work in order to understand this lesson fully.</p>
<p><span id="more-760"></span></p>
<p>Here&#8217;s the link:</p>
<p><a  title="PHP Lessons on Arrays @ Geekscribes" href="http://www.geekscribes.net/blog/2009/08/11/php-lessons-arrays/" target="_blank">http://www.geekscribes.net/blog/2009/08/11/php-lessons-arrays/</a></p>
<p>So let&#8217;s begin.. Server Constants are also called Predefined Variables, which are just arrays in fact. I will list some of them, but today, we&#8217;ll have a look at two of them..Below is a list:</p>
<pre>$_SERVER:     This grabs almost all information about the server your website resides on.

$_GET:        The HTTP GET variables are in there

$_POST:       HTTP POST Variables (Very useful with forms)

$_FILES:      Used with forms also, but only for upload purposes. LIke uploading files to a server. Think Rapidshare.

$_REQUEST:    HTTP Request variables (We can say it is a mix of $_GET and $_POST.
              But don't rely on it too much. The only way to rely on it is to use the function array_map() ).
              Also, it's a bit unsecured to use this one, so avoid!

$_SESSION:    Session Variables
              (This is a handy built-in function use to store data. Like Username, Password, User Clicks.
              It can be useful, but can be hard to understand).

$_COOKIE:     HTTP Cookies.
              (This is use to store information on your computer. Like which preference you choosed for a website.
              Or if you checked Remember Me when logged in, a cookie is set on your computer.)</pre>
<p>We&#8217;ll deal with $_SESSION and $_COOKIE in a later lesson, so no worries. <img src='http://www.geekscribes.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Today, we&#8217;ll have a look at $_GET and $_POST..and in order for you to understand, we will use an HTML Form to send a Request to the server.. Now, what is &#8220;send Request to the server&#8221;? Basically, you are making a request for a resource from the server, or are sending something to it. Whatever you put in a form is sent to the server in a special message (or request). The server can then use this to determine what you want and what to do.</p>
<p>There are two methods of sending requests, namely GET and POST. When you use GET, whatever data to be sent is passed in the URL (or action) if the form, in plain text. Using POST, the data is sent in the background making the transfer invisible to the user. Following logic, you won&#8217;t be sending login information via GET since the password would be visible in the address bar in plain text. For this, you&#8217;ll use POST. For other uses, such as getting an item&#8217;s price, GET is perfectly acceptable.</p>
<p>Note, if no value is specified for the action attribute, it means that the page refers to itself. If the page is &#8220;test.php&#8221;, it&#8217;s as if action was set to &#8220;test.php&#8221;. Also, if you don&#8217;t set a method, by default it&#8217;s &#8220;GET&#8221;. So beware if you&#8217;ll be using it to send passwords etc.</p>
<pre>&lt;form method="post" action="name.php"&gt;
   &lt;label for="name"&gt;Type your name&lt;/label&gt;
   &lt;input type="text" name="name" /&gt;
   &lt;input type="submit" name="submit" value="Output my name" /&gt;
&lt;/form&gt;</pre>
<p>Ok, i won&#8217;t go through all this, you should at least have a fair knowlegde of HTML if you are studying PHP, but what I will point out is, the part where it says &#8221; &lt;form method=&#8221;post&#8221; action=&#8221;name.php&#8221;&gt; &#8221;</p>
<p>The &#8220;method&#8221; attribute in the form tag is set to post, which means we are going to use POST ( $_POST for php ) and the page to process the code is the same where our form lives, which is set in the &#8220;action&#8221; attribute of the form tag, so it&#8217;s set to nothing, which means, use the same page as our form, the PHP Code will be in the same page.</p>
<p>Ok, let&#8217;s make a test. Fire up your code editor or use the old notepad, and type that in a file, say &#8220;test.php&#8221;. It HAS to end in .php, not .html or .htm, even if it includes HTML codes. If it doesn&#8217;t end in .php, it won&#8217;t get pre-processed, and you&#8217;ll just see your PHP code in plain text.</p>
<pre>&lt;?php</pre>
<pre>  if(isset($_POST['submit']))
  {
     echo "&lt;pre&gt;";
     print_r($_POST);
     echo "&lt;/pre&gt;";
  }</pre>
<pre>?&gt;</pre>
<pre>&lt;form method="post" action=""&gt;
   &lt;label for="name"&gt;Type your name&lt;/label&gt;
   &lt;input type="text" name="name" /&gt;
   &lt;input type="submit" name="submit" value="Output my name" /&gt;
&lt;/form&gt;</pre>
<p>Type in your name in the input box, press enter and see the results.. My output was like this:</p>
<pre>Array
(
   [name] =&gt; Kevin
   [submit] =&gt; Output my name
)</pre>
<p>print_r is a function in PHP that allows you to display the contents of an array, in key-value pairs. Here, we are printing the $_POST array. I did say these are just arrays with form data stored in them. <img src='http://www.geekscribes.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>The output therefore means:</p>
<p>Name: is the name of the field in our form. The text-box was called &#8220;name&#8221;<br />
Submit: is the name of the submit button ( Note: We can get rid of it from our array)</p>
<p>Note that &#8220;Output my name&#8221; is given as the value for submit. The value attribute of a submit input type is what&#8217;s displayed on the button in HTML.</p>
<p>Now that we know what&#8217;s stored in our POST Array, we can easily output it. We can acess it through the $_POST array. Like below:</p>
<pre>&lt;?php</pre>
<pre>  if(isset($_POST['submit']))
  {
     echo "My name is ". $_POST['name'];
  }</pre>
<pre>?&gt;</pre>
<pre>&lt;form method="post" action=""&gt;
   &lt;label for="name"&gt;Type your name&lt;/label&gt;
   &lt;input type="text" name="name" /&gt;
   &lt;input type="submit" name="submit" value="Output my name" /&gt;
&lt;/form&gt;</pre>
<p>So the code first check if the form has been submited:</p>
<pre>if(isset ($_POST['submit']) )</pre>
<p>If the array key named &#8220;submit&#8221; has a value (any value) set, then process the codes inside of the IF statement.</p>
<p>$_POST['name'], simply because, in our HTML FORM, the input where you typed your name, has the name attribute set to &#8220;name&#8221;. If you have another field, say, age. You would type $_POST['age'] to access it.</p>
<p>It&#8217;s all about arrays. You can also interact with it using a foreach loop. Most array operations in PHP could theoretically be performed on those $_GET, $_POST, &#8230; variables.</p>
<p>Now for the $_GET constant, unlike $_POST, the value is sent through the URL.</p>
<p>The form method is set to get instead of post! Try the code below, then look at your URL in the address bar</p>
<p>&lt;?php</p>
<pre>  if(isset($_GET['submit']))
  {
     echo "My name is ". $_GET['name'];
  }</pre>
<pre>?&gt;</pre>
<pre>&lt;form method="get" action=""&gt;
   &lt;label for="name"&gt;Type your name&lt;/label&gt;
   &lt;input type="text" name="name" /&gt;
   &lt;input type="submit" name="submit" value="Output my name" /&gt;
&lt;/form&gt;</pre>
<p>You will notice that your URL is now :</p>
<pre>http://localhost/test.php?<strong>name=Kevin</strong>&amp;<strong>submit=Output+my+name</strong></pre>
<pre>test.php:            This is the page we are using right now
test.php?name=kevin: This is the fun part. The ?name=&lt;name&gt;, is called a Query String, name is the $_GET Variable, and "kevin" is the value assigned to that variable.</pre>
<p>The query strings are separated from the domain by a &#8220;?&#8221; and are separated by ampersands. Spaces are substituted with &#8220;+&#8221; symbols. Note, there is a maximum length on the URL length, and hence the amount of data that can be sent via GET. So if you have to send a ton of data, use POST.</p>
<p>Another advice is don&#8217;t use multi-word names separated by spaces for the &#8220;name&#8221; attribute of fields. You don&#8217;t want to see: &#8220;?<strong>my+name</strong>=John+smith&#8221; in the URL. Then in PHP, you&#8217;d do $_POST['<strong>my_name</strong>'] as the space became an underscore. A whole lot of headaches! So don&#8217;t do it! For the sake of fellow programmers.</p>
<p>test.php?name=kevin&amp;submit=Output+my+name : the Submit is just the name of the submit button, you shouldn&#8217;t care about that too much</p>
<p><strong>IMPORTANT Notice: </strong>When using the $_GET Method, NEVER, and I mean NEVER use password field with it. Use $_POST when you form contains password field. Unless of course you want the whole world to see your password is in fact &#8220;password&#8221; :p</p>
<p>One thing you can try is, use the $_SERVER variable to check what the Actual URL Query string is set to. Try the code below:</p>
<pre>&lt;?php
if(isset($_GET['submit']))
  {
     echo "My name is ". $_GET['name'];
     echo "&lt;hr /&gt;"; //&lt;hr /&gt; just makes a horizontal rule (line) appear.
     echo "The URL Query String is ". $_SERVER['QUERY_STRING'];
     echo "&lt;hr /&gt;";
  }
?&gt;
&lt;form method="get" action=""&gt;
   &lt;label for="name"&gt;Type your name&lt;/label&gt;
   &lt;input type="text" name="name" /&gt;
   &lt;input type="submit" name="submit" value="Output my name" /&gt;
&lt;/form&gt;</pre>
<p>You will notice that the URL Query String is set to : name=&lt;name you typed&gt;&amp;submit=Output+my+name. That is, whatever comes after the &#8220;?&#8221; mark.</p>
<p>If you don&#8217;t want the &#8220;submit&#8221; part to appear in the URL, simply do not set the &#8220;name&#8221; and &#8220;value&#8221; attributes. Note, this works for GET only. If you used POST, the form doesn&#8217;t work unless &#8221; name=&#8221;submit&#8221; &#8221; is set.</p>
<p>A bonus: add this just after the last HR tag, you will see what the default $_SERVER Array holds. Code below:</p>
<pre>echo "&lt;pre&gt;";
print_r($_SERVER);
echo "&lt;/pre&gt;";</pre>
<p>You will get something like:</p>
<pre>Array
(
   [HTTP_HOST] =&gt; localhost
   [HTTP_USER_AGENT] =&gt; Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5
   [HTTP_ACCEPT] =&gt; text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
   [HTTP_ACCEPT_LANGUAGE] =&gt; en-gb,en;q=0.5
   [HTTP_ACCEPT_ENCODING] =&gt; gzip,deflate
   [HTTP_ACCEPT_CHARSET] =&gt; ISO-8859-1,utf-8;q=0.7,*;q=0.7
   [HTTP_KEEP_ALIVE] =&gt; 300
   [HTTP_CONNECTION] =&gt; keep-alive
   [HTTP_REFERER] =&gt; http://localhost/test.php?name=Kevin&amp;submit=Output+my+name

<em>   ... and it continues with other stuff.</em>
)</pre>
<p>That ton of details is a lot of details about your server and its current configuration.</p>
<p>Then you can experiment through the Array like:</p>
<pre>echo $_SERVER['HTTP_HOST'];</pre>
<p>Which will return &#8216;localhost&#8217;, as shown in the $_SERVER Global Array.</p>
<p>Ok, this should get you started.. Now let&#8217;s have a look at how we can get rid of the submit name into our $_POST Array. In order to accomplish this, we will use a built-in function of PHP. This is fun. Code below:</p>
<pre>&lt;?php

   if(isset($_POST['submit']))
   {
     // we use the array_pop function to get rid of the last element
     // In our case the last element is the submit button
     //Actually, it returns the last element of the array.
     //Since we are not capturing it, it's discarded. The array is shortened by 1 element.

     array_pop($_POST);
     echo "&lt;pre&gt;";
     print_r($_POST);
     echo "&lt;/pre&gt;";
     echo $_POST['name'];
   }
?&gt;

&lt;form method="post" action=""&gt;
   &lt;label for="name"&gt;Type your name&lt;/label&gt;
   &lt;input type="text" name="name" /&gt;
   &lt;input type="submit" name="submit" value="Output my name" /&gt;
&lt;/form&gt;</pre>
<p>Try the code, and you will see that unlike the previous one, the line &#8220;[submit] =&gt; Output my name&#8221; is gone. That&#8217;s how we get rid of it (Note: It will remove the submit button IF it is the last element in the array, if not, use an IF statement with a foreach loop to pull it out). Like below:</p>
<pre>&lt;?php</pre>
<pre>   if(isset($_POST['submit'])){</pre>
<pre>     foreach($_POST as $key =&gt; $post)
     {
        if($key != "submit")
        {
          echo $post;</pre>
<pre>        }
     }
   }</pre>
<pre>?&gt;</pre>
<pre>&lt;form method="post" action=""&gt;
   &lt;label for="name"&gt;Type your name&lt;/label&gt;
   &lt;input type="text" name="name" /&gt;
   &lt;input type="submit" name="submit" value="Output my name" /&gt;
&lt;/form&gt;</pre>
<p>If you do a print_r of $_POST, the submit will be there, because we didn&#8217;t use a function to pull it from it&#8217;s original array,but from every key and it&#8217;s value, we check if there is something which isn&#8217;t equal to &#8220;submit&#8221;, the IF statement will get rid of it, then when we echo the temporary variable $post, we get only our name.</p>
<p>Read this post again and again, until you understand how HTML Forms and PHP Works, next time there will be more from Complex Forms. Try fiddling with the $_GET and $_POST arrays and see the effects. You can also set values in $_GET and $_POST though it&#8217;s a bit useless. They are arrays after all. <img src='http://www.geekscribes.net/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<h3 style="text-align: center;">This article was contributed by Tipa of <a  title="Mu-Anime: Tipa's Site" href="http://www.mu-anime.com/" target="_blank">Mu-Anime</a></h3>

<p>This article comes from <a  href="http://www.geekscribes.net/blog">GeekScribes</a><br/><br/><a  href="http://www.geekscribes.net/blog/2009/12/10/php-lessons-8-server-constants-and-html-forms/">PHP Lessons 8: Server Constants and HTML Forms</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.geekscribes.net/blog/2009/12/10/php-lessons-8-server-constants-and-html-forms/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

