"Hello World"

PHP files and How they Work

Basic Syntax

Now that you have a basic understanding of how the magic happens, you are ready for the fundamentals of writing PHP scripts.

Embedding PHP in HTML

You are almost ready to write your first PHP script, but before we move on to that, it is important that you understand how your PHP code and your HTML will relate to one another.

"Hello World"

You are now ready to write your first PHP script.

First, we should start off with an HTML document such as the following.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello world!</title>
</head>
<body>
<h1>This is going to be my first PHP script</h1>

</body>
</html>

The next step is to open a PHP block and start writing some PHP!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello world!</title>
</head>
<body>
<h1>This is going to be my first PHP script</h1>

<?php

/*
As discussed earlier, this is a comment. I will be using comments to describe what the PHP script is doing.

The first thing that we will do is use the echo function to output the message "hello world" in our document.
*/


echo ("Hello world!");

/*
In the parsed version of this document, the only thing that will appear in place of this PHP block is the text "Hello world!".

This is not the only way to print "Hello world!" however, we could use a variable instead.
*/


$hello = "Hello world, I love evil kittens!";

/*
The Variable $hello, now contains the string "Hello world, I love evil kittens!", we can output this string by passing the variable to the echo function in the same way that we passed the string earlier.
*/


echo ($hello);

/*
After the document is parsed, we should now see the following in place of the PHP block:

Hello world!Hello world, I love evil kittens! You can see this hello world file in action by clicking here.
*/


?>

</body>
</html>

Notice the lack of formatting in the text outputted by our PHP script. We can resolve this issue by modifying our echo statements to include html tags.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello world!</title>
</head>
<body>
<h1>This is going to be my second PHP script</h1>
<?php

echo ("<p>Hello world!</p>");
$hello = "<p>Hello world, I love evil kittens!</p>";
echo ($hello);

?>
</body>
</html>

Now our block of PHP script will be replaced by the two strings wrapped in paragraph tags. To see the difference, view this file.