A Crash Course in PHP
Jim Methley
jim@logical-progression.org
A quick-and-dirty, yet pleasingly
thorough introduction to the thinking behind programming for
websites with PHP Hypertext Processor, and the concepts necessary to
start throwing your weight around with other PHP programmers This guide is intended as an aid to
people who want to know what all the hoo-hah is about, and who want
to start programming simple pages of their own in PHP.
25/10/2003
PHP's environment
Why bother with PHP?
To understand the big thing about PHP, you've got to understand what happens if you use traditional methods of presentation and processing on the web. Incidentally, I'm not claiming that this is the only way of getting these results, or that CGI is in any way 'rubbish' – I'm just stating an opinion about which prefer.
In an HTML+CGI environment, a server has to work VERY hard to process any reasonable web-based application. The majority of web applications are used to process data input from a web across the web. This data is passed from the web server to a CGI gateway program written in one of a wide selection of languages, which processes the information, and then passes it back to the server, which then puts that information into another HTML page and sends it back to the requesting browser. If it sounds like I'm trying to make this sound like a mess, that's because I think it is. Maintenance in environment like this just sucks. It's not a fun job, and you are working very hard if you have more than one site to maintain. Even if you run just your own small site, you are doing far more work than is necessary to do that task you're trying to do. It's not even one of those situations where you get a deeper understanding of what's going on because you're working at a deep level. You just waste a lot of time.
With PHP, you can concentrate on doing the job you're trying to do – processing credit cards / processing mailing list applications / whatever, with a massively reduced admin overhead. You are dealing with ONE language, and very often you can cut the whole 'CGI send and fetch' cycle out – the execution doesn't get outside of the webserver itself and the whole process can be understood by reading the one PHP page itself. One downside is that PHP pages can be very large in complex environments, and with multiple includes, it can get a little hairy, but this is a case where deeper understanding IS achieved by working at this depth.
PHP is easy on the eye, quick to learn, logical, and also powerful. It's like programming in any other less 'distributed' language – C/C++/Visual Basic, et al – but it's so well integrated into the way that the web works that programming for websites is trivial, even if you want to punish yourself by using databases :)
Relationship with Apache
I'm concentrating on the use of PHP with Apache in this guide, but the general idea as far as PHP as a module is concerned is applicable to them all – IIS5 in particular.
When you get hold of a new copy of Apache for Linux, you tend to go away and compile it from source. When you do this, you make sure that you tell Apache that it will be dealing with PHP on a near-constant basis, and to prepare itself for this fact. Apache then, rather obligingly, sets itself up so that PHP IS PART OF THE SERVER. When this is done, you install Apache and give PHP a test drive. The execution of the PHP code is done within the software of the server, and it's pretty fast, even for an interpreted language. This is 'compiled-in' PHP
The other way of running PHP on the server is as a module. In this case, the server does not have PHP as a part of its actual structure, but after the server loads, it loads another program and keeps it very close for immediate use. This other program is the PHP module, and is an EXTENSION of the server. There are many modules for Apache, and PHP is only one of them. More details are available at the PHP and Apache websites.
Relationship with the browser
As
far as the browser is concerned, PHP doesn't exist as anything other
than a three-letter extension in a filesystem. PHP acts solely on the
server, and the browser is never the wiser. This means that whatever
you do with PHP, you have to make sure that it looks like a regular
HTTP transaction if you want a browser to read it. Most problems with
PHP websites are that they hand back 'nonsense' as far as a browser
is concerned.11 As far as the browser is concerned, PHP doesn't exist
as anything other than a three-letter extension in a filesystem. PHP
acts solely on the server, and the browser is never the wiser. This
means that whatever you do with PHP, you have to make sure that it
looks like a regular HTTP transaction if you want a browser to read
it. Most problems with PHP websites are that they hand back
'nonsense' as far as a browser is concerned.
Elements of PHP programs
PHP program
A PHP program starts with the tag <?php and ends with the tag ?>, like this :
<?php
...PHP program statements...
?>
And, generally, the program is saved with the .php suffix. Here's a sample program for the (in)famous 'Hello World' program.
<?php
echo “Hello World!”;
?>
If you save this as 'index.php' in the document root of any web server, then you'll get the output
Hello World!
In any web browser you point at the server.
Variables
Variables are storage areas for values that change. They associate a name with a value. For example, when you talk about the rate of VAT (a value which occasionally changes), you are associating the name 'VAT' with that value 17.5%. The rate of VAT is a variable, the label 'VAT' is the variable name, and the number '17.5%' is the variable's value.
PHP variables consist of a dollar sign followed by a name to identify the value in the variable. Examples would be :
$time
$user_name
$address_line_2
$database_permissions
Variables are the 'unit of currency' in programs, and they hold the data that the program works on. The names themselves are only allowed to have numbers, letters, and the underscore character (_) in them.
Operators
Operators are the symbols we use in maths, and a few others for comparing values.
For example we have '+'and '-' (addition and subtraction), '*' and '/' (multiplication and division). The comparisons 'AND', 'OR', and 'NOT' are also operators and come into play in expressions, as would the '==' (equal to) '!=' (NOT equal to) and '=' assignment' operators.
It's worth mentioning the last three operators again because they are used a lot, and frequently confused for each other, even by experienced PHP hackers.
$speed != 400 means 'speed IS NOT equal to 400'
$speed == 400 means 'speed IS equal to 400'
$speed = 400 means 'SET speed TO 400' (assigns a value)
Expressions
Expressions change or compare variables. They describe a set of circumstances – usually very simple – which is used to influence the program's behaviour.
Examples of sets of circumstances would be :
'Set the current user's name to Jeff' or 'The current speed is NOT 400'
An example of these expressed in PHP would be :
$current_user = “Jeff” or '$current_speed != 400'
Statements
Expressions alone can't do much. They just describe the circumstances that the programmer identifies as being important enough to change the program's flow. To actually change the flow (and to do any other meaningful job) requires a statement.
A statement in English would be something like :
“Take the current speed and print it on the screen”
and in PHP would be written as the statement :
echo $speed;
The statement uses the keyword 'echo' and the variable '$speed'. The result when the program runs is to print the value of the variable $speed. Note that the line ends with a semicolon. This is a dead giveaway that this line of code is a statement.
A keyword is a word that is part of the PHP language. You can't change the a keyword like you can a variable, and it's not a good idea to create variables that have the same name as a keyword (e.g. naming a variable $echo). The reason for the latter is that it can get very confusing and introduce unnecessary confusion.
That was a very simple statement, consisting of a keyword, a variable and a semicolon to show the end of the statement, but statements can get as complex as you like. For example :
'Take the credit card number given by the user, add up all the digits, divide the result by 3, then add the card issue number to the result. If the result of this is not equal to the security code number they gave you, tell them that they have entered an invalid card number'
can be written in PHP as :
'if (($card_no /3)+$issue_no) != $security_no)
{
echo “Invalid card number – sorry.”;
}'
The statement listed here is more complicated than the 'echo $ speed' statement, but follows exactly the same rules, and is in fact simply a series of expressions and smaller statements rammed together. As an aside, note how much more compact the PHP version of the English statement is.
When you put enough statements together to do something meaningful in the way that you intend, then you have your program.
Arrays
Arrays belong to a class of programming tools called data structures. Other types of data structure are such exotically named creatures as linked lists, n-trees, circular buffers and roses. Data structures are basically organisations of variables. A set of variables are grouped together in a specific way, then given a common name and some method of getting data in and out of them. Only arrays will be covered here, but the other types of structure are all routinely covered in programming tutorials.
There are two basic types of array – the one-dimensional array, and the two-dimensional array. A 1-D array is like a list with a name. For example :
SHOPPING
Cake
Trousers
Marmalade
Chin cream
Cheese
The array here is called 'SHOPPING'. The first element (item) in the list is 'Cake' and the last is 'Cheese'.
A 2-D array is like a table :
USERS
|
Alice |
Bob |
Chris |
|---|---|---|
|
IT |
Accounts |
Security |
|
5 |
4 |
8 |
Alice's details occupy the first column, Bob's the second and Chris's the third. Alternatively, you could say that Names are on the first row, Departments on the second, and Floor Occupation is on the third.
You access data in all arrays the same way – by giving a subscript. In a 1-D array you just give the cell number that you want to write to or read from in square brackets - e.g.
$shopping[3]
In a 2-D array, you give the column number, followed by the row number –
$users[4,4]
The best way to think about arrays is to think of pigeon holes in a post office. Imagine a wall in a post office which is covered in pigeon holes for items to be put in until they are collected. This actually is an array. To put something in an array, you tell the program which pigeon hole you want to put the item in, or which item you want to take out.
Two things to remember about arrays :
in many programming languages, arrays are fixed-size items. This is not so in PHP – you can add to the BACK END of arrays, and the array will grow to accommodate the new data. Inserting into the MIDDLE of an array is still a lengthy not-worth-the-effort kind of job.
ARRAYS START COUNTING AT ZERO. The first element in our SHOPPING array is $shopping[0] NOT $shopping[1]. Likewise 'Alice' in the USERS array is $users[0,0] NOT $users[1,1].
Functions
Functions are cool. They allow us to extract a bit of a program, package it up and give that part a name. It saves us writing out the same piece of code over and over again.
An example would be if you wrote a PHP program for a website which took a name and address and printed them out in BOLD CAPITALS. (Why would you do that? No idea, maybe you're writing a basic PHP course and you can't think of a better example.)
What you want to do is take two items of data, and change the way that they are formatted. If you didn't use a function, then you'd probably end up repeating yourself when it came to emboldening the text. With a function, you can side-step the repetition, and save your keyboard a lot of hammer.
Here is a part of that page for doing this without functions :
$name = strtoupper($name);
echo “<B>$name</B>”;
$address = strtoupper($address);
echo “<B>$address</B>”;
The repetition here is evident, and it would be better if we could do this some other, more economical way. Luckily, functions allow us to do just that.
We declare a function, and then when we want to use it we invoke a function. Declaring a function is where we tell PHP what the function should do and is normally done right at the start of a PHP page before any of the actual work of the page gets started :
function boldcaps($string)
{
$string = strtoupper($string);
$string = “<B>$string</B>”;
return $string;
}
When it comes to actually using (invoking) our function, we use the function almost as if it were a keyword :
echo boldcaps($name);
echo boldcaps($address);
This is a bit of a contrived example, but it demonstrates the value of functions in clearing up the body of the code and making the steps of the program clearer (arguably as important as making the program work in the first place).
Building a function is quite simple – take a look at the boldcaps function declared above. It starts with the function keyword, gives the name of th function, and then is followed by a parameter. Parameters are values that are passed to functions which are then worked on by the function.
The final statement of the declaration is the return statement which hands back the modified value to the part of the program that invoked it. In the case above, the 'echo' keyword will print out a bol, capitalised version of the $name and $address variables. These are the function invokations, and they are simply the function name followed by a variable in brackets, which will have something done to it (in this case, rather cheesily turned into BOLD CAPITALS)
Inclusions
Inclusions are very helpful when we want to re-use old code that works well for a new problem or if we want to put an external chunk of information into our program when it is run.
An example of each of these two situations would be :
You are writing a 'Pay Me!' page using a downloaded credit card number validation system to save yourself writing your own. Include it – it will save you weeks of work.
You are using a generalised HTML page you designed earlier, and putting names into slots using PHP. Why have the HTML in the page when you are debugging? It just adds to the clutter! Include it at runtime and save yourself the price of a wig.
On top of the convenience of an include is the incredible simplicity of doing it. Just say :
include “general-page.html”;
and the page you want will be inserted into the page you are editing at run-time (when the program is running).
One thing to note is that if you want to write a php program that is only intended to be included into other programs, it has to have the <?php and ?> tags of a regular program. If you don't do this, you'll see the TEXT of your script included into the page you've written, and you won't be able to use the code itself.
It is also the convention to name these programs <whatever>.inc as opposed to <whatever>.php.
Language constructs
There are a lot of these, but basically they fall into one of three categories :
ITERATION
DECISION
STATEMENT
Iteration
Often called 'Loops' these statements make a piece of code repeat until certain conditions are met. For example, a program might print information until the end of the information is reached. A loop would do this, with each line of information being echoed until there was no more information to echo. The programmer would expect this to happen, and say what to do after the information is exhausted.
Decision
The most common example of a decision statement would be an if.. construct. An 'if' takes an expression, and if the expression turns out to be right, then it executes some code. If the expression is not right, then some other code will be executed instead
Statement
We've already mentioned statements, and how to construct them. They perform the meaningful work in the program. They say “what has to be done”.
Input from a web page
Input from a previous form-based web page isn't difficult if you have worked with forms before. If you haven't worked with HTML forms, here's how to operate one :
Forms are a way of getting information to a server. A form has four vital elements (and several optional extras to help make things easier - see any book on HTML)
A FORM element looks like this :
<FORM method=”POST” action=”form-processor.php”>
<INPUT type=”text” name=”name”>
<INPUT type=”text” name=”address”>
<INPUT type=”submit”>
</FORM>
A method
A handling script
Input from the user
A 'submit' button
The Method (method=”<method type>”)
The method is the way that the data moves from the browser to the server. There are two methods – POST and GET.
GET data is shown in the address bar of the browser you use, and is legible to the user. It travels as part of the URL request to the server. It is also frequently limited to a given number of characters (usually 256) which means that items such as files, wavs, jpegs, etc cannot be uploaded to a server via GET.
POST data is hidden from view, and travels to the server as part of the HTTP request. As a result POST data (theoretically) doesn't have a limit on its size, and can include files as uploads.
Either way, when you pass variables from your web pages to your server to influence the content of subsequent pages, you've got to specify how you want the data to travel – GET or POST.
The Handling Script (action=”<handling script filename>”)
When the data has been entered, you need some way of processing the input. For example if you are given a name by a user, you will be doing something with it and the handling script does it. Whether that is store it, reverse it and print it out, find out if this person has visited before or whatever, you need to process it.
The 'action' property of the FORM tag tells the server what program will process this particular data input. It is a filename. When the data arrives at the server, it will use this file to process the incoming data, and in our case it would almost certainly be another PHP page.
Input from the user (INPUT type=”<Input type>” name=”<variable name>”)
This is the actual data entry area presented by the page. Data entered here will be passed back to the server with the name given by the name property. The data entered should be of the type stated in the 'type' property. In the above example, two items of text will be sent to the server – one named (rather imaginatively) 'name' and the other named 'address'. This is the data that will be acted upon by the form processor.
Submit Button (INPUT type=”submit”)
Users generally hit some sort of input button to send data to the server. This is the 'Go' button for the form.
The FORM tag will be explained a lot more thoroughly (not to mention a lot better) in any HTML guide, but these are the essentials to getting data from a user, across the web, and into your PHP programs.
Output to a web page
Outputting content to a web page is very simple. Basically, output consists of the keyword 'echo' and a couple of other specialised versions of the well-known (if you write in 'C') C function 'printf'.
This crash course will use only the 'echo' keyword, as it's uncomplicated, generalised and above all easy-to-understand nature makes using anything else a bit questionable, even in the tightest of corners.
Use it :
echo “<whatever you want to output>”;
One thing to mention about echo – in most programming languages, you have to do the following :
echo “This is the “ + $count + “ th time that you have visited”;
Not so in PHP. PHP has been designed with this sort of thing in mind. You can just write :
echo “This is the $count th time you have been here”;
Outputting images such as jpegs, gifs, pngs, etc is simply a matter of reading them into a variable, sending an HTTP header such that the receiving browser will understand that a picture is on its way and to interpret the data as such, and then echoing the variable. That's about as complicated as it gets.
List of Operators
++,--
*,/,%
+,-
<,<=,>,>=
==, !=
&, and, &&
^, not, !
|, or, ||
.=,+=,*=,-=, etc.
PHP resources
On the Web
In books
Professional PHP4 Wrox
Magazines
Linux Format Regular PHP series