Hello World on the web browser
Step 1: open the folder htdocs
under the xampp
folder. Typically, it locates at C:\xampp\htdocs
.
Step 2: create a new folder called helloworld
.
Step 3: create a new file called index.php
under the helloworld
folder and place the following code in the file:
1 2 3 4 5 6 7 8 9 10 11 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP - Hello, World!</title> </head> <body> <h1><?php echo 'Hello, World!'; ?></h1> </body> </html> |
The code in the index.php
file looks like a regular HTML document except the part <?php
and ?>
.
The code between the opening tag <?php
and closing tag ?>
is PHP:
1 | <?php echo 'Hello, World!'; ?> |
This PHP code prints out the Hello, World
message inside the h1
tag using the echo
statement:
When PHP executes the index.php
file, it evaluates the code and returns the Hello, World!
message.
Step 4: launch a web browser and open the URL:
1 | http://localhost:8080/helloworld/ |
If you see the following on the web browser, then you’ve successfully executed the first PHP script:
If you view the soure code of the page, you’ll see the following HTML code:
1 2 3 4 5 6 7 8 9 10 11 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP - Hello, World!</title> </head> <body> <h1>Hello, World!</h1> </body> </html> |
Hello World on the command line
Step 1: open the Command Prompt on Windows or Terminal on macOS or Linux.
Step 2: navigate to the folder c:\xampp\htdocs\helloworld\.
Step 3: type the following command to execute the index.php file:
1 | c:\xampp\htdocs\helloworld>php index.php |
You’ll see the HTML output:
1 2 3 4 5 6 7 8 9 | <html lang="en"> <head> <meta charset="UTF-8"> <title>PHP - Hello, World!</title> </head> <body> <h1>Hello, World!</h1> </body> </html> |
To simplify the output, you can use the following code in the index.php
:
1 2 3 | <?php echo 'Hello, World!'; |
If you execute the script again:
1 | c:\xampp\htdocs\helloworld>php index.php |
and you’ll see the following output:
1 | Hello, World! |
When you embed PHP code with HTML, you need to have the opening tag <?php
and closing tag ?>
. However, if the file contains only PHP code, you don’t need to the closing tag ?>
like the index.php
above.