PHP is a server-side processing language for web pages: that is, it processes code contained with PHP tags, displaying the result in the browser or doing something else with the information (storing it in a database, sending it via eMail, etc). Developed in 1994 by Rasmus Lerdorf, the PHP acronym stood for “Personal Home Page”, later changing to “PHP: Hypertext Processor” in one of the self-referential acronyms that plague the IT industry. Personally, I prefer Pre-Hypertext Processor, to make it clear that PHP runs before anything else on the page.
PHP is a server-side language. PHP code on a web page is executed by the server and turned into results for the client (typically a web browser). PHP can generate HTML, CSS, even graphics. The fact that PHP runs on the server means that, so long as it is correctly written, PHP just works: it does not depend on the client’s computer to operate or run correctly, thus avoiding the disadvantages of JavaScript and Flash.
PHP is one the most powerful technologies available to web developers, having six major advantages:
It is free and open source.
PHP is developed and maintained by a loose, world-wide collaborative group of software engineers and coders. Help for PHP is freely available (the best and primary resource being www.php.net). PHP isn’t proprietary to any one company: it is maintained by collective interest, not for profit. Apache and MySQL (the server and database solution we will be using in class, respectively) are also free and open source: you can download them and install them for free.
Since anything outside a <?php ?> tag (the opening and closing tags of PHP, respectively) is interpreted as HTML, you can create static elements in HTML and interweave dynamic elements in PHP, all on the same page.
It is cross-platform.
Because it is interpreted by the server, not the client, PHP is not subject to the vagaries of interpretation by different browsers/platforms, etc. Once PHP runs correctly on a page, it will run the same forever, assuming that the server itself does not change.
PHP is expressly designed to create dynamic content for web pages.
Unlike Perl and other languages, PHP was designed for the web “from the ground up”.
The end user never sees PHP code.
Unlike HTML and JavaScript, PHP is interpreted into HTML “on the fly” when it is delivered from the server. No-one without access to your source files can ever see your PHP code.
It is relatively easy to use and learn.
PHP’s programming syntax is fairly straightforward, similar to ActionScript and other languages you have likely encountered thus far. The major problems people have with PHP are the same ones they have with other languages.
It is a very good working practice to comment your code in every language you use. Comments serve two major functions:
As notes and reminders
Comments allow you leave yourself notes as to what sections of code do, and what they are there for. It is common, as both a freelance and full-time developer, to return to code that you have not seen in six months or more: comments allow you to quickly remember what each piece of code does.
As “traffic cones” around code that is problematic.
Code surrounded by comment markup immediately ceases to work. Because code on a web page is read from the top down, you can narrow down the cause of problems by removing sections from execution by means of comments, moving the start and ending comment markup around to analyse problems via a process of elimination.
Content, markup and code within comments does not appear on a web page, but can still be read by anyone what access to your source code. (In HTML, CSS and JavaScript, that is as easy as using View / Source in the browser).
HTML
<!-- this is an HTML comment -->
Note that HTML comments are not tags; this can be confusing to many neophyte coders, as they appear to break all the rules of XHTML. Comments may be placed over multiple lines.
<!-- this is a comment
over multiple lines -->
CSS
/* This is a CSS comment */
CSS comments may also be broken over multiple lines:
/* p { font-color: black; }
hr { color: red; }
both of the above lines, plus these two
will be ignored */
You will find that some web development text editors and WYSIWYG tools insert HTML comments immediately inside embedded styles and JavaScript in an odd way:
<style type=”text/css”>
<!--
-->
</style>
or
<script type=”text/javascript”>
<!--
-->
</script>
This is an old trick employed to protect very early browsers that only understood HTML from possible misinterpretation of CSS and JavaScript. The technique is largely irrelevant now, but it does no harm to use it. What is important to remember is that (a) the JavaScript and CSS will still work in compatible browsers (HTML comments only block HTML, not CSS or JavaScript), and (b) you must still use the appropriate JavaScript and CSS comment code once you start writing in those languages.
JavaScript
Comments in JavaScript code are the same as for CSS:
/* this is a JavaScript
comment */
It is also possible to do single-line JavaScript comments:
// this is a single-line JavaScript comment
I don’t recommend the single-line comment format, as it is too easy for an errant carriage return to sneak into a comment and force the remnant into your code, breaking it.
PHP
PHP comments are exactly the same as JavaScript comments:
/* this is a PHP
comment */
// so is this
For the same reasons given in JavaScript comments, I do not recommend the single-line format for PHP comments.
A quick and simple test determines if your server supports PHP, and provides much more information about it’s capabilities.
There is a quick and simple test. Create a new page, one completely free of code of any kind, with the filename test.php (the actual name of the file is immaterial, so long as it follows standard web naming conventions and has a .php suffix). On this page, write a single line of PHP code:
<?php phpInfo(); ?>
Then upload or place the page in the appropriate directory on your server and use your web browser to navigate to the page.
If the server is running PHP, what you will see may surprise you: a huge presentation of data pulled live from the server regarding PHP, Apache, and associated modules. While very simple, this also demonstrates how powerful server-side languages can be: a single function can generate an incredible amount of content.
To extend this lesson, take a look at the source code of the generated page (CTRL-U/CMD-U in most browsers). Note that you do not see any trace of PHP code; you only see the HTML and CSS generated by PHP. The browser never directly interacts with PHP; it only receives its output, expressed as HTML, CSS, JavaScript or images.
As before, upload this page to your server and use your browser to look at it in that location.
Depending on how your server is set up (error messages shown or repressed) you will see either nothing at all on the page, or an error line similar to the following:
Parse error: syntax error, unexpected T_STRING in
/f2/demosthenes/public/test.php on line 1
This demonstrates two important points:
When PHP doesn't work (almost always due to an error in your code) it really doesn't work: the page stops, and you get an error message, or nothing at all.
The echo statement prints information to the page: that information could be a text string, as we have above, HTML, a variable, or a combination of all three. Anything other than a variable must be enclosed inside quotes; either single quotes ('') or double quotes("").
So what's the problem with our page?
The PHP opening tag is usually <?php ..., but it may also be shortcut to <? .... This latter, optional format for the opening tag confuses the PHP parser, which attempts to interpret our opening XML prolog as PHP. There are several possible solutions to this:
Drop the XML prolog. Doing so sacrifices some flexibility and future-proofing, avoids an issue in IE6 (which also has an issue with the XML prolog), keeps your page valid, and is probably the quickest solution.
Set the PHP parser to only accept the long form of the opening PHP tag and ignore the short version.
Use PHP to echo out the XML prolog. Replace the first line of the page with the following code (note the uses of single quotes):
The most valuable feature in any server-side language is includes
In most websites you have areas of content that are the same from one page to the next. These sections might include:
header or banner content
navigation bars
footers
The appearance of this content is commanded by CSS, which allows us to maintain rules for the consistent presentation of content across a site. However, the content itself is also often exactly the same: for example, you may always have the same code immediately after the opening body tag on every page:
<h1>Hannibal’s Bait & Tackle Shop</h1>
<h3>Duluth, North Dakota</h3>
To make this content the same between all pages, most so-called web developers copy and paste the same code from one HTML page to the next. The approach works well so long as the content never changes. But if the site in our example decided to offer boat rental, and changed their business name to “Hannibal’s Bait, Boat & Tackle Store”, we would have a massive amount of editing to do site-wide. We can avoid this problem entirely – and speed up web development by 10 - 50% – by using PHP includes from the very beginning.
(It is possible to “shim” PHP includes into an already extant site, but doing so usually takes considerably more work: like most things, PHP includes are a technique that deliver their greatest value if you use them right the first time, when you are initially creating a site.)
Every server-side scripting language features some form of includes: you will also hear them referred to as server-side includes or SSI’s. In PHP, the process of using them goes something like this:
Make sure that the page you want to use the include on has a .php extension. (Note that if a server is confronted with an index.html and index.php page in the same location, it will preferentially choose the first. Be very careful when substituting PHP pages for HTML ones.)
Usually your content already exists on the page. Cut (CTRL-X) this content, taking note of its location in the code.
Make a new HTML page.
Remove all code from the new page. An include takes everything from the include file and puts it into place on the main PHP page: we only want our snippet of code to be placed.
Paste (CTRL-V) the code you copied from the previous page.
Save the HTML page with the snippet of code, with a filename that follows naming conventions: for example, header.html It is typical (but not required) to save the page in an includes sub-folder inside an assets folder.
Return to the original PHP page. In the exact location where the HTML code was removed, write the following (assuming that the assets folder is directly beside the PHP page):
<?php include('assets/includes/header.html'); ?>
Make sure that both the PHP page and the include file, along with any directories, are correctly uploaded to the server, and test them in the browser.
Make another PHP page that uses the same code to include the same file.
Note that a similar function to include exists in PHP, in the form of require. Both include and require work exactly the same way, with two exceptions:
The functions differ the way in which they handle failure. If include fails to find the file, the rest of the script proceeds as normal, and a printed warning is added to the page location where the include was written. The rest of the page will appear normal.
On the other hand, if require fails to find the file it is directed to, it causes a fatal error. All execution of the page stops, and the result is likely to be a fatal error message on an otherwise blank page.
include may be used as the action of a condition (i.e. inside an if statement, covered later.) However a file called by require will always appear on the page, even if it is placed inside a condition in which an argument is not met.
For these reasons, I usually stick to include to do a server-side include on a PHP page.
Taking things too far
It is common for overly-ambitious coders to see the potential of include and go somewhat overboard, with the equivalent of the statement “Wow! All my pages down to the opening <body> tag are the same code, so I’ll just make all of that code one giant include!” In doing so, they are forgetting that the <title> should be different on every page, and includes, as we have used them here, don’t differentiate between pages they are used on. There are ways around this, but it will take us a little time to get there. For now, think of consistent content in the body alone as being suitable for includes.
Alternatives to includes
Many dynamic scripting languages feature their own alternatives to include, as do other server-side solutions and programs. DreamWeaver, for example, uses what it refers to as “templates” to achieve the same ends. The problem with proprietary solutions is that you must use continue to use DreamWeaver (as an example) to edit template files from that point forward. And, in my experience, when proprietary solutions go bad, they go really bad. There can be compelling reasons to use a proprietary solution, but the fact that you can use a text editor (or anything else) to change PHP remains a strong argument in its favour.
After include(), date() is the first function that developers respond to with “Oh, that’s why I would use PHP!”
Before we get to the function itself, a small reminder: on the whole, HTML and CSS are stateless, which means (among other things) that they have no concept of time. The only way to place today’s date on a webpage using HTML is to physically write it out on the page, mark up the code, and upload it to the server… each and every day.
With PHP, placing the current day of the week on the page couldn’t be easier:
<p>Today is <?php echo date(‘l’); ?></p>
(That’s a lowercase L used inside single quotes for the date function.)
This piece of code demonstrates several important points:
PHP is, generally speaking, used for dynamic data, i.e. content that changes. In this example, we always want our paragraph to start with the words “Today is”, so it makes little sense to place those words inside a PHP statement. The only thing that changes is the actual name of the day, so that part is PHP.
echo can be used to print out strings, the value of variables, or the result of functions.
It is still important that the <p> tag be closed, and that there is a space somewhere between the word “is” and the day of the week.
The date() function works with “switches”: individual letters placed into the function to generate date components. date() can also be used to generate the time. A complete list of switches can be found at the php.net website entry for date(), but for now let’s use an example:
<p>It is now <?php echo date('g:i A')." on ".date('l j F, Y'); ?></p>
This will give us a much more verbose readout of the current day and time, for example : “It is now 3:07 am on Monday 31 December 2011”. (We will cover the use of the concatenation period used in the code in a later lesson.)
Answers
PHP is a server-side scripting language, so by default it reports the local date and time of the server. This is actually a good thing: servers are at a known place, and keep regular, dependable track of time, whereas clients can and will have any time they wish… which will sometimes be erroneous.
In order to update the time and date we would have to physically refresh the page. PHP is server-side: it only works after communication with the server. By refreshing the page we are doing the equivalent of sending the dumbwaiter used in our earlier analogy back downstairs with an order to “give me something new”. It would be massive overkill to have to do this every minute in order to have a counting clock on the page: if you wanted a ticking clock on a web page it would make much more sense to write it in JavaScript, which works client-side.
Using date() with includes
The date() function can also be used in includes. Oddly, you do not have to change the extension of the include file to do so. (This means that any PHP that you use on the included file won’t be color-coded correctly in programs like Dreamweaver, but that’s not a major issue. You don’t have to change the extension as any PHP in an included file is run after it is called into a PHP page.)
For example, let’s say you have a copyright notice at the bottom of every page of your website. Having thought ahead, you have decided to make this portion of code an include file, with the filename footer.html. In this file is the following code:
Your client is copyright-obsessed, and wants the copyright notice updated every year. Rather than using New Year’s to update the website every time, you can modify footer.html to become:
Like any other scripting language, PHP can manipulate variables: tokens that store values that can be altered or changed. There are a few points to note regarding PHP variables in particular:
In PHP a variable is created by having a $ sign in front of the variable name; for example: $foo.
The variable name must follow the standard naming convention we have kept to thus far. i.e. alphanumerics only, no spaces or other odd characters. A variable may start with an underscore ($_foo) but not a number. You cannot use the term $this as a variable, as it is reserved.
Variables are case sensitive. $foo is a different variable from $Foo. It is traditional to start a variable name as lowercase, and to capitalise any words appended to the name (aka camelCase). For example: $customerFirstName. camelCase is optional; the important thing is to be consistent in whatever naming convention you decide to use.
Variables in PHP are not typed or scoped: that is, by default they are not explicitly set for handling numbers, characters, or any type of data in particular. A variable can change from holding a number to a letter to an array at any time.
Variables take the last value they are set to. That is, you cannot make a variable that cannot have its value changed. (That, by definition, would be a constant). Remember that PHP scripts are executed “top down” just as XHTML is, in the order that it is written. A typical error by developers beginning with work with PHP is testing a variable via an if statement before setting it to a value.
Variables can be created “on the fly” at any point inside a PHP script, and by association anywhere on a web page; they do not have to be declared.
User-created variables are not global by default. That is, variables are not passed automatically between the pages of a website.
Variables may contain arrays, strings, and other variables. Variables are not interdependent; that is, setting $x = $y and later changing the value of $y will not automatically change the value of $x
Some variables are predefined. These can usually be identified by the fact that they are always written in uppercase; for example $_SERVER['HTTP_USER_AGENT']