In this series of tutorials, I’ll give you a little introduction to the PHP programming language, which is used to dynamically generating web pages. If you follow them all through, you’ll be able to understand and write PHP scripts, enabling you to do many powerful things.
We all have to start somewhere though, and no programming tutorial would be complete without a simple program to output ‘Hello World’.
So, assuming you’ve got access to a webserver with PHP (either on your local machine, or web hosting), create a file called hello.php and add the following code to it:
IF you load this page in a web browser, you should see get the following output:
Breaking it down
We’ll have a look at what each part of this does. First, the tags:
<?php tag which marks the start of some PHP code, and goes hand in hand with the tag at the end,
?>. These are similar to When you load this page in the browser, the server will treat everything between the
?> tags as PHP code. Everything outside these tags is just treated as text and will be printed to the browser, for example like HTML on any other webpage.
The only other part in this simple script is the line:
echo command says to send something to the browser as text. It’s followed by
'Hello World' - this is a string which is just text held in quotes (note that it is surrounded by single quotes
', although it could also have been surrounded by double quotes
An important point is that the line ends in a semicolon,
;. All lines of PHP code must end in a semicolon like this - you’ll get an error if you miss one out.
What does a visitor see?
Assuming everyhing works correctly, someone visiting this as a webpage in their browser won’t ever see the PHP code, even if they look at the source code of the page. This is because the PHP code is parsed and executed on the webserver, and what gets sent to a visitor is just the output of that code.
In this case, it’s just the line
That’s it - we use PHP tags,
?> to mark the start and end of PHP code in a page. The
echo command says to output something as text - in this case the string
'Hello World!'. And all lines of PHP code must end in a semicolon.
You can mix PHP code and text within a page, and even have multiple blocks of PHP code, each within their own sets of
?> tags. For example:
This produces the same output as above, namely
You can change this to print any text you like, for example:
The output of this is:
Purple Monkey Dishwasher