The
tutorial is aimed at a user who has no previous experience with programming in
PHP or any other language.
PHP
stands for PHP: Hypertext Pre-processor. The funny abbreviation follows the
style set by Richard Stallmann when he founded
GNU As the name says, it's a pre-processor for
hypertext, which is just another word for what most people call webpages. Since
it's a preprocessor, it runs on the remote web server and processes the
webpages before they arrive to the browser. This makes it a so-called
server-side scripting language. The fact that it runs on the server has several
benefits, and some drawbacks. Lets take the benefits first:
·
On the server you can have access to things like a database.
This means that you can make a script that seeks through large amounts of data,
without the client has to download them first.
·
It's only the output from the script that is sent to the
client, not the script itself. That means that you can make the script
invisible from the end-user. That makes PHP-scripts browser-neutral; they don't
depend on some capability of the browser. It also means that you don't have to
worry that someone else can steal your carefully crafted script. It's not like
when you make a ?JavaScript --- everybody is able to read it in
the source of the webpage. It has to be this way with client-side scripting, or
else the client would be unable to get the source of the script, and therefore
unable to do any scripting.
·
You can make your own programs that you use in your scripts.
You could implement part of the script in C, and then call the program from
your script to make it run faster. PHP is a parsed language, meaning that there
are no compiled binaries. Every time someone requests a page with PHP-code, the
parser looks through the page and executes any PHP-statements it might find.
Fortunately this is a very fast process, but you might want to speed things up
if you have a very complicated script.
When you make a C-program, you compile the source and
then run the resulting binary. This makes PHP slower than an equivalent
C-program.
As I said, there are also some
drawbacks:
·
By executing everything on the server, you put more strain
on it. With many concurrent requests, and large complex scripts, the server
might not be able to handle it. But this isn't a real constrain because the
parser in PHP is so quick. And if your still can't cope with the number of
visitors, then you'll should be able to generate some revenue from banners on
your site, and then pay for a bigger server :-)
·
The pages can't do anything themselves --- you need the
server to do the magic. This means that the pages will lose some of their
functionality if your visitors decide to save them to their computer.
You could of course still put some ?JavaScript in your pages. This is a very
powerful combination between server- and client-side scripting. You could use
PHP to fetch some values from a database, and then setup your variables in the ?JavaScript with these values.
In my opinion the benefits clearly
outweigh the drawbacks (that's the reason I'm using PHP :-). And I'm not the
only one --- an increasing number of websites are using
PHP.
PHP is actually a rather simple
language, despite its great powers. It's a very young language, so the
developers have had the chance to learn from previous language’s mistakes and
their strengths. Much of the syntax is borrowed from C. This is reflected in
the different conditional statements, the loop-structures, the Boolean
operators and the assignment of variables. Since C is probably the most common
programming language today, this should make PHP easy to pick up. Even if you
don't have any previous experience with C you should be able to learn it
quickly. I certainly have, and now that I have started to look at C, I can see
how much of the syntax they have borrowed. I can just apply the techniques I've
learnt from PHP when I program in C. Of course this is only true as long as you
only write simple programs in C, since C is a "real" programming
language, suitable for writing operating-systems in or the like.
But another thing that makes PHP
easy to learn is its relaxed way of dealing with the types of variables. Its
very simple: you don't have to think of the types of variables at all! If you
assign a number to a variable, then it just works. When you later try to output
the variable to the browser it also just works. PHP takes care of converting the
variable from an integer-type to a string-type, on the fly and automatically.
To make matters even simpler, you don't even declare your variables --- you
just assign a value to them, and then they are ready. If you are an experienced
programmer (and especial if you program in Pascal) you might say: "This
can't be real! There's no syntax in this language. When you just declare
variables like that you don't have any control --- you don't even know what
type a variable is!" All I can say to this is: It really doesn't matter
--- most of the time you're interested in the value of the variable, not its
type. And if you really want, then you can indeed find out what type a given
variable is. It could come in handy if you want to check to see if a parameter
to a function really is of a given type.
Because PHP is meant to be used
with webpages it has a lot of functions to deal with text. Generally you can
say that PHP is specially designed to deal with webpages, and doing so quickly
and efficiently. Because of that most of the built-in functions are simple and
straightforward to use.
Being web-oriented, PHP also
contains all the functions you'll need to do things on the Internet. There are
functions for connecting to remote webservers, checking mail via POP3 of IMAP,
or urlencoding strings to protect special characters.
Together with a good manual, you
have all the help you'll need. And if you get stuck --- then you can count on
the community. There has been written a lot about PHP on the net (you are
reading just such a thing now :-) and there's countless mailings-lists you can
subscribe to.
Now I've told you about how easy
PHP is, and how many things you can do with it. Let's see it in action then.
Included
from PhpTutorial/Action
As in all good tutorials, we start
with the (in)famous HelloWorld
example. Here's the code:
<html>
<head>
<title>Hello
World</title>
</head>
<body>
<?php
/* This is a comment - it
will be ignored by PHP and will not show up
in the
final output. */
echo "Hello
World";
?>
</body>
</html>
You should save this piece of code
in a file with the extension .php. If that doesn't work, then try other
extensions like .php3 or .phtml. If you can't figure out the right extension,
then ask the one who installed the webserver. If that's you, then have a look
at the file called httpd.conf - if you're using Apache that is...
It should contain a line that
looks like this:
AddType application/x-httpd-php .php
Back to the example, which is
somewhat silly. But it can be used to teach you a few things anyway.
Most of the code is just plain
HTML. Only the part between <?php and ?> is PHP-code. You use either <?php
or just <? to start the code and ?> to stop it again. The parser works
within these two tags. Between the <?php and ?> you put a number of
statements, which all must be ended by a ;.
Between the two tags there is a
comment and one statement, echo "Hello World";. The comment will be
completely ignored, and the statement just prints the string "Hello World"
into the webpage, which is then sent to the browser. After the parser has
processed the page, the final output that is sent to the browser looks this
way:
<html>
<head>
<title>Hello World</title>
</head>
<body>
Hello World
</body>
As you can see, there's no trace
of the PHP-code left in the final output. In the following code-snippets I
won't include all the HTML-code.
You should think of a PHP-script
as a normal web page written in HTML, since most of the page is still just
plain-old HTML. But between the start- and end-tags (<?php or <? and ?>)
the PHP-parsed spices the page up with possibly dynamic content. You'll need to
read PhpTutorial/Variables for dynamic content, so go there now.
Included
from PhpTutorial/Variables
Before I show you any more
examples I better introduce you to the different kinds of variables we have in
PHP. Variables are what you use to store something for later use. You might
want to refer to your age, so it would be nice to define the age only one, and then
just refer to it later. When your age change, you just update the definition of
you age, and then all other calculations that refer to the age are also
updated. All the names of the variables must start with the $ character. After
that there must be a letter. The rest of the name can consist of both letters
and numbers. Here are three examples of valid names for a variable: $name, $address2
and $colour_30. As you can see, you can also use the _ (underscore) character
in your names. It is often used as a replacement for spaces, since they are not
allowed.
To use a variable you have to
assign a value to it. It is done this way:
$name = 'Martin';
The name of the variable is on the
left of the =-sign and the new value of the variable is on the right. Here we assign
the value of 18 to the variable $age:
$age = 18;
There are several different types
of variables. You have already met the integer and string types. Lets start
with the integer type.
Dealing with numbers are easy with
PHP. You can just use them as you'll like. All the normal rules about
precedence apply, so you can write something like this:
$a = 4;
$b = 7;
$c = 2 + 3 * $a + 5 * $b /*
This is evaluated as 2 + (3 * 4) + (5 * 7) = 49 */
As you can see, everything works
as you would expect. Any variables are automatically substituted with their
values. This is done before the new value is stored in the variable on the left
side of the =-sign. This means that you can do something like this:
$a = 5;
$b = 10;
$a = (2 * $a + 5)/$b; /*
$a is now equal to 1.5 */
To assign a string to a variable,
you must use quotes. You can chose between single quotes (') or double quotes (").
The kind of quote you should choose depends on the string you work with in a
given situation. There are some differences between the two types of quotes,
which the following code should demonstrate:
$first_name = 'Martin';
$greeting1 = "Hello, my first name is $first_name.";
echo $greeting1;
$last_name = "Geisler";
$greeting2 = 'Hello,
my last name is $last_name.';
echo $greeting2;
This code produces the following
output:
Hello, my first name is Martin.
Hello, my last name is $last_name.
Why was in only the first string
that worked probably?, you might ask. The answer is, that when using double
quotes PHP performs what is knows as variable-expansion. That means that PHP
expands (substitutes) $name with it's value, just as you saw it when using
numbers. The result is that the string stored in $greeting1 is "Hello, my
name is Martin." (the quotes is not part of the string stored in $greeting1).
When assigning to $greeting2 using single quotes, PHP doesn't substitute any
variables.
But there's more magic with the
double quotes. They will also expand other special characters, such as
newline-charecters (\n). This mean that the following string:
echo "Martin\nGeisler";
will look like this in the source
of the page:
Martin
Geisler
You've met the echo statement
before (in the Hello World example) and it just outputs the string after it to
the webbrowser. As I said earlier there's no trace of the PHP code, but notice
that there's a linebreak between the two words. (The linebreak can only be seen
in the source of the page, because the webbrowser treats the linebreak as a
normal space.) You should also notice that there's no space before or after the
\n-character. Because you use the \-character to indicate that the next
character is special, you have to write \\ when you want to have a single \.
The backslash (\) is called an escape-character, since it makes the characters
escape from their normal role. The escape-character also has to be escaped.
If you want to have a $-charactar
in a string enclosed in double-quotes, you'll need to escape it, or else PHP
will look for a variable, since all variables start with a $.
This string will give you a little
problem:
$name = "Martin
"gimpster" Geisler";
If you try it out, you'll get an
error. That's because the parser expects the string to stop after the second
double quote, just before the word gimpster. The rest of the line is just
garbage to the parser so it complains loud. Perhaps it would help if we escaped
the double quote? Exactly! The following string is correct:
$name = "Martin
\"gimpster\" Geisler";
The same applies if we had been
using single quotes throughout the string. But there's another way to solve the
problem. You could quote the string with single quotes and then use as many
double quotes within the string as you would like. Or you could do the inverse,
and enclose the string in double quotes and use single quotes in the string.
This solves a problem you would have when outputting HTML-code with lots of
double quotes:
echo '
<a
href="mailto:gimpster@gimpster.com">
<img
src="image.gif" width="16" height="16"
alt="me" border="0">
</a>';
If we had quoted the string with
double quotes, we have had to escape all the other double quotes. But on the
other hand, in the string above PHP wouldn't do any variable-substitution.
Also, the escape-characters will not be understood, so you can't write \n in a
string enclosed by single quotes. Instead you can put the newlines directly
into the code, as I've done in the example. The final output will still contain
those newlines.
If you want to concatenate two
strings you use the .-character (dot or full stop) like this:
$first_name = 'Martin';
$last_name = 'Geisler';
$full_name = $first_name.$last_name
Now $full_name will contain the
string "MartinGeisler". That's probably not what you wanted, it would
be better with a space between the two words. To do this, you execute the
following code:
$full_name = $first_name . '
' . $last_name
Notice that the space between the
variable-name and the dot is ignored --- it's the string with the space that's
important. You use the dot (full-stop) each time you have two strings that you
need to put after one another.
But you've also seen how this
could be solved using variable-substitution. This is often easier to read, just
remember to use double-quotes around the string. So this code gives the same
result:
$full_name = "$first_name $last_name";
Arrays are a single variable that
can hold a number of different values at the same time. To access the different
values you specify them by using brackets after the name. It works like this:
$name = "Martin";
$name = "Geisler";
Now we have made an array, and
filled in the two first slots. Notice that the numbering starts at zero and not
one. We can recall them like this:
echo $name . '
' . $name;
If you don't care which slot you
get when you assign to an array, then use a pair of empty brackets after the
name:
$name[] = "Martin";
$name[] = "gimpster";
$name[] = "Geisler";
This filled the first three slots
of the array. When you want to retrieve the information again, you must specify
which slot you want access to. But you can also identify the different slots by
name. This makes everything much more readable and easy to understand:
$personal_data['first
name'] = 'Martin';
$personal_data['nickname'] = 'gimpster';
$personal_data['last name'] = 'Geisler';
$personal_data['age'] = 18;
echo 'Hello ' . $personal_data['first
name'] .
'!
We know that you are ' . $personal_data['age'] .
'
years old.';
Notice how I broke the last line
to make it shorter and how I used the dot operator to glue the strings
toghether with the variables. The parser will ignore all whitespace, and the
result is:
Hello Martin! We know that you are 18 years old.
Also note how I split the string
up into its individual pieces. This is often nessecary when dealing with
associative arrays. The problem occurs when you try to specify the slot using a
string with a space in it. For some reason you can't just use single quotes
within another string, so the easiest way to deal with the problem is simply to
split your string up into its pieces. But despite this little annoyance, please
do use descriptive names for the slots in your arrays. It makes everything more
clear, and helps to understand what the different slots are intended for.
Now that we have seen how to
assign values to variables, lets have a look at the different control
structures there is in PHP: PhpTutorial/Control.
Included
from PhpTutorial/Control
You use control-structures to
control the flow of execution through your program. If you didn't have any of
these control-structures, all your scripts would always do the same. So let's
get on with it.
We start with the if-statement.
You use the if-statement to execute different parts of your script based on the
truth-value of an expression. The expression could be something like $a > 5.
This tests to see if the variable $a is greater than 5. If so, the expression
is true, and the next part of the if-statement is executed. If the expression
is false, then the optional else-part of the if-statement is executed. In a
script it would look like this:
if ($a < 5) {
$b = $a + 10;
} else {
$b = $a * 2;
}
If the part between the
parenthesis, (), is true, then the statements between the first pair of curly
parenthesis, {...} is executed. Else the part in the curly brackets after the else
keyword is executed. You don't have to provide a else-part, if you don't then
nothing will be executed if the test fails.
You can have all kinds of
statement between the parenthesis and the curly parenthesis. PHP is a language
where almost every statement has a value, a value that can be used together
with other values to build big expressions.
Take an assignment for example.
The statement $b = $a actually has a value, namely the value of $a. This means
that you can use this value in another assignment, like this:
$c = ($b = $a);
The assignment in the parenthesis
has the value of $a which is then assigned to $c. You can actually drop the
parenthesis, the result is the same: all three variables have the value of $a.
This allows you to understand a statement like this:
/* Initialize
counters: */
$i = $j = $k = $l = 0;
To compare the value of a variable
up against other variables of numbers, you have a number of different
comparison-operators:
Operator Meaning
-------------------------------------------
== Is equal to
!= Is not equal to
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
&& and The first and the second is true
|| or The first or the second is true
Using these operators you can
construct every Boolean expression you'll ever need. Take for example the
following if-statement:
if ($a <= $b && ($array[$a] <= $array[$b] || $array[$a+$b] > $array[$a-$b])) {
/* Do something useful - this
is a comment, it won't be executed */
}
This if-statement first test to
see if the variable $a is smaller or equal to the variable $b. If that is true
the next part is executed to see if that is also true. This is done, because
we're using &&, which means that the first statement and the second
statement should be true.
The second part uses $a and $b as
indexes in an array. If the first part is true, then the second part won't be
executed. We're just interested in if the test is true, which it is, if the
first or the second test is true. So there's no need to evaluate the second
test, if the first is already true. This means that you can execute the
following statement:
mysql_connect() or die('Could
not connect to the database!');
The function mysql_connect() tries
to make a connection to a MySQL database. It returns true if it was able to
make a connection. PHP evaluates the line an a Boolean expression. That means
that it starts by executing mysql_connect(). If it returns true, then PHP skips
the next statement because we use or. The second statement makes PHP stop with
an error message, if the first statement fails. As you can see, you can make it
as complicated as you want.
There are other control-structures:
The for-loop is useful when you
have to have the same task repeated a number of times. The for-loop works by
first initialising a variable, then do a test, and if it is true, then execute
some code. After the code have been executed do some other code, that will
increment the variable and then execute the main-code again. An example will
properly help:
for ($i = 0; $i < 10; $i++) {
echo $i;
}
"Hmm, now he introduced
several new things again" you might think. And you're perfectly right. First
lets have a look at the for-loop.
It first assigns a starting-value
of 0 to $i, then it tjeks to see if $i is smaller that 10, and if so, the echo-statement
is executed. At the end of an iteration, (one pass of the loop) the $i++
statement is executed.
This is a shorthand of $i = $i +
1;. It simply increments the variable by 1. Simelary you could write $n--, that
would decrement the variable $n by 1.
The main-code is executed until $i
is larger that 10, so our little for-loop simply prints the numbers from 0 to 9
into our webpage.
The while-loop is very similar to
the for-loop. It works like this:
while (something is true) {
some statements
}
It is used when you don't know in
advance how many iterations you'll need. If you look close, then you'll see
that each for-loop can be made into a while-loop and that each while-loop can
be made into a for-loop. This is because a for-loop like this (where a, b, c,
and d are statements):
for (a; b; c) {
d;
}
works completely like this while-loop:
a;
while (b) {
d;
c;
}
You'll often see a while-loop
being used to run though an array like this:
while (list($key, $val) = each($array)) {
echo "<p>$key => $val</p>\n";
}
The condition in the while-loop
uses several functions and an assignment. Each time the function each() is
called, it returns an array with the key and value from $array. When there are
no elements left in $array, each() returns false - this is what makes the whole
condition false and makes while-loop stop.
The list() function can be used on
the left side of an assignment to extract values from an array. You can use list()
like this, although it would be much easier to assign the variables one at a
time:
list($a, $b, $c, $d) = array(1, 2, 3, 4); //
$a == 1, $b == 2, $c == 3, $d == 4
So the condition in the while-loop
prepares $key and $val for the body of the loop. When all key-value pairs have
been examined, the loop terminates because each() return false, while then
becomes the value of the assignment, and therefore the value of the condition.
After you've run through the array
like this, each() will return false if you use it on the same array. You'll
have to call reset($array) to make each() start from the beginning again.
The next page is PhpTutorial/Functions.
Included
from PhpTutorial/Functions
Functions are very useful, so you
should make sure that you use them when ever possible. By putting your code into
functions, you make the code easy to reuse. So whenever you locate an error in
you function, you only have to fix it once. Using functions also makes your
code more readable and easier to understand. Let's start with a simple
function:
function foo($arg) {
if ($arg < 10) {
echo "$arg is less than 10";
} else {
echo "$arg is greater than or equal to 10";
}
}
This piece of code declares a
function called foo. It takes one argument, and it echoes different things,
based on the value of that argument. You use the foo function in your other
code like this:
foo(15); /*
Echoes "15 is greater than or equal to 10" */
Isn't that simple? You can also
make functions that don't have any arguments, just add an empty pair of
parenthesis after the name of the function, both when you declare the function
and when you use it.
If your version of PHP is below 4
(use the function phpinfo() to learn all sorts of things about PHP) you have to
declare your functions before you use them. That isn't necessary with version 4
and above. You really should use at least version 4, as it is the latest at the
time of writing.
You often need your functions to
return a value you can use in your programs, and here is how to do that: simply
use the return statement.
function bar() {
return (time() - mktime(0, 0, 0, 1, 21, 1982))/86400;
}
This function has no arguments and
it returns the number of days since the 21st of January, 1982 (my birthday :-)
It uses a number of different built-in functions to get the time now, and then subtract
the time I was born, and finally divide the time with 86400, the number of
seconds in a day. Before we return the number, we round it with the round()-function,
which will round the number to an integer.
Under UNIX all times are measured
as the number of seconds since the beginning of the Epoch, which was in 1970.
So when you deal with times as I just did, you are just dealing with rather
large integers (around 950,000,000). That makes it very easy to find the time
between two events.
You will use the bar function like
this in your scripts:
$days_ages = bar();
If you instead wanted to round the
floating-point number to a certain number of decimal places, then it's easy to
make your own function:
function smart_round($float, $dec) {
if ($dec == 0) {
return round($float);
} else {
return floor($float * pow(10, $dec) + 0.5) / pow(10, $dec);
}
}
$a = smart_round(2.317, 2); /*
Now $a is equal to 2.32 */
This function $float rounded to $dec
decimals. The php-function:round
has been changed in recent versions of PHP to handle a second argument like the
smart_round function.
A new feature in PHP4 makes it
possible to use an entire file as a function. This makes it possible to save
all your really cool functions in different files, and then use them in
different scripts. This expands on the concept of code-reuse, as I talked about
earlier. All this is possible thanks to the improved include
language-construct. It can now return a value from the script included. So if
you make a file that uses the return statement, you can include that file
instead of calling a function. Assuming that we have the file foo.inc and
another file called script.php. The contents of foo.inc is a follows:
/* Always
remember that you must start with a <?php tag when you
include files. The parser
drops out of php-mode when it includes a
file, so you have to get it
back again */
return (time() - mktime(0, 0, 0, 1, 21, 1982))/86400;
Then you could write the following
in script.php:
$days_aged = include('foo.inc');
That works just like the other
example, except that you have reused the code from an external source.
You've now seen most of the basic
features of PHP. There's only some PhpTutorial/Links left for you.
Included
from PhpTutorial/Links
Now that you've learned the basics
of PHP, you should be able to write your own PHP-scripts.
The best way to learn more is to
read other peoples code.