PHP: Hello World!

Hello World!

In this tutorial, we will make our first PHP program called Hello World. This lesson builds on the PHP Lesson 0 tutorial; please read that if you have not done so.

First, go to C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\. This is the webroot for the Apache web server, from where all of your web pages will be served. There should be an index.html file in this folder. Open it using Notepad or another text editor. Remove all of the text in the file and replace it with this:


<?php echo("Hello World!"); ?>


Go to File —> Save As, and save it as index.php.

Now, we will walk through the code that we wrote in Lesson 0. In a PHP file, you can write anything you could normally put into an HTML file (HTML, CSS, javascript, etc.), but now you can also add PHP in code blocks. Look at this line:

<?php echo("Hello World!"); ?>

Whenever you want to write PHP code in a web file, start your code block with this tag:


and end it with this:


Inside, we call the function echo(). This function takes anything as a parameter—such as a string, integer, array, or object—and prints it out to the web page that the user sees. This time we have put the string "Hello World!" into the function, and as you'll see, that is exactly how it shows up in the web browser.

Now, open a web browser and type into the address bar: http://localhost and then hit Enter. You should see this:

Now, right-click on the web page and choose "View Source" or "View Page Source". The code that you see here is the output of the PHP file we wrote in Lesson 0. As you can see, our string "Hello World" has printed out here, but there is no PHP code. That is because PHP runs on the server before the web page gets sent to the user. So, the user never sees any PHP code in the web page, only the output of the code. That means if you want a user to see something in your PHP code such as a variable value, you have to print it out using echo() or another print function. We'll get deeper into this subject in another tutorial.

Now, let's go back and edit our index.php file again. This time, let's print out HTML tags with our PHP code. Replace this line of code:

<?php echo("Hello World!"); ?>

with this:

<?php echo("<h1>Hello World!</h1>"); ?>

Go back to the web browser and refresh your page. Right-click and choose "View Source" or "View Page Source". Now, you should see this line:

<h1>Hello World!</h1>

So, as you can tell, it is possible to print out an entire HTML page from inside a PHP code block. While this is usually fairly cumbersome, there are many instances when printing a piece of HTML is very useful. In effect, PHP files are a mixture of HTML and PHP.

Congratulations! You've made your first PHP program, "Hello World!".

If you have any questions or comments, please post them in our Forum.