How to Run Your First PHP Program with XAMPP and Visual Studio Code
Last update: 12-17-2024
Are you ready to dive into PHP programming? This guide will walk you through setting up your environment and running your very first PHP program. We'll use Visual Studio Code as our code editor and XAMPP to set up a local web server. Let’s get started!
Step 1: Setting Up the Environment
Before we write any PHP code, we need to set up the tools to run it. Here’s how:
1. Download and Install XAMPP
XAMPP is an open-source web server package that allows you to build and test websites on a local server. The name stands for:
- X: Cross-platform
- A: Apache (the web server)
- M: MariaDB (the database)
- P: PHP
- P: Perl
To get started:
- Visit https://www.apachefriends.org/download.html.
- Find the "XAMPP for Windows" section.
- You’ll see multiple versions available. Opt for the latest version, usually listed at the bottom of the section.
- Once the XAMPP download is complete, open the installer.
- If a warning appears, click Yes to continue.
- Choose the default installation folder (
C:\xampp
) and click Next. - Wait for the installation to finish, then click Finish to launch the XAMPP Control Panel.
2. Start XAMPP
To start the server:
- Open the XAMPP Control Panel.
- Click Start for both Apache and MySQL.
- To verify the installation, open your browser and type
localhost
. If XAMPP is installed correctly, the dashboard will appear.
3. Download and Install Visual Studio Code
Visual Studio Code (VS Code) is a powerful and lightweight code editor. To download:
- Go to https://code.visualstudio.com/Download.
- Download the version for Windows.
- Follow the straightforward installation steps — just click Next until the installation is complete.
Step 2: Writing Your First PHP Program
1. Navigate to the htdocs Folder
All PHP files must be stored in the htdocs
folder for XAMPP to process them:
- Go to
C:\xampp
and locate thehtdocs
folder. - Create a new folder inside
htdocs
and name itfirstphp
.
2. Create Your PHP File
Let’s create a file named index.php
. This file will load by default when you access the folder in a browser:
- Open Visual Studio Code.
- Click Open Folder and navigate to
C:\xampp\htdocs\firstphp
. - Create a new file inside the folder and name it
index.php
. Ensure the extension is.php
.
3. Write the PHP Code
Open index.php
and add the following code:
<!DOCTYPE html>
<html>
<head>
<title>My First PHP Webpage</title>
</head>
<body>
<h2>My First PHP Webpage</h2>
<?php
echo "Hello, World!";
?>
</body>
</html>
4. Run Your PHP Program
To view your program in action:
- Open your browser.
- Type
http://localhost/firstphp
in the address bar. - You should see the heading and the text Hello, World!.
Conclusion
Congratulations! You’ve successfully set up a PHP development environment and run your first PHP program. You’re now ready to explore more complex PHP features. Happy coding!