PHP Explained - draft document - still being written - copyright Keith Martin 2005 and onwards

---

INTRODUCTION

PHP is simply a language used to write instructions for a web server, much like HTML, CSS and JavaScript are used to make instructions for the end user's web browser. There are only two requirements for PHP. The first, logically enough, is that you host your pages on a server that can process PHP; see Serving PHP below for details. The second is that you name your pages with .php rather than .html so that the server can tell when it is supposed to look through a document for PHP instructions before sending it on to whoever requested it.

The syntax of PHP isn't particularly complicated, you just have to follow some basic rules (and follow them religiously) and don't lose track of things as you go. In terms of where you put your PHP code, it is pretty flexible. You can mix it up with regular HTML in all manner of ways. For example, you could write a page which contains nothing but PHP instructions, perhaps something which does some processing and then redirects the user automatically to another page. Or you could have a chunk of PHP instructions at the beginning of a page, followed by regular HTML. In this case, this could adjust values one way or another depending on what browser you use or which page you came from. In yet another use, small (or not so small) snippets of PHP instructions could be sprinkled throughout a web page's HTML code, typically in order to be processed and replaced by custom content in the page.

PHP instructions, whether they are pages-worth of code or simple embedded snippets, always start and stop with a simple opening and closing marker. To start some PHP code you begin with <?php, and you end it with ?>. Everything inside of those will be evaluated as if it were PHP instructions, and everything outside of a pair of those will be left alone. Each individual PHP instruction, or statement, must be finished with a semicolon. This tells the interpreting engine where one individual instruction ends, so it can get on with processing it. (Technically, start some PHP code with the shorter <? is also valid, but it isn't guaranteed to work on every setup. Stick to opening PHP blocks of code with the full <?php format.)

After processing, the page is sent to the viewer - but with the PHP code stripped out and replaced with whatever the results might be. This means your PHP instructions themselves are never passed to anyone. If you're calculating price selections, for example, this is far more secure than any client-side JavaScript can be.

Before you launch into things there are a few points that should be covered. These will help you understand what's going on, so don't skip down to the code samples just yet.

 

COMMENTING

As you work, you should make sure to include notes on what different portions of the code are for. It is surprising how quick and easy it is to forget why you did something in a particular way, so don't put it off: add comments as you work, and keep them updated as you make changes.

A comment is simply a line or more of text which has been marked so that the PHP interpreting engine doesn't try to make sense of it. To make some text behave as a comment, put two forward-slash characters at the beginning of the line. It will then be ignored completely when the PHP code is run. if you want to 'comment out' a large portion of text, put /* at the beginning (preferably on its own line to make it easier to spot later on) and its mirror twin, */, at the far end.

Commenting lines is also very useful for disabling bits of your PHP scripting as you try things out. If you're having trouble with something you can simply cut it out of the loop to see if that makes any difference. You can also use this to leave older working code in your pages as you experiment with newer attempts - but be sure to include clear and complete comments explaining what you're doing or you'll just end up confusing yourself at some point.

By the way, if you use Dreamweaver, BBEdit or a similar text editor tool for your coding work (and BBEdit is good enough to make PC users consider switching to Macs) you'll see commented text and different active elements in your code marked up in different colours.

 

VARIABLES

If you're going to use PHP at all you'll have to understand what variables are and how to use them. Variables are simply named containers; they store whatever you feel like putting into them, and when you refer to them you get back whatever's inside. Variables are always named with a dollar character at the start of the name, and they are always a single 'word'; no spaces are allowed, although underscores are often used in their place. Variable names are also case-sensitive, so a variable called $Test is not the same as a variable called $test. This point is extremely important to remember, so pick a naming system and stick with it. Most PHP programmers like using all lower-case characters and underscores, as in $variable_name, rather than 'intercaps', as in $variableName, but the important thing is to remain consistent as you go. Finally, don't start a variable name with a numeral. Naming a variable $5_thing won't work, although $five_thing and $thing_5 will.

To put something into a variable just type $variablename = data, as in $colour = "red". The simple act of 'declaring' it and putting something into it creates the variable. The single equals sign means 'make this the same as that', or, to put it another way, 'put that' (i.e. "red) 'into this' (i.e. $colour).
If you made a variable called $name and put someone's name into it, then whenever you referred to $name in your PHP code it would automatically be substituted with what it contained: someone's name.

Variables containing numbers can be incremented and decremented one number at a time very simply. If a variable called $number contains "10", then simply saying $number++ adds one to it, and $number-- subtracts one instead.

A double equals sign is used to compare two things, so you can check whether a variable contains what it needs to. The code $colour == "red" will return a boolean-style (yes/no); "1" if that's true and nothing if it isn't. Be careful not to use just one equals sign where you should have used two, and vice versa.

ARRAYS, a more complex kind of variable

Normal variables hold just a single chunk of data, but an array (a kind of super variable) can store a lot more. Don't worry too much about arrays for now, just remember that their contents are sets of 'name/value' pairs... each pair, or 'element', behaving a little like a variable itself. To retrieve something from an array, you refer to the array's name and, within that, the name of the element you're after. To retrieve the value for an element called "colour" in a variable called $preferences you'd do it with $preferences["colour"]. Just as referring to a variable gets you its contents, referring to an element in an array gets you its contents. But really, don't worry too much about arrays for now.

Finally, there are some variables that are built for you automatically. These are the ones which store something submitted in a form ($_GET or $_POST, depending on how the form was designed; see Forms in the main section below), deal with cookies ($_COOKIES; see Cookies below), and provide detailed information about the server and the visitor ($_SERVER). These are arrays, so, to get the data you want, refer to the variable name itself and then the element name within square brackets. For example, $_POST["name"] pulls the data stored in the 'name' element which was sent from a post-based form.

 

FORMS

PHP is often used to process the contents of a web page form. It is more secure and reliable than JavaScript, as everything is performed on the server. Unlike client-side JavaScript there's no opportunity for someone to try to work out how the script works, as they will never see the actual PHP code - only the processed end result. And, again unlike JavaScript, it will work regardless of the end user's web browser abilities or failings.

A web form's submit button is pointed towards whatever is supposed to process the submitted data. In the case of PHP processing will point towards a custom PHP page. This will be written to extract the data that's sent to it and processing it in some way. The data will arrive as an array, a collection of individual portions of data stored in 'compartments' which are named using the form element names. As we've already explained, this could be as part of a page with visible HTML content (perhaps making immediate use of some of the submitted data) or as something which redirectly straight to an entirely separate document as part of the processing (for example, a 'thanks for sending the data' page).

 

FUNCTIONS

Functions are simply code statements that process something and return the end result. For example, the date() function returns the date, time, or both(see date() for details), mail() can send email, often used in forms, phpinfo() returns detailed information about the current PHP engine (see phpinfo() for details), and so on. You normally choose how the function is supposed to work by supplying one or more parameters within those parentheses;

[more shortly]

---

GETTING STARTED

To begin with, we'll use a very simple 'hello world' example, as favoured by seasoned programmers. This will make sure that things are working as they should and demonstrate the simplest use of PHP. Later on we'll step up to something which is more likely to be useful in real-world web work.

<?php
  print("Hello world");
?>

Type this into a regular HTML document, somewhere in its body. Save the file with .php at the end of the name instead of .html, and upload it to your web server. Now try it out in a browser. As long as you got the address right and PHP is active on the server, you'll see the words "Hello world" 'printed' into the page as if they'd been typed there directly.

The echo command works in a very similar way to the print function; it puts a string of text into the HTML of a PHP-generated structure or page. In most cases you can use either echo or print. Strictly speaking, print is a function, so what you're printing should be enclosed within parentheses, while echo is a 'language construct' which doesn't need those (and shouldn't have them unless you're echoing just one thing). Additionally, what you try to return with print has to boil down to one thing before it gets sent back, whereas echo can handle multiple items in one go. This example shows the slightly different correct use of echo and print when returning multiple items:

<?php
  echo "123", "456", "789";
?>

Produces 123456789. This could be done with multiple 'echo' instructions, but that's less efficient:

<?php
  echo "123";
  echo "456";
  echo "789";
?>

The print function can't deal with multiple items like echo; you can't just pass it a number of chunks of quoted text strung together with commas. Instead, you have to use proper 'concatenation' methods. In PHP, one very simple way of concatenating, or joining, things together is with the dot (period, full-stop) character. For example "this" . "that" becomes "thisthat" when it is processed. So this is the print equivalent of the echo structure we just saw. (The spaces around the dots aren't required except for legibility.)

<?php
  print("123" . "456" . "789");
?>

Produces 123456789. Just as with the 'echo' example, if you didn't concatenate the different chunks of data together you would have to do this with multiple 'print' instructions:

<?php
  print("123");
  print("456");
  print("789");
?>

You can embed HTML code within PHP, just remember to put it in quotes so it is treated as a regular text string. This raises an important point: any quotes that are supposed to be there in the HTML will have to be 'escaped'; flagged as something to be passed through untouched rather than being worked on my the PHP interpreter. To escape a character, put a backslash immediately before it. This snippet of PHP code shows this in action.

<?php
  print("<font color=\"red\">Red text</font>");
?>

Produces <font color="red">Red text</font> in the HTML code that the server sends back to the browser.

Without escaping those quotes around the colour definition they would be seen as ending the portion of text to be 'printed', as in print("<font color="red">Red text</font>");. The rest of the text would then be handled as if it was further PHP instructions, and you'd get an error rather than what you expected.

Now, this example is unlikely ever to be used as it stands. All it does is 'print' the evaluated code straight out, doing nothing clever with it at all. It might as well be put into the page as plain HTML in the first place. But what if we use a variable to store the colour name? Things can start getting interesting.

We'll assume that someone has picked a colour from a list or typed it into a text field and then sent the results off as part of a form. The chosen colour name has been extracted and stored in a variable called $colour. Now when we replace the specifically named colour with the variable name you can see how the PHP code can start to become very useful.

<?php
  print "<font color=\"$colour\">$colour text</font>";
?>

---

Quoting and Escaping

When you use text 'strings' in PHP you'll need to put quotes around them. This tells the interpreter to handle them as chunks of data rather than actual instructions. However, there's a subtle - but important - difference between using single quotes and double quotes. Text in single quotes will be handled exactly as it is, without any processing of variables or escaped characters. Text wrapped in double quotes, on the other hand, will have those things processed before being passed along.

The process of escaping things is useful when you want to use characters such as returns, quotes, backslashes, and anything else that would otherwise be misconstrued by the PHP engine. If you want to include a quote character in a string of quoted text, putting a backslash before it will do the trick. To put a line break in some text, use \n, to insert a tab use \t, and for a dollar symbol use \$. If you want to use a backslash in the text, escape it with its own backslash, as in \\.
(It is very important to be aware that the line break, \n, just inserts a regular line break or tab character in the text data itself, it doesn't provide the HTML tags that break lines of text as shown in a browser. Text viewed in a web browser won't show line breaks which are in the code; include <br/> or the equivalent to have such structures formatted properly in browsers. This becomes more useful when preparing text for use elsewhere, such as automatic email production.)

When escaping quotes, you only need to escape the particular kind of quote character (single or double) that's wrapped around the string of text. For example, 'that\'s it' and "that's it" produce the same result, as do 'say "hi" now' and "say \"hi\" now".

---

If

One of the reasons scripting is used is for the ability to do different things depending on certain conditions. 'If something is the case then do one thing otherwise do something else.' This can be done in a number of slightly different ways in PHP, but we'll look at the most common way of structuring this. Start with 'if', then wrap the thing you're evaluating in parentheses. Then put the instructions you want done if that is the case within braces, remembering to put a semicolon after each individual instruction. It should look something like this: if (something is true) { do something; }. Just remember that the thing you're evaluating is enclosed in ( and ) while the things that are to be done are wrapped within { and }. This is normally done across a number of lines to help keep it readable, as in the following example.

<?php
  // First put the current month into a variable
  $month = date('F');

  // Then only do something if the month is October
  if ($month == "October") {
     print "Welcome to Halloween month";
    }
?>

The first line uses the special PHP 'date()' function to put the name of the month in the variable called $month. (See PHP date() for specific details on the date() function.) Then the if structure checks to see if $month contains "October" and runs a simple instruction if the answer is true. (Note the difference between using a single equals character to assign something to a variable and using two equals characters to compare two things, explained in Variables, above. This is something that you're very likely to forget at some point.) If you want to do something else if the answer is false, add else { do something else; } to the code. Here's how it would work.

<?php
  // First put the current month into a variable
  $month = date('F');

  // Then do one thing if the month is October and something else if it isn't
  if ($month == "October") {
     print "Welcome to Halloween month";
    }
  else {
     print "Sorry, there's no Halloween in $month";
    }
?>

This also uses whatever is stored in the $month variable to customise the output if the month isn't October. Remember, when the PHP interpreter evaluates the instructions, it'll replace any variables that you 'print' with whatever they hold at the time.

---

REDIRECTION

Automatic redirection of a visitor to a new location is simple using PHP. Unlike the crude 'meta refresh' tag which can be put into the start of an HTML page, this works before a single bit of data is passed back and it doesn't annoy search engine spiders. What this involves the server doing is responding to a page request with a new HTTP location header. This tells the browser to show the new URL as the address and then fetch the data served from that location. In effect, the browser never completely stops or gets any HTML from the first location at all.

Responding with HTTP headers must be done before anything at all is sent back to the browser, including 'white space', so start your PHP page with the opening tag right at the beginning of the file and don't print or echo anything before your header lines appear.

The redirection instruction itself is very simple; all you need inside your PHP tags is header ("Location: URL");, with URL being a complete address including the protocol prefix. (This will almost always be http://, but it could be ftp:// or others.) Put the following code into a PHP file and try visiting it online:

<?php
  header ("Location: http://www.apple.com/");
  exit;
?>

Of course, this could be done as simply using a simple htaccess file on the server rather than PHP. For a more useful example of PHP redirection in action, imagine you'd like to send a visitor to a different page depending on which month it was. This could be in order to show them the latest offers, a tip of the month, or simply to change things on a regular basis without having to do it by hand every month. Put the address into a variable, using the date() function to build the month name in the URL. Then use the variable inside the redirection command. As long as there are pages with the right names ready and waiting this will work quickly and entirely automatically every time. Just be aware that web servers are case-sensitive and that the date() function capitalises the first letter of the name of the month - so name the January page as "January.html" rather than "january.html".

<?php
  $url "http://www.domain.com/" . date(F) . ".html";
  header ("Location: $url");
  exit;
?>

But what if you simply have to refer to web pages with all lower-case letters? That's not a problem; a quick use of the strtolower() function will convert the characters in a text string to lower case.
(Yes, as you've probably guessed already, strtolower() means 'string to lower'. The function strtoupper() converts to upper case, ucfirst() capitalises just the first character in a string, and ucwords() capitalises the first letter in each word.)
Place a text string or, indeed, a variable containing a text string, between the function's parentheses to put this to work. Here's one example of how to use strtolower() in the above redirection script:

<?php
  $url "http://www.domain.com/" . date(F) . ".html";
  $url = strtolower("$url");
  header ("Location: $url");
  exit;
?>

This builds the full URL and stores it in a variable in the first line, puts a lower-case version of the variable's contents into the same variable (to keep things tidy) in the second, then uses that as the URL for the header redirection in the third.

If you're interested, you can pack PHP commands together in certain ways. For example, instead of using two distinct lines to say
  $url "http://www.domain.com/" . date(F) . ".html";
  $url = strtolower("$url");

you could type
  $url = strtolower("http://www.domain.com/" . date(F) . ".html");
instead.

---

Cookies

(text in development...)

One relatively simple real-world use for PHP is with a cookie-enabled page. A cookie is a small portion of data which is stored by a user's web browser on their computer. At its most basic level, a cookie can be used to see whether or not a visitor has been to a page before, and the answer to this can be used - by some further PHP scripting - to customise the page content that the user is given. You could also use it to store something a user submits in a form, for example their name.

Using PHP, you ask the user's browser to store a cookie for your site, and you can retrieve it in other pages. The cookie is accessed using a standard variable called $_COOKIE. This holds the stored data in an array (see Arrays above), using one of the automatically-generated $_COOKIE variable that PHP provides.

Cookies can only be set before any regular HTML data is handled, so make sure your PHP cookie code comes before anything else in the page, including simple returns. To create a cookie that shows whether someone's been to the page before, start the document with the following code:

<?php
  setcookie("visited", "yes");
?>

This simply stored a cookie called "visited" on the visitor's computer, and puts "yes" into it. Now you can follow it with the rest of your web page code. Of course, this example is fairly basic, but with another portion of script you can find out whether a cookie has been set.

The isset() function finds out whether a particular cookie has been set, so you can choose what to do: greet the visitor as a long-lost friend or demand that they sign in. In the example below notice that we've added the exit() function. This halts all processing completely, so anything after this point, whether it is PHP or HTML, won't be sent. The exit() function can be extremely useful when trying to get some code to work, and it can also be handy where you'd like to stop processing if certain conditions are or aren't met. Just don't forget you have it there!

<?php
  if (isset($_COOKIE["visited"])) {
    print("Welcome back " . $_COOKIE["visited"] . "<br/>");
  } else {
    print("Please <a href=\"signin.html\">sign in</a><br/>");
  }
  exit();
?>

Another way to handle storing data and using it across multiple pages is with session variables. We'll tackle this in a future update to this document.

---

Forms

Sending data using a form and PHP is actually pretty simple once you understand how things work. In the code of an HTML form, its target, or 'action', will be some kind of script which accepts the form data, pulls the different bits apart, and makes use of them in some way. Our example asks for a name and then uses that at relevant points in the next page. This is extremely basic, but it should help give you a clear idea of how these things work.

This simple form example will use two pages. The first is a regular HTML page. We've named this question.html in our example. In it, along with whatever HTML layout code you want to use, put the following code. Remember, this is standard HTML stuff here. The form 'action' points to the PHP file we'll make next:

<form method=POST action="colour.php">
  What is your favourite colour? <input type="text" name="colourchoice"/>
  <input type="submit" value="Go"/>
</form>

That's it for the form itself. Now you need to write the code which processes this and makes use of what the user supplied in the text field. Take the HTML page where you want to use the supplied colour choice, and change its filename so it ends with .php instead of .html. Our example is called colour.php; if you want to use a different name (remembering that it has to end with .php) just make sure that you change the form action target in the previous page accordingly. In your PHP page, put in the following snippet of code wherever you want the name to appear.

  <?php print $_POST['colourchoice']; ?>

This tells the PHP engine to look in the '$_POST' variable, which holds all data sent by the form, and find and use the data attached to the item called 'colourchoice'. (If the form had method had been GET rather than POST you'd use the $_GET variable instead.)

To sum up, the question.html page contains a form with a text field called 'colourchoice'. When someone sends the form, it goes to the page called colour.php, which looks at the received form data and uses the contents of the item called 'colourchoice' wherever you put that code. It is possible to do this in a more elegant way, but this example is both compact and simple, and it works. Here's an example of this in use in code, as a response to someone typing their favourite colour:

<p>
Your favourite colour is <?php print "<font color=\"$colour\">$colour</font>"; ?>
</p>

---

Repeating

This example shows how PHP can be used to build up some HTML content by looping around and repeating itself a number of times. The first example here uses a simple str_repeat (string repeat) command, which just repeats the given text the specified number of times. The structure of this command is simple: the str_repeat is followed by the text to be repeated and the number of times to repeat, separated by a comma and wrapped in parentheses.

<table width="200">
<?php
  print str_repeat ("<tr><td>cell</td></tr>", 10);
  ?>
</td></tr> </table>

This is perfectly usable but somewhat limited. If you'd like to include a counter which increments with each loop, such as a number put into each table cell, then a slightly more complex method is needed. This example uses the 'while' logic structure, which effectively says 'while something is not the case, do this and repeat'.

First, a variable called $counter is created by putting '1' into it. Yes, you can create a variable at any time just by doing something like this. Then the code says, in effect, 'while the variable called $counter is less than 11, do the following instructions'. Then, inside the braces (the curly brackets), the first line 'prints' some data (including the $counter variable) and the next increments $counter by one.

<table width="200">
<?php
  $counter = 1;

  // Loop until the counter variable reaches 10
  while ($counter < 11) {
    print "<tr><td>cell $counter</td></tr>";
    // Increment the counter by one each time
    $counter++;
    }
?>
</table>

---

Essential Reference

When you start putting PHP into practise you'll find that it can be both inspiring and confusing. Remember our list of common mistakes, as many problems will stem from making one or more of those slips. You should also invest in some PHP reference and example books. There are many around on bookshop shelves, but we recommend considering Build Your Own Database Driven Website Using PHP and MySQL, Third Edition by Kevin Yank (despite its alarming name this is written for relative beginners), PHP Pocket Reference, Second Edition by Rasmus Lerdorf (the creator of PHP), PHP Cookbook by David Sklar and Adam Trachtenberg, and Programming PHP by Rasmus Lerdorf and Kevin Tatroe. See the UK/European reference page or USA/Canada reference page for details.

When you find one or two you like, keep them with you as much as possible and keep dipping into them even when you're not specifically trying to produce PHP code. You'll end up with a reasonable grasp of how to use this language sooner than you think.

---

Boxes...

SERVING PHP

In order to use PHP in your web pages they need to be hosted from a system which has the PHP engine installed. As PHP is arguably the most popular and widely-used server-side scripting language for the web, and as it is free, open-source software, PHP support is often already provided in many web hosting packages. It isn't, however, in all; most free web hosting packages don't include support for PHP, and some low-cost ones don't either. If this is the case with your current host package, ask your hosting company if PHP support can be made available either free or for a reasonable charge.
Having PHP running on your hosted web site is essential, as without it your script instructions won't be performed when pages are viewed. Having PHP running on your own Mac is not essential, but it does mean that you can test out your efforts without having to upload your changes all the time. Doing this doesn't mean compiling complex Unix software bundles or even downloading anything, as Mac OS X (version 10.x and above) has PHP installed already - just disabled. All you have to do is change two lines of a text file on your Mac and run a simple command, as shown in Enabling PHP on your Mac.

Enabling PHP on your Mac

The best tool to use for this and the rest of the code editing tasks we discuss is BBEdit, by Bare Bones Software. If you don't already have this, download a free 30-day demo or buy for $99 from www.barebones.com. When meddling directly with code, BBEdit is our text editor of choice; it handles syntax colouring, auto-completion, intelligent code indenting and, handily, it can let you browse through OS X's hidden folders and files. You can of course use any text editor from TextEdit onwards for basic code editing, but very few tools give access to the hidden configuration file that you need to edit for this trick.

In BBEdit, choose File > Open Hidden, then browse to /etc/httpd/ and open the file called httpd.conf. In there, do a quick search for "php" to help you find the line which reads:
# LoadModule php4_module libexec/httpd/libphp4.so
and, separately, the line which reads:
# AddModule mod_php4.c.
The # character at the beginning of these lines disables them, so just delete that character from each, then save your changes (authenticate with your regular Mac admin password when asked) and quit BBEdit.

If you'd rather see what you're doing, try pasting the following AppleScript into Script Editor and running it to open the nested window in the Finder:
tell application "Finder"
  open folder "httpd" of folder "etc" of item "private" of startup disk
end tell

Now you need to restart the Mac's built-in Apache webserver engine so that it reads the new configuration file and enables PHP. To do this you can either restart your Mac or, more quickly although also more geekily, launch Terminal, type sudo apachectl restart, and press return. Type your admin password and press return again to authenticate the command, and after a few seconds you'll see a message telling you that Apache is configures and is 'resuming normal operations'.

Now type the phpinfo() command into a text file (see INFO), save it as 'test.php' (or some other name ending with .php), and put it into the Sites folder in your home folder. In any browser, visit http://127.0.0.1/~username/test.php (replacing username with your 'short user name', the name shown on your OS X home directory) to see the results of the phpinfo() command.

INFO

You can find out a lot about the PHP 'environment', the PHP engine which is running on the web server, simply by using a tiny snippet of PHP code. Put the following code into a text file, call it something like "info.php", and upload it to your site.

<?php
  phpinfo();
?>

Now use a browser to read it from your web site. This will give you a mountain of information about the version of PHP that's running, all its various current settings, and a huge amount of detail about other processes as well. Print or save a copy of this page then delete the info.php document from your server. The information it supplies could be used by someone to hack the server, so don't leave it on there in case someone guesses its name.

PHP date()

The date() function is useful for getting the date and time in whatever fine-grained detail you want, and in whichever format is most suitable. By putting the right parameters into the parentheses you tell the PHP engine what sort of date/time detail you want. The list of parameters is pretty long, but these are a good starting point:

  • g (hour in 12-hour format)i (minutes, with leading zero if necessary)
  • a (am or pm)
  • l (name of the day of the week)
  • j (day of the month)
  • F (name of the month)
  • Y (year in four digits)
By putting a short PHP string into your HTML code you can show the precise date and time that the page is requested. One handy example is with a copyright notice, where you want to show the current year without having to update the page every January. Here's an example of this in use: <p>Copyright <?php echo "date(Y)"; ?> Keith Martin </p>. Another use might be to find out what month it is as part of choosing what someone sees in a web page. This kind of conditional process is covered in the section on 'if'.

If you wanted more complete time and day information just put it all inside the date() parentheses, enclosed in quotes. Put this into a variable before trying to print or echo it. This example shows the time of day with am or pm.

<?php
$the_date = date("g:ia");
  print "$the_date";
?>

You can of course go much further with this, but beware of using characters which mean specific things indate() terms; those have to be escaped. This example puts the day of the week, a comma and space, and the time with colon into the variable.

<?php
$the_date = date("l, g:ia");
  print "$the_date";
?>

Alternatively, you can string together multiple date() functions, each with its own parameter. This snippet of code echoes back the time and the day of the week:
<?php echo date(g), ":", date(i), date(a), " on ", date(l); ?>
This simply calls the date function first for the hour then the minutes (with a colon inbetween), then it adds am or pm, then a string of text and finally the day of the week. You may find it easier to read in multiple lines, and you could use the print() function instead of echo if you liked. Here's how this could be handled:

<?php
  print(date(g));
  print(":");
  print(date(i));
  print(date(a));
  print(" on ");
  print(date(l));
?>

COMMON MISTAKES

When you write PHP code you will make the odd mistake, no matter how careful you are. This is simply a fact of life when writing out scripts by hand, which is why decent HTML and CSS code-generating tools such as Softpress Freeway are such a boon for general web design work. There's no real equivalent for PHP, sadly, so here is a list of some of the most common slip-ups that you're likely to make at one point or another. When things don't go as expected; when you get errors or raw code rather than the expected results, see whether you've done any of the following things.

Not naming the page using .php

Not ending a statement with a semicolon (using a colon by mistake is particularly hard to spot)

Using a different spelling for a variable name (remember, PHP is case-sensitive)

Not escaping special characters

Not using <? and ?> around your PHP code

Using = rather than == to compare two values

Not quoting something when it should be

Quoting something when it shouldn't be

Using single or double quotes inappropriately

Having too many, not enough, or just misplaced braces (curly brackets) in IF statements and similar constructions

For UK users in particular, typing a £ symbol instead of $ when working with variable names