When learning a new programming language, one of the first things we do is create a “Hello, World!” application. This simple program prints the famous string to the console. In this tutorial, we will guide you through the process of creating your first PHP program.
Before getting started, make sure you have MAMP running, and open the htdocs
folder as explained in the previous steps. For coding, we recommend using VS Code, a user-friendly code editor. If you are not familiar with VS Code, check out this introduction.
The code shown above generates the “Welcome to MAMP” page that you may have seen in your browser. However, for our first program, we need to replace it with the following code:
<?php
echo 'Hello World';
?>
Once you have replaced the code, save the file and refresh the page on http://localhost:8888. You should see the “Hello World” message displayed on the page.
Congratulations! You have successfully created your first PHP program.
Now, let’s take a closer look at what is happening in this program.
By default, the Apache HTTP server is configured to listen on port 8888
on localhost (your computer). When you access http://localhost:8888 in your browser, you are making an HTTP request for the content of the root URL (/
).
Apache is configured to serve the index.html
file included in the htdocs
folder for this route. However, since we have set up Apache to work with PHP, it will search for an index.php
file instead.
In our case, the index.php
file exists, and the PHP code is executed on the server before Apache sends the page back to the browser.
The <?php
opening tag indicates the beginning of a PHP code section, while the ?>
closing tag marks the end. Within these tags, we use the echo
statement to print the string “Hello World” within quotes.
Remember that in PHP, a semicolon is required at the end of each statement.
PHP allows us to embed code within HTML, effectively “decorating” an HTML page with dynamic data. However, in modern PHP development, it is common to use frameworks like Laravel to generate HTML separately from PHP code. This book focuses on plain PHP, so we will start with the basics.
For example, the code snippet below will produce the same result in the browser:
Hello
<?php
echo 'World';
?>
To the end-user, there is no visible difference between the two approaches.
It’s worth noting that although the page is technically an HTML page, it only contains the “Hello World” string. The browser can interpret this and display it as expected.