The code itself fits right inside a page's HTML, and like HTML it is
made up of plain ol' text. So a page that displays the words "I am the
CHICKEN MAN!" message would sit inside an HTML page
named something.php, like this:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20. |
<html>
<head>
<title> Chicken Man Example </title>
</head>
<body>
<font color="red">My PHP code makes this page say:</font>
<p>
<?php
print ("I am the CHICKEN MAN");
?>
</body>
</html>
|
See how that works? The HTML is rendered as regular HTML, but everything
inside the <?php and ?> tags gets processed as PHP.
Basic Syntax
It's time to write your own first PHP script. The basic rules of PHP are
as follows:
Naming Files
In order to get a PHP script working, the file it's in or the file that
it calls to do the heavy lifting must end in .php (earlier versions
used the file extensions .php3 and .phtml). Like HTML, your files are saved
as plain text.
Comments
It's important to get in the habit of leaving notes about your code with the comment tags so that months down the road you can make sense of what you were trying to make your script do. The way you set comments apart from your code (that you don't want displayed
or executed) is with either "//" at the beginning of each line, or
surrounded by "/*" and "*/" if you want to comment out
several lines:
<?php
// This will be ignored. Note to self:
// Pick up ice cream, cake, and balloons.
print ("I am the CHICKEN MAN");
/*
This, too, will be ignored.
Hey, and don't forget
the spanking machine!
*/
?>
Code Syntax
Start of Code
Every piece of PHP code begins with "<?php"
(or the abbreviated "<?" if your server is configured to handle
that).
End of Code
The way to signify that the PHP code is finished is by adding "?>" at the end.
Every Chunk
With a few exceptions, each separate instruction that you
write will end with a semicolon.
Parentheses
The typical function looks like this ...
print ( );
... where "print" is the function and the stuff that the function
works on sits inside the parentheses, with a semicolon to finish it off.
(Just to confuse you, "print" is the exception that also works
without parentheses.) By the way, echo () is the same as print ().
Much like HTML, the actual formatting of your PHP code (where you put
spaces, line breaks, etc.) will not affect the outcome except those parts of the
code that tell a Web browser how to display your page. So this piece of
code ...
<?php
print ("I am the CHICKEN MAN");
?>
... is effectively identical to:
<?php print ("I am the CHICKEN MAN"); ?>
Like more complicated HTML, it behooves you to use white space and tabs
in your code to make the code more understandable. (Behoove you too, pal!)
Capisce? Ready to write your first script? Let's go.
next page»