|
Opening & Ending PHP Tags
To open a block of PHP code in a page you can use one of these four sets
of opening and closing tags
| Opening Tag |
Closing Tag |
| <? |
?> |
| <?php |
?> |
| <% |
%> |
| <script language="php"> |
</script> |
The first pair (<? and ?>) is called
short tags. You should avoid using short tags in your application especially
if it's meant to be distributed on other servers. This is because short tags
are not always supported ( though I never seen any web host that don't support
it ). Short tags are only available only explicitly enabled setting the short_open_tag
value to On in the PHP configuration file php.ini.
So, for all PHP code in this website I will use the second pair, <?php
and ?>.
Now, for the first example create a file named hello.php
( you can use NotePad or your favorite text editor ) and put it in your web
servers root directory. If you use Apache the root directory is APACHE_INSTALL_DIR\htdocs,
with APACHE_INSTALL_DIR
is the directory where you install Apache. So if you install Apache on C:\Program
Files\Apache Group\Apache2\htdocs then you put hello.php in
C:\Program Files\Apache Group\Apache2\htdocs
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "<p>Hello World, How Are You Today?</p>";
?>
</body>
</html>
To view the result start Apache then open your browser and go to
http://localhost/hello.php
or http://127.0.0.1/hello.php.
The example above shows how to insert PHP code into an HTML file. It also
shows the echo statement used to output a string.
See that the echo statement ends with a semicolon.
Every command in PHP must end with a semicolon. If you forget to use semicolon
or use colon instead after a command you will get an error message like this
Parse error: parse error, unexpected ':', expecting
',' or ';' in c:\Apache\htdocs\examples\get.php on line 7
However in the hello.php example above omitting
the semicolon won't cause an error. That's because the echo
statement was immediately followed by a closing tag. |