The tutorial is aimed at users who have no previous experience with programming in PHP or any other language. But there's no guarantee that this goal has been reached. It's very likely that there are places where the user is assumed to know things he or she won't know at this point of learning PHP.
MartinGeisler wrote this tutorial after having used PHP for some time. Because of that, some sections of the tutorial might be difficult to understand --- it's hard to remember afterwards how difficult things were. So if you have any problems with parts of the tutorial, then please mail him and give your advice. Or even better: edit the page directly in your browser. The pages in the tutorial (except this one) can be edited freely so please use this chance to improve the text. The only requirement is that you choose a proper WikiWord as your login name --- no registration is necessary, this is just a way for you to sign your change.
You can make your own programs for 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:
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 implement 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 (like me) 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 learned 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 it's 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 especially 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 or IMAP, or url encoding 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 a lot written 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.
Here we'll go through how you would install PHP.
The first thing you'll have to do, is to grab the source for PHP from . Then grab the source for the Apache webserver from http://httpd.apache.org/download.cgi
Instructions can be found at http://www.php.net/manual/en/install.unix.php.
Instructions can be found at http://www.php.net/manual/en/install.windows.php.
Another possibility is to download and run PHPTriad from http://www.phpgeek.com/. This installs the very popular triad of programs: PHP, MySql and Apache. It should be very cool and very easy.
And Im A gay tossa ahahaha wankers
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>
<p>
<?php
// This is a comment that extends to the end of the
line.
/* This is multi-line comment. Comments are ignored by PHP,
but provide valuable information to people reading the source.
*/
echo "Hello
World!\n";
?>
</p>
</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 whoever 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
Anyway --- this line informs Apache that files ending with .php
are PHP scripts. Thanks go to Jon-o Addleman jaddle@po-box.mcgill.ca
for suggesting that I should write this piece.
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, each of which must be ended by a ;
(a semi-colon).
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> <p> Hello World </p> </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, but remember that you'll have to use HTML if you want your PHP scripts to work on the net. You'll also have to include the right HTML codes in the strings you output from PHP, if you're outputting more than just very simple strings.
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.
$
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 is easy with PHP. You can just use them as you 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;To assign a string to a variable, you must use quotes. You can choose 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 it only the first string that worked properly?", you might
ask. The answer is that when using double quotes, PHP performs what is known as
variable-expansion. That means that PHP expands (substitutes) $first_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 are not part of the string stored in $greeting1
).
When assigning to $greeting2
using single quotes, PHP doesn't
substitute any variables and $greeting2
ends up with "Hello,
my last name is $last_name.
".
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 would 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.
It's only when you're evaluating expressions (such as in assignments and echo statements) that the difference between single and double quotes comes into play. After the assignment is done, you wont be able to tell how the string was produced. Consider this code:
$first_name =
'Martin';
$last_name = "Geisler";
$var1 = "$first_name
$last_name";
$var2 = 'Martin
Geisler';
The two variables $var1 and $var2 will both contain the string Martin Geisler after the evaluation, without any sign of all the different kinds of quotes that were used in the construction and PHP will not make any distinction between the values stored in the two variables.
If you want to concatenate (add together) two strings you use the .
-character
(a 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";
When using variable substitution you might run into a little problem. The problem occurs when you want to substitute a variable in a string and have text immediately after the variable. You have to delimit the name of the variable somehow. Using curly braces is the solution as shown in this code:
$noun =
'car';
echo "A $noun, two ${noun}s";
Here we're playing with English words in plural form. The first occurrence of $noun is substituted correctly, even when it's followed immediately by a comma because you cannot have a comma in the name of a variable. But you could certainly have a variable called $nouns, so we have to use curly braces to indicate that we want the variable called $noun and not some nonexistent variable called $nouns.
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[0] = 'Martin'; $name[1] = 'Geisler';
(There's no syntax hightlighting in the above example because it involves square brackets with numbers in them, which is also used for footnotes in PhpWiki. So some of the following examples will be in plain black & white.)
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[0] . ' ' . $name[1];
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, numbered 0, 1, and 2. 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 together 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 the easiest way to deal with associative arrays. Another possibility is to use variable substitution with curly braces like this:
echo "Hello
{$personal_data['first
name']}! " .
"We know that
you are {$personal_data['age']}
years old.";
This code gives the same result. You can put complex expressions inside such a set of curly braces. This includes accessing elements in multidimensional arrays and object properties.
Please do use descriptive names for the slots in your arrays. It makes the code much more clear, and helps to indicate what the different slots are intended for.
Now that we have seen how to assign values to variables, let's have a look at the different control structures there are in PHP:
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.
if
-statementWe 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 braces, {...}
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 braces. 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 or both is true |
(Note: problems with the WikiMarkup;
you actually need to use || and not ¦¦ as the or
operator.)
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 tests to see if the variable $a
is smaller or equal to the variable $b
. If true, the next part is
executed to see if it is also true. This happens 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 whether the entire test is true, which it is, if either 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 as a Boolean expression. That means that it starts by
executing mysql_connect()
. If that returns true, then PHP skips the
next statement, because we used 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:
for
-loopThe for
-loop is useful when you need to have the same task
repeated a number of times. The for
-loop works by first
initializing a variable, then performing a test, and then - if the test is true
- executing some code. After that code hass been executed, additional code is run
to increment the variable and then execute the main code again. An example will
probably 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, let's have a look at the for
-loop.
It first assigns a starting-value of 0 to $i
, then it checks to
see if $i
is smaller than 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 statement is a shorthand of $i = $i + 1;
. It simply
increments the variable i
by 1. Similarly, you could write $n--
;
that would decrement the variable $n
by 1.
The main code is executed while $i
is less than 10, so our
little for
-loop simply prints the numbers from 0 to 9 into our
webpage.
while
-loopThe 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,
which 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.
Here is an example with reset()
and each()
that
will build a table that shows the keys and values of an array:
$array =
array('Foo' => 42,
'Bar'
=> 3.14,
'Baz'
=> 2.71);
// Start the table
echo "<table>\n";
// Print the first row with headers
echo "<tr>\n";
echo " <th>Key</th>\n";
echo " <th>Value</th>\n";
echo "</tr>\n";
// Ensure that the each() function starts from the
start:
reset($array);
while (list($key, $value)
= each($array))
{
// Print a single row
echo "<tr>\n";
echo "<td>$key</td>\n";
echo "<td>$value</td>\n";
echo "</tr>\n";
}
// End the table
echo "</table>\n";
This code will produce a table like this one:
Key | Value |
Foo | 42 |
Bar | 3.14 |
Baz | 2.71 |
The important thing for you to notice in the above code is the way HTML tables can be built up in PHP. Tables in HTML start with the opening tag, and then comes any number of rows, each row consists of any number of cells. Finally you close the table again.
So when building HTML tables using PHP, remember that they always start in the upper left-hand corner (the cell that says "Key" in this example) and then continue to the right along the same row: then come the rows below in the same way, left-to-right, until you finally end up in the lower right-hand corner (that's the cell that says "2.71" here).
Whenever you need to use a certain piece of code over and over again, it is very useful to put it in a function. By putting your code into functions, you make the code easy to reuse. Whenever you locate an error in your code, you only have to fix it once: in the function. Using functions also makes your code easier to read and understand, especially when you choose sensible names for functions. Let's start with a simple function:
function foo($arg)
{
if ($arg <
10) {
echo "$arg is smaller
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 (that's the bit between parenthesis called $arg above), and it echoes
different things, based on the value of that argument. You "call" the foo
function lower down the page, 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.
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.
Note that before we return the number, we could round it with the round()
-function,
which will round the number to an integer: more on round()
below!
In the body of the page you call into action that bar
function
like this :
$days_ages =
bar();
If instead you 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 smart_round
function returns $float
rounded to
$dec
decimals. The php-function:round
has been changed in recent versions of PHP to allow the use of that second,
precision, $dec
argument.
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: include()
can now
use a value returned from an external file, instead of calling a function
declared in the same file.
Let's look at this in action! We have the file foo.inc
which we
want to use within the file script.php
. This is the code for foo.inc
:
<?php
/* You must write the included files
within PHP,
in other words within <?php and ?> tags. This is because
the assumption is always made that
included files are not part of any PHP code. */
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.
Now that you've learned the basics of PHP, you should be able to write your own PHP-scripts