First PHP Script – Hello World


Getting started with PHP is simple and exciting. In this tutorial, you’ll write your very first PHP script and learn how PHP code is executed on a web server. The classic “Hello, World!” program is the standard way to start learning any new programming language, and PHP is no exception.

This guide is perfect for beginners learning PHP, and it includes essential tips on writing and running your first PHP file using XAMPP local server.



What is a PHP Script?

A PHP script is a block of code written in the PHP language. These scripts are executed on the server and return HTML output to the browser.

All PHP code must be enclosed within special tags:

<?php
  // PHP code goes here 
?>

Output

PHP is working!

The server identifies PHP code using the opening <?php and closing ?> tags. Anything written inside is processed by the PHP engine.


Setting Up Your First PHP File

Before writing your first script, make sure:

  • You have installed XAMPP or any PHP-enabled local server
  • Apache server is running via the XAMPP Control Panel


Step 1: Navigate to the htdocs Folder

In XAMPP, PHP files are placed inside the htdocs directory:
C:\xampp\htdocs\

Create a new folder named php-basics (optional) and open it.



Step 2: Create a New PHP File

Create a new text file using any code editor (e.g., VS Code, Notepad++) and name it:
hello.php
Make sure the file extension is .php.



Writing the "Hello, World!" Script in PHP

Open the hello.php file and write the following code:

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

Output

Hello, World!

Explanation:

  • <?php starts the PHP code
  • echo is a PHP statement that outputs data to the browser
  • "Hello, World!" is the text being printed
  • ; ends the statement (required in PHP)


Running the PHP Script in Your Browser

  • Open your browser
  • Type the following URL in the address bar:

    http://localhost/php-basics/hello.php

If you did everything correctly, you should see this message on the screen:

Hello, World!

This confirms that your PHP environment is set up and working properly.



PHP File vs HTML File: What’s the Difference?

  • PHP files are processed on the server and can contain logic (if statements, loops, etc.).
  • HTML files are static and displayed as-is in the browser.
  • You can embed PHP into HTML to make dynamic web pages.

Example of PHP embedded in HTML:

<!DOCTYPE html>
<html>
  <head>
     <title>My First PHP Page</title>
  </head>
  <body>
     <h1> <?php echo "Hello from PHP!"; ?> </h1>
  </body>
</html>

Output

Hello, World!


Best Practices for Writing PHP Scripts

  • Always use proper file extensions: .php
  • Save your files in the server’s root folder (htdocs)
  • Use echo or print to output content
  • Use a proper code editor for better syntax highlighting