PHP Structure
July 21, 2000
All of the PHP code within one web page is considered to be one PHP
"script". You are free to break up the code into multiple
<?php ... ?> sections, as needed. For example, we might set a
variable containing today's date at the beginning of a page, which is
then used for output later in the page. Let's call our ongoing example
script worldpeace.php3. Note that PHP pages usually have the
filename extension .php3, as that is the default filename
that the web server will look for. This can be changed by reconfiguring
the web server.
worldpeace.php3:
<?php
$today=getdate(time());
?>
<H2>Today's Headline:</H2>
<P ALIGN="center">
<?php
print "World Peace Declared";
?>
</P><HR>
<!-- begin footer -->
<SMALL>Today is <?php
print $today[weekday];
?></SMALL>
We haven't yet discussed the PHP language itself, so let's focus on
structure for now. The above page contains a small section of PHP code,
which assigns a value to a variable $today. A second block of
PHP code in the middle of the page outputs our headline, and a third
block of PHP near the end of the page uses the $today variable
to output the day of the week. Given that today (the day I'm writing
this, not necessarily the day you're reading it!) is Wednesday, the
above code would produce the page:
Today's Headline:
World Peace Declared
Today is Wednesday |
Besides breaking up PHP code into multiple blocks, it is also possible
to include code from external files into your pages. Sometimes you
wish to keep bits of code in its own file -- for instance, HTML code
that makes up a repeating element such as a logo or footer, or PHP code
that makes up a function that you might want to use in several
different pages. Returning to the previous example, suppose we break
out the footer into its own file, and the initial PHP block into its
own file:
setdate.php3:
<?php
$today=getdate(time());
?>
footer.php3:
<!-- begin footer -->
<SMALL>Today is <?php
print $today[weekday];
?></SMALL>
Now, we can use PHP's include() function to pull the above
files into our example page:
<?php
include ("setdate.php3");
?>
<H2>Today's Headline:</H2>
<P ALIGN="center">
<?php
print "World Peace Declared";
?>
</P><HR>
<?php
include ("footer.php3"); ?>
The most common use for the include() function is, as seen
above, to reuse certain components across several pages. Of course,
your components will often contain much more code than the examples
seen here! Also notice that each component is treated as an HTML page
-- that is, it can contain HTML tags and any PHP code must appear
within the <?php ... ?> tags.
The Very Basics
Welcome to PHP
Scalar Variables and Data
|