In the previous tutorials about working environments, we have shown that PHP is a dynamic scripting language precompiled and interpreted on the server side. It is now up to us to realize our first programs and to execute them on the Web server (local or remote).

In computer programming, there is a “tradition” to generate the string Hello World! on the standard output (in our case it is a computer screen). So let’s start with the very first script presented below.

Your first PHP script

Copy the following code into a text editor (Notepad, Wordpad or Notepad++ will do the trick) and save this file with the name hello_world_basic.php.

Note: all files with PHP code must be saved with the extension .php (or .phpX where X is the PHP version number).

<?php echo 'Hello World !'; ?>

Run this first script in a web browser (Safari, Firefox, Opera, Internet Explorer…). You can see that the text Hello World! is displayed on the screen. So we get the result we expected at the beginning. Let’s move on to the explanations.

Details :

First of all the tags. Any PHP script must be surrounded by two tags to delimit it from another type of content found in the same file (HTML code for example). Here we use the tags. There are others but they are strongly discouraged to use. If you want to know what they are and why you should not use them, we invite you to consult the following tutorial: Why it is not advisable to use short tags.

In any case, you should always use the tags in this first program. This is THE first good practice to adopt when coding in PHP.

The second part of the code is what we call in programming a statement. The echo() function (or rather the language structure because it is a particular function of PHP) is in charge of writing what is passed as a parameter to the standard output. Here the parameter is a string (type) whose value is “Hello World!

Improving the Hello World

So far, nothing difficult. Let’s go to the next level. We will generate our Hello World! in the middle of an HTML document. Here is the code of the hello_2.php file:

<!DOCTYPE html>
<html>
<head>
<title>Your hello world</title>
</head>

<body>
<?php echo 'Hello World !'; ?>
</body>

</html>