Scripts
- A file containing PHP code should
ordinarily have an extension
of .php
Shebang
- The first line must be one of the
following, to indicate
that the file is a PHP script:
#!/usr/bin/php
#!/usr/local/bin/php
#!/usr/bin/env php
- The shebang is required for running PHP
files as CGI scripts
- There's some controversy over which of
the above approaches is best
- To find out which location PHP is run
from on a given computer, type
"
which php"
PHP tags
<?php PHP_CODE ?>
- The preferred method
- Allows the use of PHP in XML-conformant
code such as XHTML
<? PHP_CODE ?>
- Not always available
- <?= expression ?> # Shortcut
version to echo an
expression
<script language="php"> PHP_CODE </script>
<% PHP_CODE %>
- Only available if ASP-style tags have
been enabled
- <%= $variable; %> # Shortcut
version to echo a
variable
Usage
- The closing tag automatically implies a
semicolon; the
last line of a PHP block does not have to be explictly terminated with
a
semicolon.
- The closing tag eats the end-of-line
character that follows
it.
Examples
<?php echo("text\n"); ?>
<? echo ("text\n"); ?>
<?= "text\n" ?>
<script language="php"> echo ("text\n"); </script>
<% echo ("text\n"); %>
<%= $variable; %>
Embedding PHP in html
- The PHP parser only executes code that's
within PHP tags; the
rest of the file is left as-is.
<?php
if ($expression) {
?>
<strong>This is true.</strong>
<?php
} else {
?>
<strong>This is false.</strong>
<?php
}
?>