Your Local PHP Laboratory
Because PHP is a server-side language, you can't just open a .php
file in your browser like you do with an HTML file. Your code needs to be processed by a server before it can be displayed. To do this on your own computer, we need to set up a local development environment.
This environment mimics a live web server and typically consists of three key components known as a "stack":
- Apache: The web server software that listens for requests from your browser.
- MySQL (or MariaDB): The database system where you'll store your application's data.
- PHP: The language interpreter that processes your PHP code.
Introducing XAMPP
The easiest way for a beginner to install this entire stack is by using a free, all-in-one package called XAMPP. XAMPP bundles Apache, MariaDB (a popular fork of MySQL), PHP, and other useful tools into a single, easy-to-install application for Windows, macOS, and Linux.
Step 1: Download XAMPP
Go to the official Apache Friends website to download XAMPP. Make sure you download a version that includes a modern version of PHP (PHP 8.2 or higher).
Step 2: Install XAMPP
Run the installer you downloaded. The process is straightforward, and you can generally accept the default settings. On Windows, you might see a warning about User Account Control (UAC); it's usually safe to click "OK" and continue. It's recommended to install XAMPP in the default location (e.g., C:\xampp
).
Step 3: The XAMPP Control Panel
Once installed, open the XAMPP Control Panel. This is your command center for your local server. You will see a list of modules. For our purposes, we only need two:
- Find the Apache module and click the "Start" button. It should turn green.
- Find the MySQL module and click the "Start" button. It should also turn green.
Congratulations, your local server is now running!
Running Your First PHP Script
Now that your server is running, let's write and execute your first line of PHP code.
- Navigate to the `htdocs` folder: This is the "web root" directory for your server. Any file you place here can be accessed through your browser. The typical location is
C:\xampp\htdocs
. - Create a Project Folder: Inside `htdocs`, create a new folder for our course. Let's name it
php-course
. - Create a PHP File: Open your code editor (like VS Code or Sublime Text), create a new file, and type the following code:
<?php echo "<h1>Hello from my local server!</h1>"; ?>
- Save the File: Save this file as
hello.php
inside yourphp-course
folder. - View in Your Browser: Open your web browser (like Chrome or Firefox) and navigate to the following URL:
http://localhost/php-course/hello.php
If you see the message "Hello from my local server!" displayed on the page, you have successfully set up your environment and run your first PHP script. Excellent work!