• PHP Video Tutorials

PHP - Hello World



Conventionally, learners write a "Hello World" program as their first program when learning a new language or a framework. The objective is to verify if the software to be used has been installed correctly and is working as expected. To run a Hello World program in PHP, you should have installed the Apache server along with PHP module on the operating system you are using.

PHP is a server-side programming language. The PHP code must be available in the document root of the web server. The web server document root is the root directory of the web server running on your system. The documents under this root are accessible to any system connected to the web server (provided the user has permissions). If a file is not under this root directory, then it cannot be accessed through the web server.

In this tutorial, we are using XAMPP server software for writing PHP code. The default document root directory is typically "C:\xampp\htdocs\" on Windows and "/opt/lamp/htdocs/" on Linux. However, you can change the default document root by modifying the DocumentRoot setting in Apache server’s configuration file "httpd.conf".

While on a Windows operating system, start the Apache server from the XAMPP control panel.

PHP Hello World

Browse to the "htdocs" directory. Save the following script as "hello.php" in it.

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

Open a new tab in your browser and enter http://localhost/hello.php as the URL. You should see the "Hello World" message in the browser window.

A PHP script may contain a mix of HTML and PHP code.

<!DOCTYPE html>
<html>
<body>
   <h1>My PHP Website</h1>
   <?php
      echo "Hello World!";
   ?>
</body>
</html>

The "Hello World" message will be rendered as a plain text. However, you can put HTML tags inside the "Hello World" string. The browser will interpret the tags accordingly.

In the following code, the "echo" statement renders "Hello World" so that it is in <h1> heading with the text aligned at the center of the page.

<!DOCTYPE html>
<html>
<head>
   <title>My PHP Website</title>
</head>
<body>
   <?php
      echo "<h1 align='center'>Hello World!</h1>";
   ?>
</body>
</html>

PHP Script from Command Prompt

You can run your PHP script from the command prompt. Let's assume you have the following content in your "hello.php" file.

<?php
   echo "Hello PHP!!!!!";
?>

Add the path of the PHP executable to your operating system’s path environment variable. For example, in a typical XAMPP installation on Windows, the PHP executable "php.exe" is present in "c:\xampp\php" directory. Add this directory in the PATH environment variable string.

Now run this script as command prompt −

C:\xampp\htdocs>php hello.php

You will get the following output −

Hello PHP!!!!!
Advertisements