Sunday 12 February 2012

An introduction to PHP

I haven't blogged in a while, and it's been bothering me. My DITA (Digital Information Technologies and Architecture) module ended in December, and I wasn't sure what to add to my blog after that. If you've read this before you will know that setting up a blog was a requirement for that module of my course. It's now a new term and having had three lectures about Web Applications, it feels the logical way to go. Over the last few weeks we've covered HTML and CSS. I won't be posting about them as I have already covered the basics in previous posts. I will, however, recommend a few good websites at the end of this post.


This blog post is going to be about my first experiments with PHP. To begin, I should probably give a little bit of background on the topic. PHP is a programming language which is used in dynamic web pages. Unlike static html web pages, dynamic web pages are flexible, they can 'remember' you, and are generally easier to maintain and update. PHP stands for 'Hypertext Preprocessor'. Our lecturer Pete informed us that this is a recursive acronym (another example of geek humour), although it is interesting to note that it orignally stood for 'personal home page' back in 1994 when it was created by Rasmus Lerdorf.


The great thing about PHP is that you can drop it in the middle of HTML script, and it does something wonderful. It is a scripted language and was designed specially for the Web. It is server side, which means everything PHP does occurs on the server rather than on the client. Luckily for me, my university has provided me with a web server application (Apache) so that everything will work.


PHP is open source and platform independent, which means that it is free (hurrah!) and will run with Windows, Macs, Linux, and pretty much anything else. Using a server-side script is great for developing dynamic pages, as I mentioned before. This means that you can do seemingly basic things, like adding in today's date and time, which you cannot do with HTML. It also saves you from repeating yourself when you are coding, which you often have to do using HTML. In the example I use below where I list a number of years in a form, it only takes one piece of PHP code. To do it in HTML I would have to include every single year (which would be 112 lines of script). It would also be more awkward to update. PHP allows you to automate tasks, saving you lots of effort.


PHP also allows you to do some more sophisticated things. For example, you can require conditions to be met before certain content is displayed. It also allows you to store data separately (for example in an SQL database - more on that in another blog post). PHP also allows you to put headers and footers on web pages consistently, send emails, read web pages... hopefully by now it is evident that it is very handy to use.


Having considered why PHP is useful, we can look at how to identify and use it. To add a PHP code to a page, use php tags:


<?php
?>


This is the PHP equivalent to the HTML tags <html> and </html>. To see some PHP in action, please see my web page here. I'm not sure whether non-students can access this, so apologies if you can't see it. One day I may have my own web page which everyone can see. But for the time being,  this is where I have a space online.


At the top of the page it tells you the current day, date and time. The PHP code for this is:


    <?php
      echo "<p>Today is " . date("l") . " " . date("d") . date("S") . " " . date("F") . " " . date("Y") . ". It is " . date("g") . "." . date("i") . " " . date("a") . ".</p>";
    ?>


All the different letters after date describe what will be brought back. so 'l' is the day, 'd' is the date, etc. Be aware that PHP is case sensitive, so typing date("s") and date("S") will give different results. PHP date documentation explains this very well. The echo command inserts content into the HTML page.


Note the use of quotation marks. If the text you wish to include contains quotation marks, this can cause an error. For example, if you wanted to display 'He said "good morning".' then you would probably type:


echo "He said "good morning."";


However this would cause an error message because computers aren't all that bright and won't understand that you have quotation marks within quotation marks. To tell it that this is what you are doing, you must use a backslash to precede the quotation mark like this:


echo "He said \"good morning.\"";


This is better than mixing single and double quotation marks (which would fix your problem but could potentially cause you more bother in the long run). 


After displaying the date on my web page I tried to be more ambitious and involve some drop-down menus. On the page there is a field for day, month and year. Before anyone points out the obvious, I know that you can select non-existent dates (such as 31st February). Automatically selecting days that match months requires Java and I haven't got that far yet!


I will divide this up into chunks, because different code is required for the different parts. The day and year are integers (numbers) so the code is essentially the same. It looks like this:


<label for="day">Day</label>
        <select name="day" id="day">


<?php
$day = 31;
for ($counter = 1; $counter <= $day; $counter++) {
echo "<option>".$counter."</option>n";
}
?>
</select>


Take note that this is a mixture of HTML script and PHP. As I said before, PHP is great because it can be dropped in. All you have to remember is to start php with <?php and end it with ?> 


The third line of PHP includes a 'for' command. This is what I was referring to earlier when I said that PHP allows you to automate tasks, and when it requires a condition to be met. What the code is saying is that the variable name $day is 31. When the variable $counter, which starts at 1, is less than or equal to the variable $day, display the number in the counter and add 1 to the counter. The code in the curly brackets { and } populates the drop down menu with 1, then when the semi-colon is reached it loops back to the beginning of the 'for' command. In doing so, the drop down menu becomes 2 (1+1), then 3 (2+1), then 4 (3+1) and so on until the condition is met where $counter becomes equal to $date, which is when it reaches 31. Then it stops looping back to the beginning of the 'for' command and moves on to the next piece of code after the semi-colon (in this case it moves on to the month which I will discuss next).


The code for the month is a little bit more complicated because it involves arrays. An array is a container for strings (words or letters), integers, or a mixture. It is used to create a list for the computer to read through. I will discuss this below before I get on to the month drop down menu.


Arrays


In programming, arrays are used to create lists in a labelled 'container'. An array is a collection of related data, in the example of months it would be a list of all of the months. When selecting an item from an array, it is important to understand that the computer starts counting from 0, not from 1. So to select the third item in a list, you would need to use [2] and not [3]. The function count() allows you to see how many items are 'stored' in your array. 


Additionally, you can label the items within your array. So rather than calling back numbers, you can select a label. For example, if you were looking up meetings in a calendar you might have something like:


$meeting = array("client" => "Bloggs & Co.", "room" => "Conference Centre", "subject" => "Discussion re: new contract");


So rather that using the position of the item in the array, you could just type in:


$meeting["client"]


which would return "Bloggs & Co.". The terminology for the items is that on the left (client) is the index and on the right (Bloggs & Co.) is the value.


So, after that slight deviation let us return to the date on the web page. The coding for the month field is:


<label for="month">Month</label>
        <select name="month" id="month">
     
 <?php
 
$month = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
for ($counter = 0; $counter <= 11; $counter++) {
echo "<option>".$month[$counter]."</option>";
}
?>
</select>


With all the of the field code, don't forget that it will need to be within a form. So if you are trying this out yourself, you will need to start with:


<form>
<fieldset>


Then put your HTML and PHP code here to generate the drop down menus. Then close with:


</fieldset>
</form>


I hope this has been a useful, if brief, introduction to PHP. It's easy to see why it is a popular language to use, as you can do so much more with it than you can with html on its own. Not to mention the fact that it saves you from typing potentially thousands of lines of nearly-identical code using functions like 'for'.




Some useful links:


HTML and CSS Tutorials by HTML Dog
W3 Colour selector for CSS
Code Academy
PHP Guidance


Books that I will be using during this module:


Griffiths, P. (2007) HTML Dog: The Best-Practice Guide to XHTML & CSS, New Riders: Berkeley, CA
See this on Amazon

Ullman, L. (2011) PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (Visual QuickPro Guides), Peachpit Press: Berkeley, CA
See this on Amazon

Negrino, T. & Smith, D. (2012) JavaScript: Visual QuickStart Guide (Visual QuickStart Guides), Peachpit Press: Berkeley, CA
See this on Amazon

No comments:

Post a Comment