As in all good tutorials, we start with the (in)famous “Hello World” 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
and upload it to your webserver. Then load the page in your browser.
If the page doesn’t say “Hello World!”, then try other extensions like
.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
This line informs Apache that files ending with
.php are PHP
scripts. Again, please refer to the installation instructions in the
PHP manual for
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
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 are two comments and one statement,
"Hello World!\n";. The comments will be completely ignored, and the
statement just prints the string “
Hello World” into the webpage,
followed by a newline. This is what is 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> </html>
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 Internet. 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` and `?>) the PHP-parsed spices the page
up with possibly dynamic content. You will need variables for dynamic
content, so go read about it now.